Skip to main content

js_component_bindgen/
function_bindgen.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt::Write;
3use std::mem;
4
5use heck::{ToLowerCamelCase, ToUpperCamelCase};
6use wasmtime_environ::component::{
7    InterfaceType, ResourceIndex, RuntimeCallbackIndex, RuntimeComponentInstanceIndex,
8    RuntimeMemoryIndex, RuntimeReallocIndex, TypeComponentLocalErrorContextTableIndex,
9    TypeFutureTableIndex, TypeResourceTableIndex, TypeStreamTableIndex,
10};
11use wit_bindgen_core::abi::{Bindgen, Bitcast, Instruction};
12use wit_component::StringEncoding;
13use wit_parser::abi::WasmType;
14use wit_parser::{
15    Alignment, ArchitectureSize, Handle, Resolve, SizeAlign, Type, TypeDef, TypeDefKind, TypeId,
16};
17
18use crate::intrinsics::Intrinsic;
19use crate::intrinsics::component::ComponentIntrinsic;
20use crate::intrinsics::conversion::ConversionIntrinsic;
21use crate::intrinsics::js_helper::JsHelperIntrinsic;
22use crate::intrinsics::lift::LiftIntrinsic;
23use crate::intrinsics::p3::async_future::AsyncFutureIntrinsic;
24use crate::intrinsics::p3::async_stream::AsyncStreamIntrinsic;
25use crate::intrinsics::p3::async_task::AsyncTaskIntrinsic;
26use crate::intrinsics::resource::ResourceIntrinsic;
27use crate::intrinsics::string::StringIntrinsic;
28use crate::{ManagesIntrinsics, get_thrown_type, source};
29use crate::{uwrite, uwriteln};
30
31/// Method of error handling
32#[derive(Debug, Clone, PartialEq)]
33pub enum ErrHandling {
34    /// Do no special handling of errors, requiring users to return objects that represent
35    /// errors as represented in WIT
36    None,
37    /// Require throwing of result error objects
38    ThrowResultErr,
39    /// Catch thrown errors and convert them into result<t,e> error variants
40    ResultCatchHandler,
41}
42
43impl ErrHandling {
44    fn to_js_string(&self) -> String {
45        match self {
46            ErrHandling::None => "none".into(),
47            ErrHandling::ThrowResultErr => "throw-result-err".into(),
48            ErrHandling::ResultCatchHandler => "result-catch-handler".into(),
49        }
50    }
51}
52
53/// Data related to a given resource
54#[derive(Clone, Debug, PartialEq)]
55pub enum ResourceData {
56    Host {
57        tid: TypeResourceTableIndex,
58        rid: ResourceIndex,
59        component_idx: RuntimeComponentInstanceIndex,
60        needs_task_context: bool,
61        local_name: String,
62        dtor_name: Option<String>,
63    },
64    Guest {
65        resource_name: String,
66        prefix: Option<String>,
67        extra: Option<ResourceExtraData>,
68    },
69}
70
71#[derive(Clone, Debug, PartialEq)]
72pub struct PayloadTypeMetadata {
73    pub(crate) ty: Type,
74    pub(crate) iface_ty: InterfaceType,
75    /// JS expression that serves as a function that lifts a given type
76    pub(crate) lift_js_expr: String,
77    /// JS expression that serves as a function that lowers a given type
78    pub(crate) lower_js_expr: String,
79    pub(crate) size32: u32,
80    pub(crate) align32: u32,
81    pub(crate) flat_count: Option<u8>,
82}
83
84/// Supplemental data kept along with [`ResourceData`]
85#[derive(Clone, Debug, PartialEq)]
86pub enum ResourceExtraData {
87    Stream {
88        table_idx: TypeStreamTableIndex,
89        elem_ty: Option<PayloadTypeMetadata>,
90    },
91    Future {
92        table_idx: TypeFutureTableIndex,
93        elem_ty: Option<PayloadTypeMetadata>,
94        nesting_level: u32,
95    },
96    ErrorContext {
97        table_idx: TypeComponentLocalErrorContextTableIndex,
98    },
99}
100
101/// Map used for resource function bindgen within a given component
102///
103/// Mapping from the instance + resource index in that component (internal or external)
104/// to the unique global resource id used to key the resource tables for this resource.
105///
106/// The id value uniquely identifies the resource table so that if a resource is used
107/// by n components, there should be n different indices and spaces in use. The map is
108/// therefore entirely unique and fully distinct for each instance's function bindgen.
109///
110/// The second bool is true if it is an imported resource.
111///
112/// For a given resource table id {x}, with resource index {y} the local variables are assumed:
113/// - handleTable{x}
114/// - captureTable{y} (rep to instance map for captured imported tables, only for JS import bindgen, not hybrid)
115/// - captureCnt{y} for assigning capture rep
116///
117/// For component-defined resources:
118/// - finalizationRegistry{x}
119///
120/// handleTable internally will be allocated with { rep: i32, own: bool } entries
121///
122/// In the case of an imported resource tables, in place of "rep" we just store
123/// the direct JS object being referenced, since in JS the object is its own handle.
124///
125#[derive(Clone, Debug, PartialEq)]
126pub struct ResourceTable {
127    /// Whether a resource was imported
128    ///
129    /// This should be tracked because imported types cannot be re-exported uniquely (?)
130    pub imported: bool,
131
132    /// Data related to the actual resource
133    pub data: ResourceData,
134}
135
136/// A mapping of type IDs to the resources that they represent
137pub type ResourceMap = BTreeMap<TypeId, ResourceTable>;
138
139#[derive(bon::Builder)]
140#[non_exhaustive]
141pub struct FunctionBindgen<'a> {
142    /// Skip task management for generated function calls. Defaults to `false`.
143    ///
144    /// This is normally used by embedders when they want to run generated bindings
145    /// inside a wasm guest and let the native embedding manage execution and
146    /// canonical abi call lifetimes instead of the host task runtime.
147    #[builder(default)]
148    pub skip_fn_call_task_management: bool,
149
150    /// Mapping of resources for types that have corresponding definitions locally
151    pub resource_map: &'a ResourceMap,
152
153    /// Whether current resource borrows need to be deactivated
154    pub clear_resource_borrows: bool,
155
156    /// Set of intrinsics
157    pub intrinsics: &'a mut BTreeSet<Intrinsic>,
158
159    /// Whether to perform valid lifting optimization
160    pub valid_lifting_optimization: bool,
161    /// Whether WIT flags are represented as bigint values.
162    #[builder(default)]
163    pub flags_as_bigint: bool,
164    /// Whether WIT enum values use SCREAMING_SNAKE_CASE strings.
165    #[builder(default)]
166    pub enum_values_screaming_snake_case: bool,
167
168    /// Sizes and alignments for sub elements
169    pub sizes: &'a SizeAlign,
170
171    /// Method of error handling
172    pub err: ErrHandling,
173
174    /// Temporary values
175    pub tmp: usize,
176
177    /// Source code of the function
178    pub src: source::Source,
179
180    /// Block storage
181    pub block_storage: Vec<source::Source>,
182
183    /// Blocks of the function
184    pub blocks: Vec<(String, Vec<String>)>,
185
186    /// Parameters of the function
187    pub params: Vec<String>,
188
189    /// Memory variable
190    pub memory: Option<&'a String>,
191
192    /// Realloc function name
193    pub realloc: Option<&'a String>,
194
195    /// Synchronous deallocator for owned canonical ABI buffers.
196    pub dealloc: Option<&'a String>,
197
198    /// Post return function name
199    pub post_return: Option<&'a String>,
200
201    /// Prefix to use when printing tracing information
202    pub tracing_prefix: &'a String,
203
204    /// Whether tracing is enabled
205    pub tracing_enabled: bool,
206
207    /// Whether top-level result errors should be thrown as their raw lifted payload.
208    pub no_component_error_wrapping: bool,
209
210    /// Method if string encoding
211    pub encoding: StringEncoding,
212
213    /// Callee of the function
214    pub callee: &'a str,
215
216    /// Whether the callee is dynamic (i.e. has multiple operands)
217    pub callee_resource_dynamic: bool,
218
219    /// The [`wit_bindgen::Resolve`] containing extracted WIT information
220    pub resolve: &'a Resolve,
221
222    /// Whether the function requires async porcelain
223    ///
224    /// In the case of an import this likely implies the use of JSPI
225    /// and in the case of an export this is simply code generation metadata.
226    pub requires_async_porcelain: bool,
227
228    /// Whether the function is guest async lifted (i.e. WASI P3)
229    pub is_async: bool,
230
231    /// Whether the canonical ABI call itself is async.
232    ///
233    /// This can differ from `is_async` when an async component function is
234    /// canonically lifted from a synchronous core function.
235    pub canonical_abi_async: bool,
236    /// Whether the component-level function type is `async` (independently of
237    /// how it was lifted or lowered)
238    pub func_type_async: bool,
239    /// The interned index of the result tuple type of an exported function,
240    /// which `task.return` must match
241    pub return_result_type_idx: Option<u32>,
242
243    /// Whether an async export returning a future needs a non-async outer
244    /// function to preserve the future as a distinct awaitable layer.
245    pub wrap_async_future_result: bool,
246
247    /// Component result type, used to lift callbackless async core returns.
248    pub result_ty: Option<&'a Type>,
249
250    /// Interface name
251    pub iface_name: Option<&'a str>,
252
253    /// Whether the callee was transpiled from Wasm to JS (asm.js) and thus needs shimming for i64
254    pub asmjs: bool,
255
256    /// Component state generated from processing a component.
257    ///
258    /// This information is normally accessible via producing/having
259    /// access to a [`wasmtime_environ::component::Component`]), and
260    /// is required for *some* bindgen instructions.
261    ///
262    /// If you are performing bindgen aganist a dummy module, you may omit this field, but if
263    /// processing has been performed on the component, and this state is available at time of generation for
264    /// this function, provide this information (normally found in [`CanonicalOptions`]s)
265    ///
266    pub component_state: Option<FunctionBindgenComponentState>,
267
268    /// Whether the bindgen is being performed for an import
269    /// (false implies generation is being performed for an export)
270    pub(crate) for_import: Option<bool>,
271}
272
273/// Metadata that is derived from processing a component.
274///
275/// This information is often required to perform bindgen completely, *but*
276/// requires component processing which not all downstream bindgen consumers may
277/// perform.
278///
279/// For bindgen consumers that perform generation which requires this information,
280/// the information should be provided.
281///
282#[derive(bon::Builder)]
283#[non_exhaustive]
284pub struct FunctionBindgenComponentState {
285    pub(crate) component_idx: RuntimeComponentInstanceIndex,
286    pub(crate) realloc_fn_idx: Option<RuntimeReallocIndex>,
287    pub(crate) memory_idx: Option<RuntimeMemoryIndex>,
288    pub(crate) callback_fn_idx: Option<RuntimeCallbackIndex>,
289}
290
291/// JS expressions that resolve to or return component state
292#[derive(bon::Builder)]
293#[non_exhaustive]
294pub struct ComponentStateJsExprs {
295    /// JS expression that is a number, e.g. "0"
296    pub(crate) component_idx: String,
297    /// JS expression that is the generated name of the callback, e.g. "callback_1"
298    pub(crate) callback_fn_name: String,
299    /// JS function expression that returns the callback function for this function, e.g. "() => callback_1"
300    pub(crate) get_callback_fn: String,
301    /// JS expression that is the index of the top-level declared memory associated with this function, e.g. "1"
302    pub(crate) memory_idx: String,
303    /// JS function expression that returns the top-level declared memory associated with this function, e.g. "() => memory0"
304    pub(crate) get_memory_fn: String,
305    /// JS function expression that returns the realloc fn relevant to this function, e.g. "() => realloc0"
306    pub(crate) get_realloc_fn: String,
307}
308
309impl FunctionBindgenComponentState {
310    /// Get JS expressions that represent the bindgen state
311    ///
312    /// When certain values are missing either `null` or `() => null` JS expressions are returned
313    ///
314    fn get_js_exprs(&self) -> ComponentStateJsExprs {
315        ComponentStateJsExprs {
316            component_idx: self.component_idx.as_u32().to_string(),
317            callback_fn_name: match self.callback_fn_idx {
318                Some(idx) => format!("callback_{}", idx.as_u32()),
319                None => "null".into(),
320            },
321            get_callback_fn: match self.callback_fn_idx {
322                Some(idx) => format!("() => callback_{}", idx.as_u32()),
323                None => "() => null".into(),
324            },
325            memory_idx: match self.memory_idx {
326                Some(idx) => idx.as_u32().to_string(),
327                None => "null".into(),
328            },
329            get_memory_fn: match self.memory_idx {
330                Some(idx) => format!("() => memory{}", idx.as_u32()),
331                None => "() => null".into(),
332            },
333            get_realloc_fn: match self.realloc_fn_idx {
334                Some(idx) => format!("() => realloc{}", idx.as_u32()),
335                None => "undefined".into(),
336            },
337        }
338    }
339}
340
341/// Returns whether an `ok`/`err` tagged object can unambiguously be interpreted
342/// as an explicitly wrapped result returned by a host import.
343///
344/// Hosts have historically returned the raw success payload, so that
345/// interpretation takes precedence whenever the payload itself can have the
346/// corresponding tag.
347fn unambiguous_result_wrapper_tags(resolve: &Resolve, ty: Option<&Type>) -> (bool, bool) {
348    let Some(ty) = ty else {
349        return (true, true);
350    };
351    let Type::Id(id) = ty else {
352        return (true, true);
353    };
354
355    match &resolve.types[crate::dealias(resolve, *id)].kind {
356        TypeDefKind::Variant(variant) => (
357            !variant.cases.iter().any(|case| case.name == "ok"),
358            !variant.cases.iter().any(|case| case.name == "err"),
359        ),
360        TypeDefKind::Result(_) => (false, false),
361        TypeDefKind::Record(record) => {
362            let unambiguous = !record.fields.iter().any(|field| field.name == "tag");
363            (unambiguous, unambiguous)
364        }
365        TypeDefKind::Flags(flags) => {
366            let unambiguous = !flags.flags.iter().any(|flag| flag.name == "tag");
367            (unambiguous, unambiguous)
368        }
369        TypeDefKind::Option(payload) => unambiguous_result_wrapper_tags(resolve, Some(payload)),
370        _ => (true, true),
371    }
372}
373
374fn instruction_requires_task_runtime(inst: &Instruction<'_>) -> bool {
375    matches!(
376        inst,
377        Instruction::CallInterface { async_: true, .. }
378            | Instruction::AsyncTaskReturn { .. }
379            | Instruction::FutureLift { .. }
380            | Instruction::FutureLower { .. }
381            | Instruction::StreamLift { .. }
382            | Instruction::StreamLower { .. }
383            | Instruction::ErrorContextLift
384            | Instruction::ErrorContextLower
385    )
386}
387
388impl FunctionBindgen<'_> {
389    fn validate_task_management(&self) {
390        if !self.skip_fn_call_task_management {
391            return;
392        }
393        assert!(
394            !self.is_async && !self.canonical_abi_async && !self.wrap_async_future_result,
395            "Skipping task management requires the synchronous canonical ABI"
396        );
397        assert!(
398            !self.asmjs,
399            "Skipping task management does not support asm.js"
400        );
401        assert!(
402            self.resource_map
403                .values()
404                .all(|table| matches!(table.data, ResourceData::Guest { extra: None, .. })),
405            "Skipping task management requires guest resource tables without async metadata"
406        );
407    }
408
409    fn tmp(&mut self) -> usize {
410        let ret = self.tmp;
411        self.tmp += 1;
412        ret
413    }
414
415    fn intrinsic(&mut self, intrinsic: Intrinsic) -> String {
416        self.intrinsics.insert(intrinsic);
417        intrinsic.name().to_string()
418    }
419
420    // Task-only templates may be built unconditionally, but must only be emitted
421    // when task management is enabled.
422    fn task_intrinsic(&mut self, intrinsic: Intrinsic) -> String {
423        if !self.skip_fn_call_task_management {
424            self.intrinsic(intrinsic)
425        } else {
426            intrinsic.name().to_string()
427        }
428    }
429
430    fn emit_dealloc(&mut self, ptr: &str, len: &str, size: usize, align: usize) {
431        let Some(dealloc) = self.dealloc else {
432            return;
433        };
434        if size == 0 {
435            return;
436        }
437        let byte_size = if size == 1 {
438            len.to_string()
439        } else {
440            format!("{len} * {size}")
441        };
442        uwriteln!(
443            self.src,
444            "if ({len} !== 0) {dealloc}({ptr}, {byte_size}, {align});"
445        );
446    }
447
448    fn emit_list_bounds_check(&mut self, ptr: &str, len: &str, element_size: usize) {
449        const MAX_LIST_BYTE_LENGTH: usize = (1 << 28) - 1;
450
451        let memory = self.memory.as_ref().unwrap().to_string();
452        let runtime_error = self.intrinsic(Intrinsic::WebAssemblyRuntimeError);
453        if let Some(max_elements) = MAX_LIST_BYTE_LENGTH.checked_div(element_size) {
454            uwriteln!(
455                self.src,
456                "if ({ptr} < 0 || {len} < 0 || {len} > {max_elements} || {ptr} > {memory}.buffer.byteLength || {len} > Math.floor(({memory}.buffer.byteLength - {ptr}) / {element_size})) throw new {runtime_error}('wasm trap: out of bounds memory access');"
457            );
458        } else {
459            uwriteln!(
460                self.src,
461                "if ({ptr} < 0 || {len} < 0 || {ptr} > {memory}.buffer.byteLength) throw new {runtime_error}('wasm trap: out of bounds memory access');"
462            );
463        }
464    }
465
466    fn emit_guest_dealloc(&mut self, ptr: &str, len: &str, size: usize, align: usize) {
467        if size == 0 {
468            return;
469        }
470        assert!(
471            self.dealloc.is_some(),
472            "guest deallocation requires a dealloc function"
473        );
474        self.emit_dealloc(ptr, len, size, align);
475    }
476
477    fn emit_dealloc_list_or_map(&mut self, operands: &[String], size: usize, align: usize) {
478        let (body, results) = self.blocks.pop().unwrap();
479        assert!(results.is_empty());
480        if size == 0 {
481            return;
482        }
483
484        let tmp = self.tmp();
485        let ptr = format!("ptr{tmp}");
486        let len = format!("len{tmp}");
487        uwriteln!(self.src, "const {ptr} = ({}) >>> 0;", operands[0]);
488        uwriteln!(self.src, "const {len} = ({}) >>> 0;", operands[1]);
489        if !body.is_empty() {
490            uwriteln!(
491                self.src,
492                "for (let i = 0; i < {len}; i++) {{
493                    const base = {ptr} + i * {size};
494                    {body}
495                }}"
496            );
497        }
498        self.emit_guest_dealloc(&ptr, &len, size, align);
499    }
500
501    fn lift_callbackless_async_result(&mut self) -> Option<(String, String)> {
502        if !self.is_async || self.for_import.unwrap_or_default() {
503            return None;
504        }
505
506        let Type::Id(id) = self.result_ty? else {
507            return None;
508        };
509        let type_id = crate::dealias(self.resolve, *id);
510        let resource = self.resource_map.get(&type_id)?;
511        let (lift_intrinsic, table_idx, table_field) = match resource {
512            ResourceTable {
513                imported: true,
514                data:
515                    ResourceData::Guest {
516                        extra: Some(ResourceExtraData::Future { table_idx, .. }),
517                        ..
518                    },
519            } => (
520                LiftIntrinsic::LiftFlatFuture,
521                table_idx.as_u32(),
522                "futureTableIdx",
523            ),
524            ResourceTable {
525                imported: true,
526                data:
527                    ResourceData::Guest {
528                        extra: Some(ResourceExtraData::Stream { table_idx, .. }),
529                        ..
530                    },
531            } => (
532                LiftIntrinsic::LiftFlatStream,
533                table_idx.as_u32(),
534                "streamTableIdx",
535            ),
536            _ => return None,
537        };
538
539        let component_idx = self
540            .component_state
541            .as_ref()
542            .map(|state| state.get_js_exprs().component_idx)
543            .unwrap_or_else(|| "-1".into());
544        let lift_fn = self.intrinsic(Intrinsic::Lift(lift_intrinsic));
545        let result_var = format!("directAsyncResult{}", self.tmp());
546        let code = format!(
547            r#"
548              const [{result_var}] = {lift_fn}({{
549                  {table_field}: {table_idx},
550                  componentIdx: {component_idx},
551              }})({{
552                  componentIdx: {component_idx},
553                  params: [ret],
554                  useDirectParams: true,
555                  isBorrowed: false,
556              }});
557            "#,
558        );
559        Some((code, result_var))
560    }
561
562    fn clamp_guest<T>(&mut self, results: &mut Vec<String>, operands: &[String], min: T, max: T)
563    where
564        T: std::fmt::Display,
565    {
566        let clamp = self.intrinsic(Intrinsic::ClampGuest);
567        results.push(format!("{}({}, {}, {})", clamp, operands[0], min, max));
568    }
569
570    fn load(
571        &mut self,
572        method: &str,
573        offset: ArchitectureSize,
574        operands: &[String],
575        results: &mut Vec<String>,
576    ) {
577        let view = self.intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::DataView));
578        let Some(memory) = self.memory.as_ref() else {
579            panic!(
580                "unexpectedly missing memory during bindgen for interface [{:?}] (callee {})",
581                self.iface_name, self.callee,
582            );
583        };
584        results.push(format!(
585            "{view}({memory}).{method}(({}) + {offset}, true)",
586            operands[0],
587            offset = offset.size_wasm32()
588        ));
589    }
590
591    fn store(&mut self, method: &str, offset: ArchitectureSize, operands: &[String]) {
592        let view = self.intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::DataView));
593        let memory = self.memory.as_ref().unwrap();
594        uwriteln!(
595            self.src,
596            "{view}({memory}).{method}(({}) + {offset}, {}, true);",
597            operands[1],
598            operands[0],
599            offset = offset.size_wasm32()
600        );
601    }
602
603    /// Write result assignment lines to output
604    ///
605    /// In general this either means writing preambles, for example that look like the following:
606    ///
607    /// ```js
608    /// let ret =
609    /// ```
610    ///
611    /// ```js
612    /// var [ ret0, ret1, ret2 ] =
613    /// ```
614    ///
615    /// ```js
616    /// let ret;
617    /// ```
618    ///
619    /// This function returns as a first tuple parameter a list of
620    /// variables that should be created via let statements beforehand.
621    ///
622    /// # Arguments
623    ///
624    /// * `amt` - number of results
625    /// * `results` - list of variables that will be returned
626    ///
627    fn generate_result_assignment_lhs(
628        &mut self,
629        amt: usize,
630        results: &mut Vec<String>,
631        is_async: bool,
632    ) -> (String, String) {
633        let mut s = String::new();
634        let mut vars_init = String::new();
635        match amt {
636            0 => {
637                // Async functions with no returns still return async code,
638                // which will be used as the initial callback result going into the async driver
639                if is_async {
640                    uwrite!(s, "ret = ")
641                }
642                uwriteln!(vars_init, "let ret;");
643            }
644            1 => {
645                uwrite!(s, "ret = ");
646                results.push("ret".to_string());
647                uwriteln!(vars_init, "let ret;");
648            }
649            n => {
650                uwrite!(s, "[");
651                for i in 0..n {
652                    if i > 0 {
653                        uwrite!(s, ", ");
654                    }
655                    uwrite!(s, "ret{i}");
656                    results.push(format!("ret{i}"));
657                    uwriteln!(vars_init, "let ret;");
658                }
659                uwrite!(s, "] = ");
660            }
661        }
662        (vars_init, s)
663    }
664
665    fn bitcast(&mut self, cast: &Bitcast, op: &str) -> String {
666        match cast {
667            Bitcast::I32ToF32 => {
668                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::I32ToF32));
669                format!("{cvt}({op})")
670            }
671            Bitcast::F32ToI32 => {
672                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::F32ToI32));
673                format!("{cvt}({op})")
674            }
675            Bitcast::I64ToF64 => {
676                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::I64ToF64));
677                format!("{cvt}({op})")
678            }
679            Bitcast::F64ToI64 => {
680                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::F64ToI64));
681                format!("{cvt}({op})")
682            }
683            Bitcast::I32ToI64 => format!("BigInt({op})"),
684            Bitcast::I64ToI32 => format!("Number({op})"),
685            Bitcast::I64ToF32 => {
686                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::I32ToF32));
687                format!("{cvt}(Number({op}))")
688            }
689            Bitcast::F32ToI64 => {
690                let cvt = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::F32ToI32));
691                format!("BigInt({cvt}({op}))")
692            }
693            Bitcast::None
694            | Bitcast::P64ToI64
695            | Bitcast::LToI32
696            | Bitcast::I32ToL
697            | Bitcast::LToP
698            | Bitcast::PToL => op.to_string(),
699            Bitcast::PToI32 => format!("({op} | 0)"),
700            Bitcast::I32ToP => format!("({op} >>> 0)"),
701            Bitcast::PToP64 | Bitcast::I64ToP64 | Bitcast::LToI64 => format!("BigInt({op})"),
702            Bitcast::P64ToP => format!("(Number({op}) >>> 0)"),
703            Bitcast::I64ToL => format!("Number({op})"),
704            Bitcast::Sequence(casts) => {
705                let mut statement = op.to_string();
706                for cast in casts.iter() {
707                    statement = self.bitcast(cast, &statement);
708                }
709                statement
710            }
711        }
712    }
713
714    /// Start and enter the task for a call into a guest Wasm export.
715    ///
716    /// This must run before canonical argument lowering because lowering may
717    /// invoke guest core exports such as `realloc`, which can access task-local
718    /// context in WASI P3 components.
719    pub(crate) fn start_wasm_export_task(&mut self) {
720        self.validate_task_management();
721        if self.skip_fn_call_task_management {
722            return;
723        }
724        let is_async = self.is_async;
725        let is_manual_async = self.requires_async_porcelain;
726        let preserve_future_result = self.wrap_async_future_result;
727        let fn_name = self.callee;
728        let err_handling = self.err.to_js_string();
729        let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
730        let get_component_state = self.intrinsic(Intrinsic::Component(
731            ComponentIntrinsic::GetOrCreateAsyncState,
732        ));
733        let start_current_task_fn = self.intrinsic(Intrinsic::AsyncTask(
734            AsyncTaskIntrinsic::CreateNewCurrentTask,
735        ));
736        let current_task_may_block = self.intrinsic(Intrinsic::AsyncTask(
737            AsyncTaskIntrinsic::CurrentTaskMayBlock,
738        ));
739
740        let (component_idx_expr, get_callback_fn_expr, callback_fn_name) =
741            if let Some(state) = &self.component_state {
742                let ComponentStateJsExprs {
743                    component_idx,
744                    callback_fn_name,
745                    get_callback_fn,
746                    ..
747                } = state.get_js_exprs();
748                (component_idx, get_callback_fn, callback_fn_name)
749            } else {
750                ("1".into(), "() => null".into(), "null".into())
751            };
752
753        uwriteln!(
754            self.src,
755            r#"
756              const hostProvided = false;
757              {get_component_state}({component_idx_expr}).throwIfTrapped();
758
759              const [task, _wasm_call_currentTaskID] = {start_current_task_fn}({{
760                  componentIdx: {component_idx_expr},
761                  isAsync: {is_async},
762                  isManualAsync: {is_manual_async},
763                  preserveFutureResult: {preserve_future_result},
764                  entryFnName: '{fn_name}',
765                  getCallbackFn: {get_callback_fn_expr},
766                  callbackFnName: {callback_fn_name},
767                  errHandling: '{err_handling}',
768                  callingWasmExport: true,
769              }});
770              task.setCalleeIsAsync({canonical_abi_async});
771              task.setFuncTypeIsAsync({func_type_async});
772              {set_return_result_type_idx}
773            "#,
774            canonical_abi_async = self.canonical_abi_async,
775            func_type_async = self.func_type_async,
776            set_return_result_type_idx = self
777                .return_result_type_idx
778                .map(|idx| format!("task.setReturnResultTypeIdx({idx});"))
779                .unwrap_or_default(),
780        );
781
782        if self.is_async || self.requires_async_porcelain {
783            uwriteln!(
784                self.src,
785                r#"
786                  const started = await task.enter();
787                  if (!started) {{
788                      {debug_log_fn}('[Instruction::AsyncTaskReturn] failed to enter task', {{
789                          taskID: task.id(),
790                          subtaskID: task.currentSubtask()?.id(),
791                      }});
792                      // (the deadlock detector records why entry was given up on)
793                      throw task.isErrored() ?? new Error("failed to enter task");
794                  }}
795                  // The store may have trapped while this task waited to enter: nothing
796                  // runs after a trap (Canonical ABI), so this call fails too.
797                  try {{
798                      {get_component_state}({component_idx_expr}).throwIfInterrupted();
799                  }} catch (err) {{
800                      task.setErrored(err);
801                      task.reject(err);
802                      task.exit({{ skipExclusiveLockCheck: true }});
803                      throw err;
804                  }}
805                "#,
806            );
807        } else {
808            uwriteln!(self.src, "const started = task.enterSync();");
809        }
810        uwriteln!(
811            self.src,
812            "{current_task_may_block}.value = task.mayBlock() ? 1 : 0;"
813        );
814
815        if self.callee_resource_dynamic {
816            let resource_borrows =
817                self.intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceCallBorrows));
818            let handle_tables = self.intrinsic(Intrinsic::HandleTables);
819            let scope_id = self.intrinsic(Intrinsic::ScopeId);
820            uwriteln!(
821                self.src,
822                r#"
823                  {scope_id}++;
824                  task.registerOnResolveHandler(() => {{
825                      {scope_id}--;
826                      for (const {{ rid, handle }} of {resource_borrows}) {{
827                          const storedScopeId = {handle_tables}[rid][handle << 1]
828                          if (storedScopeId === {scope_id}) {{
829                              throw new TypeError('borrows not dropped for resource call');
830                          }}
831                      }}
832                      {resource_borrows} = [];
833                  }}
834
835                  }});
836                "#
837            );
838            uwriteln!(self.src, "{scope_id}++;");
839        }
840
841        let (memory_idx_expr, get_memory_fn_expr) = if let Some(state) = &self.component_state {
842            let ComponentStateJsExprs {
843                memory_idx,
844                get_memory_fn,
845                ..
846            } = state.get_js_exprs();
847            (memory_idx, get_memory_fn)
848        } else {
849            ("null".into(), "() => null".into())
850        };
851        uwriteln!(
852            self.src,
853            r#"
854              if ({memory_idx_expr} !== null) {{
855                  task.setReturnMemoryIdx({memory_idx_expr});
856                  task.setReturnMemory(({get_memory_fn_expr})());
857              }}
858            "#
859        );
860    }
861
862    /// Run the full canonical adapter body with the export task installed as
863    /// the component's current task. This includes argument lowering and
864    /// result lifting, both of which may call guest core functions.
865    pub(crate) fn begin_wasm_export_body(&mut self) {
866        self.validate_task_management();
867        if self.skip_fn_call_task_management {
868            return;
869        }
870        let is_async = self.is_async || self.requires_async_porcelain;
871        let wrapper = if is_async {
872            self.intrinsic(Intrinsic::WithGlobalCurrentTaskMetaFnAsync)
873        } else {
874            self.intrinsic(Intrinsic::WithGlobalCurrentTaskMetaFn)
875        };
876        if self.is_async {
877            // The caller of an async-lifted export gets the task's result as
878            // soon as the task resolves (Canonical ABI: `on_resolve` runs at
879            // `task.return`), even when the task keeps running afterwards, e.g.
880            // blocked in a synchronous wait. The body's own completion is raced
881            // against that resolution. (A manually async, sync-typed export
882            // resolves when its core function returns, so it needs no race.)
883            let return_task_res = if self.wrap_async_future_result {
884                "{ value: taskRes }"
885            } else {
886                "taskRes"
887            };
888            let throw_result_err = if self.no_component_error_wrapping {
889                "throw taskRes.val;".to_string()
890            } else {
891                let component_err = self.intrinsic(Intrinsic::ComponentError);
892                format!("throw new {component_err}(taskRes.val);")
893            };
894            uwriteln!(
895                self.src,
896                r#"
897                  const finishCompletion = async () => {{
898                      let taskRes = await task.completionPromise();
899                      if (task.getErrHandling() === 'throw-result-err') {{
900                          if (typeof taskRes !== 'object') {{
901                              return {return_task_res};
902                          }}
903                          if (taskRes.tag === 'err') {{ {throw_result_err} }}
904                          if (taskRes.tag === 'ok') {{ taskRes = taskRes.val; }}
905                      }}
906                      return {return_task_res};
907                  }};
908                  const body = {wrapper}({{
909                      taskID: task.id(),
910                      componentIdx: task.componentIdx(),
911                      fn: async () => {{
912                          try {{
913                "#,
914            );
915        } else {
916            let await_ = if is_async { "await " } else { "" };
917            let async_ = if is_async { "async " } else { "" };
918            uwriteln!(
919                self.src,
920                r#"
921                  return {await_}{wrapper}({{
922                      taskID: task.id(),
923                      componentIdx: task.componentIdx(),
924                      fn: {async_}() => {{
925                          try {{
926                "#,
927            );
928        }
929    }
930
931    pub(crate) fn end_wasm_export_body(&mut self) {
932        self.validate_task_management();
933        if self.skip_fn_call_task_management {
934            return;
935        }
936        uwriteln!(
937            self.src,
938            r#"
939                      }} catch (err) {{
940                          if (!task.isResolvedState()) {{
941                              task.setErrored(err);
942                              task.reject(err);
943                          }}
944                          if (!task.isExited()) {{ task.exit({{ skipExclusiveLockCheck: true }}); }}
945                          throw err;
946                      }}
947                  }},
948              }});
949            "#,
950        );
951        if self.is_async {
952            uwriteln!(
953                self.src,
954                r#"
955                  // (a failure after the task resolved is recorded on the store; the
956                  // caller already has, or is about to get, the task's result)
957                  body.catch(() => {{}});
958                  return await Promise.race([body, finishCompletion()]);
959                "#,
960            );
961        }
962    }
963}
964
965impl ManagesIntrinsics for FunctionBindgen<'_> {
966    /// Add an intrinsic, supplying it's name afterwards
967    fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
968        self.intrinsic(intrinsic);
969    }
970}
971
972impl Bindgen for FunctionBindgen<'_> {
973    type Operand = String;
974
975    /// Get the sizes and alignment for a given structure
976    fn sizes(&self) -> &SizeAlign {
977        self.sizes
978    }
979
980    /// Push a new block of code
981    fn push_block(&mut self) {
982        let prev = mem::take(&mut self.src);
983        self.block_storage.push(prev);
984    }
985
986    /// Finish a block of code
987    fn finish_block(&mut self, operands: &mut Vec<String>) {
988        let to_restore = self.block_storage.pop().unwrap();
989        let src = mem::replace(&mut self.src, to_restore);
990        self.blocks.push((src.into(), mem::take(operands)));
991    }
992
993    /// Output the return pointer
994    fn return_pointer(&mut self, _size: ArchitectureSize, _align: Alignment) -> String {
995        unimplemented!("determining the return pointer for this function is not implemented");
996    }
997
998    /// Check whether a list of the given element type can be represented as a builtni JS type
999    ///
1000    /// # Arguments
1001    ///
1002    /// * `resolve` - the [`Resolve`] that might be used to resolve nested types (i.e. [`Type::TypeId`])
1003    /// * `elem_ty` - the [`Type`] of the element stored in the list
1004    ///
1005    fn is_list_canonical(&self, resolve: &Resolve, elem_ty: &Type) -> bool {
1006        js_array_ty(resolve, elem_ty).is_some()
1007    }
1008
1009    fn emit(
1010        &mut self,
1011        resolve: &Resolve,
1012        inst: &Instruction<'_>,
1013        operands: &mut Vec<String>,
1014        results: &mut Vec<String>,
1015    ) {
1016        self.validate_task_management();
1017        let task_managed = !self.skip_fn_call_task_management;
1018        if !task_managed {
1019            assert!(
1020                !instruction_requires_task_runtime(inst),
1021                "Async ABI instructions require task management"
1022            );
1023        }
1024        match inst {
1025            Instruction::GetArg { nth } => results.push(self.params[*nth].clone()),
1026
1027            Instruction::I32Const { val } => results.push(val.to_string()),
1028
1029            Instruction::ConstZero { tys } => {
1030                for t in tys.iter() {
1031                    match t {
1032                        WasmType::I64 | WasmType::PointerOrI64 => results.push("0n".to_string()),
1033                        WasmType::I32
1034                        | WasmType::F32
1035                        | WasmType::F64
1036                        | WasmType::Pointer
1037                        | WasmType::Length => results.push("0".to_string()),
1038                    }
1039                }
1040            }
1041
1042            Instruction::U8FromI32 => self.clamp_guest(results, operands, u8::MIN, u8::MAX),
1043
1044            Instruction::S8FromI32 => self.clamp_guest(results, operands, i8::MIN, i8::MAX),
1045
1046            Instruction::U16FromI32 => self.clamp_guest(results, operands, u16::MIN, u16::MAX),
1047
1048            Instruction::S16FromI32 => self.clamp_guest(results, operands, i16::MIN, i16::MAX),
1049
1050            Instruction::U32FromI32 => results.push(format!("{} >>> 0", operands[0])),
1051
1052            Instruction::U64FromI64 => {
1053                results.push(format!("BigInt.asUintN(64, BigInt({}))", operands[0]))
1054            }
1055
1056            Instruction::S32FromI32 | Instruction::S64FromI64 => {
1057                results.push(operands.pop().unwrap())
1058            }
1059
1060            Instruction::I32FromU8 => {
1061                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToUint8));
1062                results.push(format!("{conv}({op})", op = operands[0]))
1063            }
1064
1065            Instruction::I32FromS8 => {
1066                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToInt8));
1067                results.push(format!("{conv}({op})", op = operands[0]))
1068            }
1069
1070            Instruction::I32FromU16 => {
1071                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToUint16));
1072                results.push(format!("{conv}({op})", op = operands[0]))
1073            }
1074
1075            Instruction::I32FromS16 => {
1076                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToInt16));
1077                results.push(format!("{conv}({op})", op = operands[0]))
1078            }
1079
1080            Instruction::I32FromU32 => {
1081                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToUint32));
1082                results.push(format!("{conv}({op})", op = operands[0]))
1083            }
1084
1085            Instruction::I32FromS32 => {
1086                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToInt32));
1087                results.push(format!("{conv}({op})", op = operands[0]))
1088            }
1089
1090            Instruction::I64FromU64 => {
1091                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToBigUint64));
1092                results.push(format!("{conv}({op})", op = operands[0]))
1093            }
1094
1095            Instruction::I64FromS64 => {
1096                let conv = self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToBigInt64));
1097                results.push(format!("{conv}({op})", op = operands[0]))
1098            }
1099
1100            Instruction::F32FromCoreF32 | Instruction::F64FromCoreF64 => {
1101                results.push(operands.pop().unwrap())
1102            }
1103
1104            Instruction::CoreF32FromF32 | Instruction::CoreF64FromF64 => {
1105                results.push(format!("+{}", operands[0]))
1106            }
1107
1108            Instruction::CharFromI32 => {
1109                let validate =
1110                    self.intrinsic(Intrinsic::String(StringIntrinsic::ValidateGuestChar));
1111                results.push(format!("{}({})", validate, operands[0]));
1112            }
1113
1114            Instruction::I32FromChar => {
1115                let validate = self.intrinsic(Intrinsic::String(StringIntrinsic::ValidateHostChar));
1116                results.push(format!("{}({})", validate, operands[0]));
1117            }
1118
1119            Instruction::Bitcasts { casts } => {
1120                for (cast, op) in casts.iter().zip(operands) {
1121                    results.push(self.bitcast(cast, op));
1122                }
1123            }
1124
1125            Instruction::BoolFromI32 => {
1126                let tmp = self.tmp();
1127                uwrite!(self.src, "var bool{} = {};\n", tmp, operands[0]);
1128                if self.valid_lifting_optimization {
1129                    results.push(format!("!!bool{tmp}"));
1130                } else {
1131                    let throw = self.intrinsic(Intrinsic::ThrowInvalidBool);
1132                    results.push(format!(
1133                        "bool{tmp} == 0 ? false : (bool{tmp} == 1 ? true : {throw}())"
1134                    ));
1135                }
1136            }
1137
1138            Instruction::I32FromBool => {
1139                results.push(format!("{} ? 1 : 0", operands[0]));
1140            }
1141
1142            Instruction::RecordLower { record, .. } => {
1143                // use destructuring field access to get each
1144                // field individually.
1145                let tmp = self.tmp();
1146                let mut expr = "var {".to_string();
1147                for (i, field) in record.fields.iter().enumerate() {
1148                    if i > 0 {
1149                        expr.push_str(", ");
1150                    }
1151                    let name = format!("v{tmp}_{i}");
1152                    expr.push_str(&field.name.to_lower_camel_case());
1153                    expr.push_str(": ");
1154                    expr.push_str(&name);
1155                    results.push(name);
1156                }
1157                uwrite!(self.src, "{} }} = {};\n", expr, operands[0]);
1158            }
1159
1160            Instruction::RecordLift { record, .. } => {
1161                // records are represented as plain objects, so we
1162                // make a new object and set all the fields with an object
1163                // literal.
1164                let mut result = "{\n".to_string();
1165                for (field, op) in record.fields.iter().zip(operands) {
1166                    result.push_str(&format!("{}: {},\n", field.name.to_lower_camel_case(), op));
1167                }
1168                result.push('}');
1169                results.push(result);
1170            }
1171
1172            Instruction::TupleLower { tuple, .. } => {
1173                // Tuples are represented as an array, sowe can use
1174                // destructuring assignment to lower the tuple into its
1175                // components.
1176                let tmp = self.tmp();
1177                let mut expr = "var [".to_string();
1178                for i in 0..tuple.types.len() {
1179                    if i > 0 {
1180                        expr.push_str(", ");
1181                    }
1182                    let name = format!("tuple{tmp}_{i}");
1183                    expr.push_str(&name);
1184                    results.push(name);
1185                }
1186                uwrite!(self.src, "{}] = {};\n", expr, operands[0]);
1187            }
1188
1189            Instruction::TupleLift { .. } => {
1190                // Tuples are represented as an array, so we just shove all
1191                // the operands into an array.
1192                results.push(format!("[{}]", operands.join(", ")));
1193            }
1194
1195            Instruction::FlagsLower { flags, .. } => {
1196                let op0 = &operands[0];
1197
1198                if self.flags_as_bigint {
1199                    let flag_count = flags.flags.len();
1200                    uwriteln!(
1201                        self.src,
1202                        "if (typeof {op0} !== 'bigint') {{
1203                            throw new TypeError('flags must be a bigint');
1204                        }}
1205                        if ({op0} < 0n || ({op0} >> {flag_count}n) !== 0n) {{
1206                            throw new TypeError('flags have extraneous bits set');
1207                        }}"
1208                    );
1209
1210                    for i in 0..flags.repr().count() {
1211                        let tmp = self.tmp();
1212                        let name = format!("flags{tmp}");
1213                        let shift = i * 32;
1214                        uwriteln!(
1215                            self.src,
1216                            "const {name} = Number(({op0} >> {shift}n) & 0xffff_ffffn);"
1217                        );
1218                        results.push(name);
1219                    }
1220                    return;
1221                }
1222
1223                // Generate the result names.
1224                for _ in 0..flags.repr().count() {
1225                    let tmp = self.tmp();
1226                    let name = format!("flags{tmp}");
1227                    // Default to 0 so that in the null/undefined case, everything is false by
1228                    // default.
1229                    uwrite!(self.src, "let {name} = 0;\n");
1230                    results.push(name);
1231                }
1232
1233                uwrite!(
1234                    self.src,
1235                    "if (typeof {op0} === 'object' && {op0} !== null) {{\n"
1236                );
1237
1238                for (i, chunk) in flags.flags.chunks(32).enumerate() {
1239                    let result_name = &results[i];
1240
1241                    uwrite!(self.src, "{result_name} = ");
1242                    for (i, flag) in chunk.iter().enumerate() {
1243                        if i != 0 {
1244                            uwrite!(self.src, " | ");
1245                        }
1246
1247                        let flag = flag.name.to_lower_camel_case();
1248                        uwrite!(self.src, "Boolean({op0}.{flag}) << {i}");
1249                    }
1250                    uwrite!(self.src, ";\n");
1251                }
1252
1253                uwrite!(
1254                            self.src,
1255                            "\
1256                    }} else if ({op0} !== null && {op0} !== undefined) {{
1257                        throw new TypeError('only an object, undefined or null can be converted to flags');
1258                    }}
1259                ");
1260
1261                // We don't need to do anything else for the null/undefined
1262                // case, since that's interpreted as everything false, and we
1263                // already defaulted everyting to 0.
1264            }
1265
1266            Instruction::FlagsLift { flags, .. } => {
1267                let tmp = self.tmp();
1268                results.push(format!("flags{tmp}"));
1269
1270                if let Some(op) = operands.last() {
1271                    // We only need an extraneous bits check if the number of flags isn't a multiple
1272                    // of 32, because if it is then all the bits are used and there are no
1273                    // extraneous bits.
1274                    if flags.flags.len() % 32 != 0 && !self.valid_lifting_optimization {
1275                        let mask: u32 = 0xffffffff << (flags.flags.len() % 32);
1276                        uwriteln!(
1277                            self.src,
1278                            "if (({op} & {mask}) !== 0) {{
1279                                throw new TypeError('flags have extraneous bits set');
1280                            }}"
1281                        );
1282                    }
1283                }
1284
1285                if self.flags_as_bigint {
1286                    uwriteln!(self.src, "var flags{tmp} = 0n;");
1287                    for (i, op) in operands.iter().enumerate() {
1288                        let shift = i * 32;
1289                        uwriteln!(self.src, "flags{tmp} |= BigInt({op} >>> 0) << {shift}n;");
1290                    }
1291                    return;
1292                }
1293
1294                uwriteln!(self.src, "var flags{tmp} = {{");
1295
1296                for (i, flag) in flags.flags.iter().enumerate() {
1297                    let flag = flag.name.to_lower_camel_case();
1298                    let op = &operands[i / 32];
1299                    let mask: u32 = 1 << (i % 32);
1300                    uwriteln!(self.src, "{flag}: Boolean({op} & {mask}),");
1301                }
1302
1303                uwriteln!(self.src, "}};");
1304            }
1305
1306            Instruction::VariantPayloadName => results.push("e".to_string()),
1307
1308            Instruction::VariantLower {
1309                variant,
1310                results: result_types,
1311                name,
1312                ..
1313            } => {
1314                let blocks = self
1315                    .blocks
1316                    .drain(self.blocks.len() - variant.cases.len()..)
1317                    .collect::<Vec<_>>();
1318                let tmp = self.tmp();
1319                let op = &operands[0];
1320                uwriteln!(self.src, "var variant{tmp} = {op};");
1321
1322                for i in 0..result_types.len() {
1323                    uwriteln!(self.src, "let variant{tmp}_{i};");
1324                    results.push(format!("variant{tmp}_{i}"));
1325                }
1326
1327                let expr_to_match = format!("variant{tmp}.tag");
1328
1329                uwriteln!(self.src, "switch ({expr_to_match}) {{");
1330                for (case, (block, block_results)) in variant.cases.iter().zip(blocks) {
1331                    uwriteln!(self.src, "case '{}': {{", case.name.as_str());
1332                    if case.ty.is_some() {
1333                        uwriteln!(self.src, "const e = variant{tmp}.val;");
1334                    }
1335                    self.src.push_str(&block);
1336
1337                    for (i, result) in block_results.iter().enumerate() {
1338                        uwriteln!(self.src, "variant{tmp}_{i} = {result};");
1339                    }
1340                    uwriteln!(
1341                        self.src,
1342                        "break;
1343                        }}"
1344                    );
1345                }
1346                let variant_name = name.to_upper_camel_case();
1347                uwriteln!(
1348                    self.src,
1349                    r#"default: {{
1350                        throw new TypeError(`invalid variant tag value \`${{JSON.stringify({expr_to_match})}}\` (received \`${{variant{tmp}}}\`) specified for \`{variant_name}\``);
1351                    }}"#,
1352                );
1353                uwriteln!(self.src, "}}");
1354            }
1355
1356            Instruction::VariantLift { variant, name, .. } => {
1357                let blocks = self
1358                    .blocks
1359                    .drain(self.blocks.len() - variant.cases.len()..)
1360                    .collect::<Vec<_>>();
1361
1362                let tmp = self.tmp();
1363                let op = &operands[0];
1364
1365                uwriteln!(
1366                    self.src,
1367                    "let variant{tmp};
1368                    switch ({op}) {{"
1369                );
1370
1371                for (i, (case, (block, block_results))) in
1372                    variant.cases.iter().zip(blocks).enumerate()
1373                {
1374                    let tag = case.name.as_str();
1375                    uwriteln!(
1376                        self.src,
1377                        "case {i}: {{
1378                            {block}\
1379                            variant{tmp} = {{
1380                                tag: '{tag}',"
1381                    );
1382                    if case.ty.is_some() {
1383                        assert!(block_results.len() == 1);
1384                        uwriteln!(self.src, "   val: {}", block_results[0]);
1385                    } else {
1386                        assert!(block_results.is_empty());
1387                    }
1388                    uwriteln!(
1389                        self.src,
1390                        "   }};
1391                        break;
1392                        }}"
1393                    );
1394                }
1395                let variant_name = name.to_upper_camel_case();
1396                if !self.valid_lifting_optimization {
1397                    uwriteln!(
1398                        self.src,
1399                        "default: {{
1400                            throw new TypeError('invalid variant discriminant for {variant_name}');
1401                        }}",
1402                    );
1403                }
1404                uwriteln!(self.src, "}}");
1405                results.push(format!("variant{tmp}"));
1406            }
1407
1408            Instruction::OptionLower {
1409                payload,
1410                results: result_types,
1411                ..
1412            } => {
1413                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
1414                let (mut some, some_results) = self.blocks.pop().unwrap();
1415                let (mut none, none_results) = self.blocks.pop().unwrap();
1416
1417                let tmp = self.tmp();
1418                let op = &operands[0];
1419                uwriteln!(self.src, "var variant{tmp} = {op};");
1420
1421                for i in 0..result_types.len() {
1422                    uwriteln!(self.src, "let variant{tmp}_{i};");
1423                    results.push(format!("variant{tmp}_{i}"));
1424
1425                    let some_result = &some_results[i];
1426                    let none_result = &none_results[i];
1427                    uwriteln!(some, "variant{tmp}_{i} = {some_result};");
1428                    uwriteln!(none, "variant{tmp}_{i} = {none_result};");
1429                }
1430
1431                if maybe_null(resolve, payload) {
1432                    uwriteln!(
1433                        self.src,
1434                        r#"switch (variant{tmp}.tag) {{
1435                            case 'none': {{
1436                                {none}
1437                                break;
1438                            }}
1439                            case 'some': {{
1440                                const e = variant{tmp}.val;
1441                                {some}
1442                                break;
1443                            }}
1444                            default: {{
1445                                {debug_log_fn}("ERROR: invalid value (expected option as object with 'tag' member)", {{ value: variant{tmp}, valueType: typeof variant{tmp} }});
1446                                throw new TypeError('invalid variant specified for option');
1447                            }}
1448                        }}"#,
1449                    );
1450                } else {
1451                    uwriteln!(
1452                        self.src,
1453                        "if (variant{tmp} === null || variant{tmp} === undefined) {{
1454                            {none}\
1455                        }} else {{
1456                            const e = variant{tmp};
1457                            {some}\
1458                        }}"
1459                    );
1460                }
1461            }
1462
1463            Instruction::OptionLift { payload, .. } => {
1464                let (some, some_results) = self.blocks.pop().unwrap();
1465                let (none, none_results) = self.blocks.pop().unwrap();
1466                assert!(none_results.is_empty());
1467                assert!(some_results.len() == 1);
1468                let some_result = &some_results[0];
1469
1470                let tmp = self.tmp();
1471                let op = &operands[0];
1472
1473                let (v_none, v_some) = if maybe_null(resolve, payload) {
1474                    (
1475                        "{ tag: 'none' }",
1476                        format!(
1477                            "{{
1478                                tag: 'some',
1479                                val: {some_result}
1480                            }}"
1481                        ),
1482                    )
1483                } else {
1484                    ("undefined", some_result.into())
1485                };
1486
1487                if !self.valid_lifting_optimization {
1488                    uwriteln!(
1489                        self.src,
1490                        "let variant{tmp};
1491                        switch ({op}) {{
1492                            case 0: {{
1493                                {none}\
1494                                variant{tmp} = {v_none};
1495                                break;
1496                            }}
1497                            case 1: {{
1498                                {some}\
1499                                variant{tmp} = {v_some};
1500                                break;
1501                            }}
1502                            default: {{
1503                                throw new TypeError('invalid variant discriminant for option');
1504                            }}
1505                        }}",
1506                    );
1507                } else {
1508                    uwriteln!(
1509                        self.src,
1510                        "let variant{tmp};
1511                        if ({op}) {{
1512                            {some}\
1513                            variant{tmp} = {v_some};
1514                        }} else {{
1515                            {none}\
1516                            variant{tmp} = {v_none};
1517                        }}"
1518                    );
1519                }
1520
1521                results.push(format!("variant{tmp}"));
1522            }
1523
1524            Instruction::ResultLower {
1525                results: result_types,
1526                ..
1527            } => {
1528                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
1529                let (mut err, err_results) = self.blocks.pop().unwrap();
1530                let (mut ok, ok_results) = self.blocks.pop().unwrap();
1531
1532                let tmp = self.tmp();
1533                let op = &operands[0];
1534                uwriteln!(self.src, "var variant{tmp} = {op};");
1535
1536                for i in 0..result_types.len() {
1537                    uwriteln!(self.src, "let variant{tmp}_{i};");
1538                    results.push(format!("variant{tmp}_{i}"));
1539
1540                    let ok_result = &ok_results[i];
1541                    let err_result = &err_results[i];
1542                    uwriteln!(ok, "variant{tmp}_{i} = {ok_result};");
1543                    uwriteln!(err, "variant{tmp}_{i} = {err_result};");
1544                }
1545
1546                uwriteln!(
1547                    self.src,
1548                    r#"switch (variant{tmp}.tag) {{
1549                        case 'ok': {{
1550                            const e = variant{tmp}.val;
1551                            {ok}
1552                            break;
1553                        }}
1554                        case 'err': {{
1555                            const e = variant{tmp}.val;
1556                            {err}
1557                            break;
1558                        }}
1559                        default: {{
1560                            {debug_log_fn}("ERROR: invalid value (expected result as object with 'tag' member)", {{ value: variant{tmp}, valueType: typeof variant{tmp} }});
1561                            throw new TypeError('invalid variant specified for result');
1562                        }}
1563                    }}"#,
1564                );
1565            }
1566
1567            Instruction::ResultLift { result, .. } => {
1568                let (err, err_results) = self.blocks.pop().unwrap();
1569                let (ok, ok_results) = self.blocks.pop().unwrap();
1570                let ok_result = if result.ok.is_some() {
1571                    assert_eq!(ok_results.len(), 1);
1572                    ok_results[0].to_string()
1573                } else {
1574                    assert_eq!(ok_results.len(), 0);
1575                    String::from("undefined")
1576                };
1577                let err_result = if result.err.is_some() {
1578                    assert_eq!(err_results.len(), 1);
1579                    err_results[0].to_string()
1580                } else {
1581                    assert_eq!(err_results.len(), 0);
1582                    String::from("undefined")
1583                };
1584                let tmp = self.tmp();
1585                let op0 = &operands[0];
1586
1587                if !self.valid_lifting_optimization {
1588                    uwriteln!(
1589                        self.src,
1590                        "let variant{tmp};
1591                        switch ({op0}) {{
1592                            case 0: {{
1593                                {ok}\
1594                                variant{tmp} = {{
1595                                    tag: 'ok',
1596                                    val: {ok_result}
1597                                }};
1598                                break;
1599                            }}
1600                            case 1: {{
1601                                {err}\
1602                                variant{tmp} = {{
1603                                    tag: 'err',
1604                                    val: {err_result}
1605                                }};
1606                                break;
1607                            }}
1608                            default: {{
1609                                throw new TypeError('invalid variant discriminant for expected');
1610                            }}
1611                        }}",
1612                    );
1613                } else {
1614                    uwriteln!(
1615                        self.src,
1616                        "let variant{tmp};
1617                        if ({op0}) {{
1618                            {err}\
1619                            variant{tmp} = {{
1620                                tag: 'err',
1621                                val: {err_result}
1622                            }};
1623                        }} else {{
1624                            {ok}\
1625                            variant{tmp} = {{
1626                                tag: 'ok',
1627                                val: {ok_result}
1628                            }};
1629                        }}"
1630                    );
1631                }
1632                results.push(format!("variant{tmp}"));
1633            }
1634
1635            Instruction::EnumLower { name, enum_, .. } => {
1636                let tmp = self.tmp();
1637
1638                let op = &operands[0];
1639                uwriteln!(self.src, "var val{tmp} = {op};");
1640
1641                // Declare a variable to hold the result.
1642                uwriteln!(
1643                    self.src,
1644                    "let enum{tmp};
1645                    switch (val{tmp}) {{"
1646                );
1647                for (i, case) in enum_.cases.iter().enumerate() {
1648                    let case_name =
1649                        crate::enum_case_name(&case.name, self.enum_values_screaming_snake_case);
1650                    uwriteln!(
1651                        self.src,
1652                        "case '{case}': {{
1653                            enum{tmp} = {i};
1654                            break;
1655                        }}",
1656                        case = case_name
1657                    );
1658                }
1659                uwriteln!(self.src, "default: {{");
1660                if !self.valid_lifting_optimization {
1661                    uwriteln!(
1662                        self.src,
1663                        "if (({op}) instanceof Error) {{
1664                        console.error({op});
1665                    }}"
1666                    );
1667                }
1668                uwriteln!(
1669                            self.src,
1670                            "
1671                            throw new TypeError(`\"${{val{tmp}}}\" is not one of the cases of {name}`);
1672                        }}
1673                    }}",
1674                        );
1675
1676                results.push(format!("enum{tmp}"));
1677            }
1678
1679            Instruction::EnumLift { name, enum_, .. } => {
1680                let tmp = self.tmp();
1681
1682                uwriteln!(
1683                    self.src,
1684                    "let enum{tmp};
1685                    switch ({}) {{",
1686                    operands[0]
1687                );
1688                for (i, case) in enum_.cases.iter().enumerate() {
1689                    let case_name =
1690                        crate::enum_case_name(&case.name, self.enum_values_screaming_snake_case);
1691                    uwriteln!(
1692                        self.src,
1693                        "case {i}: {{
1694                            enum{tmp} = '{case}';
1695                            break;
1696                        }}",
1697                        case = case_name
1698                    );
1699                }
1700                if !self.valid_lifting_optimization {
1701                    let name = name.to_upper_camel_case();
1702                    uwriteln!(
1703                        self.src,
1704                        "default: {{
1705                            throw new TypeError('invalid discriminant specified for {name}');
1706                        }}",
1707                    );
1708                }
1709                uwriteln!(self.src, "}}");
1710
1711                results.push(format!("enum{tmp}"));
1712            }
1713
1714            // The ListCanonLower instruction is called on async function parameter lowers,
1715            // which are separated in memory by one pointer follow.
1716            //
1717            // We ignore `realloc` in the instruction because it's the name of the *import* from the
1718            // component's side (i.e. `"cabi_realloc"`). Bindings have already set up the appropriate
1719            // realloc for the current component (e.g. `realloc0`) and it is available in the bindgen
1720            // object @ `self.realloc`
1721            //
1722            // Note that this can be called *inside* a "regular" ListCanonLower, for example
1723            // when a list of lists or list of Uint8Arrays is sent.
1724            //
1725            Instruction::ListCanonLower { element, .. } => {
1726                self.intrinsic(Intrinsic::Conversion(
1727                    ConversionIntrinsic::RequireValidNumericPrimitive,
1728                ));
1729                let tmp = self.tmp();
1730                let memory = self.memory.as_ref().unwrap();
1731                let realloc = self.realloc.unwrap();
1732
1733                // Alias the list to a local variable
1734                uwriteln!(self.src, "var val{tmp} = {};", operands[0]);
1735                if matches!(element, Type::U8) {
1736                    uwriteln!(
1737                        self.src,
1738                        "var len{tmp} = Array.isArray(val{tmp}) ? val{tmp}.length : val{tmp}.byteLength;"
1739                    );
1740                } else {
1741                    uwriteln!(self.src, "var len{tmp} = val{tmp}.length;");
1742                }
1743
1744                // Gather metadata about list element
1745                let size = self.sizes.size(element).size_wasm32();
1746                let align = self.sizes.align(element).align_wasm32();
1747
1748                // Allocate space for the type in question
1749                uwriteln!(
1750                    self.src,
1751                    "var ptr{tmp} = {realloc_call}(0, 0, {align}, len{tmp} * {size});",
1752                    realloc_call = if self.is_async {
1753                        format!("await {realloc}")
1754                    } else {
1755                        realloc.to_string()
1756                    },
1757                );
1758
1759                // Determine what methods to use with a DataView when setting the data
1760                let (dataview_set_method, check_fn_intrinsic) =
1761                    gen_dataview_set_and_check_fn_js_for_numeric_type(resolve, element);
1762
1763                // Detect whether we're dealing with a regular array
1764                uwriteln!(
1765                    self.src,
1766                    r#"
1767                        let valData{tmp};
1768                        const valLenBytes{tmp} = len{tmp} * {size};
1769                        if (Array.isArray(val{tmp})) {{
1770                            // Regular array likely containing numbers, write values to memory
1771                            let offset = 0;
1772                            const dv{tmp} = new DataView({memory}.buffer);
1773                            for (const v of val{tmp}) {{
1774                                {check_fn_intrinsic}(v);
1775                                dv{tmp}.{dataview_set_method}(ptr{tmp} + offset, v, true);
1776                                offset += {size};
1777                            }}
1778                        }} else {{
1779                            // TypedArray / ArrayBuffer-like, direct copy
1780                            valData{tmp} = new Uint8Array(val{tmp}.buffer || val{tmp}, val{tmp}.byteOffset, valLenBytes{tmp});
1781                            const out{tmp} = new Uint8Array({memory}.buffer, ptr{tmp}, valLenBytes{tmp});
1782                            out{tmp}.set(valData{tmp});
1783                        }}
1784                    "#,
1785                );
1786
1787                results.push(format!("ptr{tmp}"));
1788                results.push(format!("len{tmp}"));
1789            }
1790
1791            Instruction::ListCanonLift { element, .. } => {
1792                let tmp = self.tmp();
1793                let memory = self.memory.as_ref().unwrap().to_string();
1794                let size = self.sizes.size(element).size_wasm32();
1795                let align = self.sizes.align(element).align_wasm32();
1796                uwriteln!(self.src, "var ptr{tmp} = {} >>> 0;", operands[0]);
1797                uwriteln!(self.src, "var len{tmp} = {};", operands[1]);
1798                self.emit_list_bounds_check(&format!("ptr{tmp}"), &format!("len{tmp}"), size);
1799                uwriteln!(
1800                    self.src,
1801                    "if (ptr{tmp} % {align} !== 0) throw new TypeError(`list pointer [${{ptr{tmp}}}] is not aligned to {align}`);
1802                    var result{tmp} = new {array_ty}({memory}.buffer.slice(ptr{tmp}, ptr{tmp} + len{tmp} * {elem_size}));",
1803                    elem_size = size,
1804                    array_ty = js_array_ty(resolve, element).unwrap(), // TODO: this is the wrong endianness
1805                );
1806                self.emit_dealloc(&format!("ptr{tmp}"), &format!("len{tmp}"), size, align);
1807                results.push(format!("result{tmp}"));
1808            }
1809
1810            Instruction::StringLower { .. } => {
1811                // Only Utf8 and Utf16 supported for now
1812                assert!(matches!(
1813                    self.encoding,
1814                    StringEncoding::UTF8 | StringEncoding::UTF16
1815                ));
1816
1817                let (call_prefix, encode_intrinsic) = match (self.encoding, self.is_async) {
1818                    (StringEncoding::UTF16, true) => (
1819                        "await ",
1820                        Intrinsic::String(StringIntrinsic::Utf16EncodeAsync),
1821                    ),
1822                    (StringEncoding::UTF16, false) => {
1823                        ("", Intrinsic::String(StringIntrinsic::Utf16Encode))
1824                    }
1825                    (StringEncoding::UTF8, true) => (
1826                        "await ",
1827                        Intrinsic::String(StringIntrinsic::Utf8EncodeAsync),
1828                    ),
1829                    (StringEncoding::UTF8, false) => {
1830                        ("", Intrinsic::String(StringIntrinsic::Utf8Encode))
1831                    }
1832                    _ => unreachable!("unsupported encoding {}", self.encoding),
1833                };
1834                let encode = self.intrinsic(encode_intrinsic);
1835
1836                let tmp = self.tmp();
1837                let memory = self.memory.as_ref().unwrap();
1838                let str = String::from("cabi_realloc");
1839                let realloc = self.realloc.unwrap_or(&str);
1840                let s = &operands[0];
1841                uwriteln!(
1842                    self.src,
1843                    r#"
1844                      var encodeRes = {call_prefix}{encode}({s}, {realloc}, {memory});
1845                      var ptr{tmp} = encodeRes.ptr;
1846                      var len{tmp} = {encoded_len};
1847                    "#,
1848                    encoded_len = match self.encoding {
1849                        StringEncoding::UTF8 => "encodeRes.len".into(),
1850                        _ => format!("{}.length", s),
1851                    }
1852                );
1853                results.push(format!("ptr{tmp}"));
1854                results.push(format!("len{tmp}"));
1855            }
1856
1857            Instruction::StringLift => {
1858                // Only Utf8 and Utf16 supported for now
1859                assert!(matches!(
1860                    self.encoding,
1861                    StringEncoding::UTF8 | StringEncoding::UTF16
1862                ));
1863                let decoder = self.intrinsic(match self.encoding {
1864                    StringEncoding::UTF16 => Intrinsic::String(StringIntrinsic::Utf16Decoder),
1865                    _ => Intrinsic::String(StringIntrinsic::GlobalTextDecoderUtf8),
1866                });
1867                let tmp = self.tmp();
1868                let memory = self.memory.as_ref().unwrap();
1869                uwriteln!(self.src, "var ptr{tmp} = {} >>> 0;", operands[0]);
1870                uwriteln!(self.src, "var len{tmp} = {};", operands[1]);
1871                uwriteln!(
1872                    self.src,
1873                    "var result{tmp} = {decoder}.decode(new Uint{}Array({memory}.buffer, ptr{tmp}, len{tmp}));",
1874                    if self.encoding == StringEncoding::UTF16 {
1875                        "16"
1876                    } else {
1877                        "8"
1878                    }
1879                );
1880                let code_unit_size = if self.encoding == StringEncoding::UTF16 {
1881                    2
1882                } else {
1883                    1
1884                };
1885                self.emit_dealloc(
1886                    &format!("ptr{tmp}"),
1887                    &format!("len{tmp}"),
1888                    code_unit_size,
1889                    code_unit_size,
1890                );
1891                results.push(format!("result{tmp}"));
1892            }
1893
1894            Instruction::ListLower { element, .. } => {
1895                let (body, body_results) = self.blocks.pop().unwrap();
1896                assert!(body_results.is_empty());
1897                let tmp = self.tmp();
1898                let vec = format!("vec{tmp}");
1899                let result = format!("result{tmp}");
1900                let len = format!("len{tmp}");
1901                let size = self.sizes.size(element).size_wasm32();
1902                let align = ArchitectureSize::from(self.sizes.align(element)).size_wasm32();
1903
1904                // first store our vec-to-lower in a temporary since we'll
1905                // reference it multiple times.
1906                uwriteln!(self.src, "var {vec} = {};", operands[0]);
1907                uwriteln!(self.src, "var {len} = {vec}.length;");
1908
1909                // ... then realloc space for the result in the guest module
1910                let realloc = self.realloc.as_ref().unwrap();
1911                uwriteln!(
1912                    self.src,
1913                    "var {result} = {realloc_call}(0, 0, {align}, {len} * {size});",
1914                    realloc_call = if self.is_async {
1915                        format!("await {realloc}")
1916                    } else {
1917                        realloc.to_string()
1918                    },
1919                );
1920
1921                // ... then consume the vector and use the block to lower the
1922                // result.
1923                self.emit_list_bounds_check(&result, &len, size);
1924                uwriteln!(self.src, "for (let i = 0; i < {vec}.length; i++) {{");
1925                uwriteln!(self.src, "const e = {vec}[i];");
1926                uwrite!(self.src, "const base = {result} + i * {size};");
1927                self.src.push_str(&body);
1928                uwrite!(self.src, "}}\n");
1929
1930                results.push(result);
1931                results.push(len);
1932            }
1933
1934            Instruction::ListLift { element, .. } => {
1935                let (body, body_results) = self.blocks.pop().unwrap();
1936                let tmp = self.tmp();
1937                let size = self.sizes.size(element).size_wasm32();
1938                let align = self.sizes.align(element).align_wasm32();
1939                let len = format!("len{tmp}");
1940                uwriteln!(self.src, "var {len} = {};", operands[1]);
1941                let base = format!("base{tmp}");
1942                uwriteln!(self.src, "var {base} = {} >>> 0;", operands[0]);
1943                self.emit_list_bounds_check(&base, &len, size);
1944                uwriteln!(
1945                    self.src,
1946                    "if ({base} % {align} !== 0) throw new TypeError(`list pointer [${{{base}}}] is not aligned to {align}`);"
1947                );
1948                let result = format!("result{tmp}");
1949                uwriteln!(self.src, "var {result} = [];");
1950                results.push(result.clone());
1951
1952                uwriteln!(self.src, "for (let i = 0; i < {len}; i++) {{");
1953                uwriteln!(self.src, "const base = {base} + i * {size};");
1954                self.src.push_str(&body);
1955                assert_eq!(body_results.len(), 1);
1956                uwriteln!(self.src, "{result}.push({});", body_results[0]);
1957                uwrite!(self.src, "}}\n");
1958                self.emit_dealloc(&base, &len, size, align);
1959            }
1960
1961            Instruction::MapLower { key, value, .. } => {
1962                let (body, body_results) = self.blocks.pop().unwrap();
1963                assert!(body_results.is_empty());
1964
1965                let tmp = self.tmp();
1966                let map = format!("map{tmp}");
1967                let entries = format!("entries{tmp}");
1968                let result = format!("result{tmp}");
1969                let len = format!("len{tmp}");
1970                let entry = self.sizes.record([*key, *value]);
1971                let size = entry.size.size_wasm32();
1972                let align = ArchitectureSize::from(entry.align).size_wasm32();
1973
1974                uwriteln!(self.src, "const {map} = {};", operands[0]);
1975                uwriteln!(
1976                    self.src,
1977                    "if (!({map} instanceof Map)) throw new TypeError('expected a Map');"
1978                );
1979                uwriteln!(self.src, "const {entries} = {map}.entries();");
1980                uwriteln!(self.src, "const {len} = {map}.size;");
1981
1982                let realloc = self.realloc.as_ref().unwrap();
1983                uwriteln!(
1984                    self.src,
1985                    "const {result} = {realloc_call}(0, 0, {align}, {len} * {size});",
1986                    realloc_call = if self.is_async {
1987                        format!("await {realloc}")
1988                    } else {
1989                        realloc.to_string()
1990                    },
1991                );
1992
1993                self.emit_list_bounds_check(&result, &len, size);
1994                uwriteln!(self.src, "let i = 0;");
1995                uwriteln!(self.src, "for (const [key, value] of {entries}) {{");
1996                uwriteln!(self.src, "const base = {result} + i * {size};");
1997                self.src.push_str(&body);
1998                uwriteln!(self.src, "i++;");
1999                uwrite!(self.src, "}}\n");
2000
2001                results.push(result);
2002                results.push(len);
2003            }
2004
2005            Instruction::MapLift { key, value, .. } => {
2006                let (body, body_results) = self.blocks.pop().unwrap();
2007                assert_eq!(body_results.len(), 2);
2008
2009                let tmp = self.tmp();
2010                let entry = self.sizes.record([*key, *value]);
2011                let entry_size = entry.size.size_wasm32();
2012                let align = entry.align.align_wasm32();
2013                let len = format!("len{tmp}");
2014                uwriteln!(self.src, "const {len} = {};", operands[1]);
2015                let base = format!("base{tmp}");
2016                uwriteln!(self.src, "const {base} = {} >>> 0;", operands[0]);
2017                self.emit_list_bounds_check(&base, &len, entry_size);
2018                let result = format!("result{tmp}");
2019                uwriteln!(self.src, "const {result} = new Map();");
2020                results.push(result.clone());
2021
2022                uwriteln!(self.src, "for (let i = 0; i < {len}; i++) {{");
2023                uwriteln!(self.src, "const base = {base} + i * {entry_size};");
2024                self.src.push_str(&body);
2025                uwriteln!(
2026                    self.src,
2027                    "{result}.set({}, {});",
2028                    body_results[0],
2029                    body_results[1]
2030                );
2031                uwrite!(self.src, "}}\n");
2032                self.emit_dealloc(&base, &len, entry_size, align);
2033            }
2034
2035            Instruction::FixedLengthListLower { size, .. } => {
2036                let tmp = self.tmp();
2037                let array = format!("array{tmp}");
2038                uwriteln!(self.src, "const {array} = {};", operands[0]);
2039                for i in 0..*size {
2040                    results.push(format!("{array}[{i}]"));
2041                }
2042            }
2043
2044            Instruction::FixedLengthListLift { .. } => {
2045                let tmp = self.tmp();
2046                let result = format!("result{tmp}");
2047                uwriteln!(self.src, "const {result} = [{}];", operands.join(", "));
2048                results.push(result);
2049            }
2050
2051            Instruction::FixedLengthListLowerToMemory {
2052                element, size: len, ..
2053            } => {
2054                let (body, body_results) = self.blocks.pop().unwrap();
2055                assert!(body_results.is_empty());
2056
2057                let tmp = self.tmp();
2058                let array = format!("array{tmp}");
2059                uwriteln!(self.src, "const {array} = {};", operands[0]);
2060                let addr = format!("addr{tmp}");
2061                uwriteln!(self.src, "const {addr} = {};", operands[1]);
2062                let elem_size = self.sizes.size(element).size_wasm32();
2063
2064                uwriteln!(self.src, "for (let i = 0; i < {len}; i++) {{");
2065                uwriteln!(self.src, "const e = {array}[i];");
2066                uwrite!(self.src, "const base = {addr} + i * {elem_size};");
2067                self.src.push_str(&body);
2068                uwrite!(self.src, "}}\n");
2069            }
2070
2071            Instruction::FixedLengthListLiftFromMemory {
2072                element, size: len, ..
2073            } => {
2074                let (body, body_results) = self.blocks.pop().unwrap();
2075                assert_eq!(body_results.len(), 1);
2076
2077                let tmp = self.tmp();
2078                let addr = format!("addr{tmp}");
2079                uwriteln!(self.src, "const {addr} = {};", operands[0]);
2080                let elem_size = self.sizes.size(element).size_wasm32();
2081                let result = format!("result{tmp}");
2082                uwriteln!(self.src, "const {result} = [];");
2083                results.push(result.clone());
2084
2085                uwriteln!(self.src, "for (let i = 0; i < {len}; i++) {{");
2086                uwrite!(self.src, "const base = {addr} + i * {elem_size};");
2087                self.src.push_str(&body);
2088                uwriteln!(self.src, "{result}.push({});", body_results[0]);
2089                uwrite!(self.src, "}}\n");
2090            }
2091
2092            Instruction::IterElem { .. } => results.push("e".to_string()),
2093
2094            Instruction::IterMapKey { .. } => results.push("key".to_string()),
2095
2096            Instruction::IterMapValue { .. } => results.push("value".to_string()),
2097
2098            Instruction::IterBasePointer => results.push("base".to_string()),
2099
2100            Instruction::CallWasm { name, sig } => {
2101                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
2102                let get_component_state = self.task_intrinsic(Intrinsic::Component(
2103                    ComponentIntrinsic::GetOrCreateAsyncState,
2104                ));
2105                let component_idx_expr = self
2106                    .component_state
2107                    .as_ref()
2108                    .map(|state| state.get_js_exprs().component_idx)
2109                    .unwrap_or_else(|| "-1".into());
2110                let has_post_return = self.post_return.is_some();
2111                let is_async = self.is_async;
2112                uwriteln!(
2113                    self.src,
2114                    "{debug_log_fn}('{prefix} [Instruction::CallWasm] enter', {{
2115                         funcName: '{name}',
2116                         paramCount: {param_count},
2117                         async: {is_async},
2118                         postReturn: {has_post_return},
2119                      }});",
2120                    param_count = sig.params.len(),
2121                    prefix = self.tracing_prefix,
2122                );
2123
2124                // TODO: trap if this component is already on the call stack (re-entrancy)
2125
2126                // TODO(threads): start a thread
2127                // TODO(threads): Task#enter needs to be called with the thread that is executing (inside thread_func)
2128                // TODO(threads): thread_func will contain the actual call rather than attempting to execute immediately
2129
2130                // Output result binding preamble (e.g. 'var ret =', 'var [ ret0, ret1] = exports...() ')
2131                // along with the code to perofrm the call
2132                let sig_results_length = sig.results.len();
2133                let (vars_init, assignment_lhs) =
2134                    self.generate_result_assignment_lhs(sig_results_length, results, is_async);
2135
2136                let (call_prefix, call_err_cleanup) =
2137                    if self.requires_async_porcelain | self.is_async {
2138                        (
2139                            "await ",
2140                            format!(
2141                                r#"
2142                              {debug_log_fn}('[Instruction::CallWasm] error during async call', {{
2143                                  taskID: task.id(),
2144                                  err,
2145                              }});
2146                              {get_component_state}({component_idx_expr}).markTrapped(err);
2147                              task.setErrored(err);
2148                              task.reject(err);
2149                              task.exit();
2150                              return task.completionPromise();
2151                            "#
2152                            ),
2153                        )
2154                    } else {
2155                        (
2156                            "",
2157                            format!(
2158                                r#"
2159                              {debug_log_fn}('[Instruction::CallWasm] error during sync call', {{
2160                                  taskID: task.id(),
2161                                  err,
2162                              }});
2163                              {get_component_state}({component_idx_expr}).markTrapped(err);
2164                              task.setErrored(err);
2165                              task.reject(err);
2166                              task.exit();
2167                              throw err;
2168                            "#
2169                            ),
2170                        )
2171                    };
2172
2173                let args = if self.asmjs {
2174                    let split_i64 =
2175                        self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::SplitBigInt64));
2176
2177                    let mut args = Vec::new();
2178                    for (i, op) in operands
2179                        .drain(operands.len() - sig.params.len()..)
2180                        .enumerate()
2181                    {
2182                        if matches!(sig.params[i], WasmType::I64) {
2183                            args.push(format!("...({split_i64}({op}))"));
2184                        } else {
2185                            args.push(op);
2186                        }
2187                    }
2188                    args
2189                } else {
2190                    mem::take(operands)
2191                };
2192
2193                let mut callee_invoke = format!(
2194                    "{callee}({args})",
2195                    callee = self.callee,
2196                    args = args.join(", ")
2197                );
2198
2199                if self.asmjs {
2200                    // wasm2js does not support multivalue return
2201                    // if/when it does, this will need changing.
2202                    assert!(sig.results.len() <= 1);
2203                    // same with async(?)
2204                    assert!(!self.requires_async_porcelain && !self.is_async);
2205
2206                    if sig.results.len() == 1 && matches!(sig.results[0], WasmType::I64) {
2207                        let merge_i64 = self
2208                            .intrinsic(Intrinsic::Conversion(ConversionIntrinsic::MergeBigInt64));
2209                        callee_invoke =
2210                            format!("{merge_i64}({callee_invoke}, task.tmpRetI64HighBits)");
2211                    }
2212                }
2213
2214                // Argument lowering can await realloc and allow another task
2215                // to run. Reinstall this task immediately before entering Wasm.
2216                let call_wrapper = self.task_intrinsic(Intrinsic::WithGlobalCurrentTaskMetaFn);
2217                if task_managed {
2218                    uwriteln!(
2219                        self.src,
2220                        r#"
2221                      {vars_init}
2222                      try {{
2223                           {assignment_lhs} {call_prefix}{call_wrapper}({{
2224                               taskID: task.id(),
2225                               componentIdx: task.componentIdx(),
2226                               fn: () => {callee_invoke},
2227                           }});
2228                      }} catch (err) {{
2229                          {call_err_cleanup}
2230                      }}
2231                      task.endFirstSlice();
2232                    "#,
2233                    );
2234                } else {
2235                    uwriteln!(
2236                        self.src,
2237                        "{vars_init}\n{assignment_lhs}{call_prefix}{callee_invoke};"
2238                    );
2239                }
2240
2241                // Core wasm32 pointers arrive as signed i32 values. Normalize
2242                // them before any host-side arithmetic, which must not wrap.
2243                for (result, ty) in results.iter_mut().zip(&sig.results) {
2244                    if matches!(ty, WasmType::Pointer) {
2245                        *result = format!("({result} >>> 0)");
2246                    }
2247                }
2248
2249                if self.tracing_enabled {
2250                    let prefix = self.tracing_prefix;
2251                    let to_result_string =
2252                        self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToResultString));
2253                    uwriteln!(
2254                        self.src,
2255                        "console.error(`{prefix} return {}`);",
2256                        if sig_results_length > 0 || !results.is_empty() {
2257                            format!("result=${{{to_result_string}(ret)}}")
2258                        } else {
2259                            "".to_string()
2260                        }
2261                    );
2262                }
2263            }
2264
2265            // Call to an imported interface (normally provided by the host)
2266            Instruction::CallInterface { func, async_ } => {
2267                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
2268                let get_component_state = self.task_intrinsic(Intrinsic::Component(
2269                    ComponentIntrinsic::GetOrCreateAsyncState,
2270                ));
2271                let track_host_operation = self
2272                    .task_intrinsic(Intrinsic::Component(ComponentIntrinsic::TrackHostOperation));
2273                let start_current_task_fn = self.task_intrinsic(Intrinsic::AsyncTask(
2274                    AsyncTaskIntrinsic::CreateNewCurrentTask,
2275                ));
2276                let current_task_get_fn =
2277                    self.task_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
2278
2279                // At first, use the global current task metadata, in case we are executing from
2280                // inside a with-global-current-task wrapper
2281                let get_global_current_task_meta_fn =
2282                    self.task_intrinsic(Intrinsic::GetGlobalCurrentTaskMetaFn);
2283
2284                uwriteln!(
2285                    self.src,
2286                    "{debug_log_fn}('{prefix} [Instruction::CallInterface] ({async_}, @ enter)');",
2287                    prefix = self.tracing_prefix,
2288                    async_ = async_.then_some("async").unwrap_or("sync"),
2289                );
2290
2291                // Determine the callee function and arguments
2292                let (callee_fn_js, callee_args_js) = if self.callee_resource_dynamic {
2293                    (
2294                        format!("{}.{}", operands[0], self.callee),
2295                        operands[1..].join(", "),
2296                    )
2297                } else {
2298                    (self.callee.into(), operands.join(", "))
2299                };
2300
2301                if task_managed {
2302                    uwriteln!(self.src, "const hostProvided = true;");
2303                }
2304
2305                // Set task memory index and memory object
2306                let (component_idx_expr, callback_fn_name_expr, get_callback_fn_expr) =
2307                    if let Some(state) = &self.component_state {
2308                        let ComponentStateJsExprs {
2309                            component_idx,
2310                            callback_fn_name,
2311                            get_callback_fn,
2312                            ..
2313                        } = state.get_js_exprs();
2314                        (component_idx, callback_fn_name, get_callback_fn)
2315                    } else {
2316                        ("-1".into(), "null".into(), "() => null".into())
2317                    };
2318
2319                // Start the necessary subtasks and/or host task
2320                //
2321                // We must create a subtask in the case of an async host import.
2322                //
2323                // If there's no parent task, we're not executing in a subtask situation,
2324                // so we can just create the new task and immediately continue execution.
2325                //
2326                // If there *is* a parent task, then we are likely about to create new task that
2327                // matches/belongs to an existing subtask in the parent task.
2328                //
2329                // If we're dealing with a function that has been marked as a host import, then
2330                // we expect that `Trampoline::LowerImport` and relevant intrinsics were called before
2331                // this, and a subtask has been set up.
2332                //
2333                if task_managed {
2334                    uwriteln!(
2335                        self.src,
2336                        r#"
2337                    let parentTask;
2338                    let task;
2339                    let subtask;
2340
2341                    const createTask = () => {{
2342                        const results = {start_current_task_fn}({{
2343                            componentIdx: -1,
2344                            isAsync: {is_async},
2345                            entryFnName: '{fn_name}',
2346                            getCallbackFn: {get_callback_fn_expr},
2347                            callbackFnName: {callback_fn_name_expr},
2348                            errHandling: '{err_handling}',
2349                            callingWasmExport: false,
2350                        }});
2351                        task = results[0];
2352                    }};
2353
2354                    taskCreation: {{
2355                        parentTask = {current_task_get_fn}(
2356                            {component_idx_expr},
2357                            {get_global_current_task_meta_fn}({component_idx_expr})?.taskID,
2358                        )?.task;
2359
2360                        if (!parentTask) {{
2361                            createTask();
2362                            break taskCreation;
2363                        }}
2364
2365                        createTask();
2366
2367                        if (hostProvided) {{
2368                            subtask = parentTask.getLatestSubtask();
2369                            if (!subtask) {{
2370                                throw new Error(`Missing subtask (in parent task [${{parentTask.id()}}]) for host import, has the import been lowered? (ensure asyncImports are set properly)`);
2371                            }}
2372                            task.setParentSubtask(subtask);
2373                        }}
2374                    }}
2375                    "#,
2376                        is_async = self.is_async,
2377                        fn_name = self.callee,
2378                        err_handling = self.err.to_js_string(),
2379                    );
2380                }
2381
2382                let is_async = self.requires_async_porcelain || *async_;
2383
2384                // If we're async then we *know* that there is a result, even if the functoin doesn't have one
2385                // at the CM level -- async functions always return
2386                let fn_wasm_result_count = if func.result.is_none() { 0 } else { 1 };
2387
2388                // If the task is async, do an explicit wait for backpressure before the call execution
2389                if task_managed && is_async {
2390                    uwriteln!(
2391                        self.src,
2392                        r#"
2393                        const started = await task.enter({{ isHost: hostProvided }});
2394                        if (!started) {{
2395                            {debug_log_fn}('[Instruction::CallInterface] failed to enter task', {{
2396                                taskID: task.id(),
2397                                subtaskID: task.getParentSubtask()?.id(),
2398                            }});
2399                            // (the deadlock detector records why entry was given up on)
2400                      throw task.isErrored() ?? new Error("failed to enter task");
2401                        }}
2402                        "#,
2403                    );
2404                } else if task_managed {
2405                    uwriteln!(self.src, "const started = task.enterSync();",);
2406                }
2407
2408                // Build the JS expression that calls the callee
2409                let (call_prefix, call_wrapper, call_err_cleanup) = if is_async
2410                    || self.requires_async_porcelain
2411                {
2412                    (
2413                        "await ",
2414                        self.task_intrinsic(Intrinsic::WithGlobalCurrentTaskMetaFnAsync),
2415                        format!(
2416                            r#"
2417                              {debug_log_fn}('[Instruction::CallInterface] error during async call', {{
2418                                  taskID: task.id(),
2419                                  subtaskID: task.getParentSubtask()?.id(),
2420                                  err,
2421                              }});
2422                              {get_component_state}({component_idx_expr}).markTrapped(err);
2423                              task.setErrored(err);
2424                              task.reject(err);
2425                              task.exit();
2426                              return task.completionPromise();
2427                            "#
2428                        ),
2429                    )
2430                } else {
2431                    (
2432                        "",
2433                        self.task_intrinsic(Intrinsic::WithGlobalCurrentTaskMetaFn),
2434                        format!(
2435                            r#"
2436                              {debug_log_fn}('[Instruction::CallInterface] error during sync call', {{
2437                                  taskID: task.id(),
2438                                  subtaskID: task.getParentSubtask()?.id(),
2439                                  err,
2440                              }});
2441                              {get_component_state}({component_idx_expr}).markTrapped(err);
2442                              task.setErrored(err);
2443                              task.reject(err);
2444                              task.exit();
2445                              throw err;
2446                            "#
2447                        ),
2448                    )
2449                };
2450
2451                let call = if task_managed && is_async {
2452                    // Hand the raw host return value to the subtask, so it can be disposed
2453                    // if the guest cancels the call and discards the result
2454                    format!(
2455                        r#"{call_prefix} {call_wrapper}({{
2456                              componentIdx: task.componentIdx(),
2457                              taskID: task.id(),
2458                              fn: () => {track_host_operation}(() => {{
2459                                  const hostRet = {callee_fn_js}({callee_args_js});
2460                                  subtask?.setHostPendingResult(hostRet);
2461                                  return hostRet;
2462                              }}),
2463                          }})
2464                        "#,
2465                    )
2466                } else if task_managed {
2467                    format!(
2468                        r#"{call_prefix} {call_wrapper}({{
2469                              componentIdx: task.componentIdx(),
2470                              taskID: task.id(),
2471                              fn: () => {track_host_operation}(() => {callee_fn_js}({callee_args_js})),
2472                          }})
2473                        "#,
2474                    )
2475                } else {
2476                    format!("{call_prefix}{callee_fn_js}({callee_args_js})")
2477                };
2478                let (vars_init, assignment_lhs) = if self.err == ErrHandling::ResultCatchHandler {
2479                    results.push("ret".to_string());
2480                    ("let ret;".to_string(), "ret = ".to_string())
2481                } else {
2482                    self.generate_result_assignment_lhs(fn_wasm_result_count, results, is_async)
2483                };
2484                uwriteln!(self.src, "{vars_init}");
2485                let borrows = if !task_managed && self.clear_resource_borrows {
2486                    let queue =
2487                        self.intrinsic(Intrinsic::Resource(ResourceIntrinsic::CurResourceBorrows));
2488                    let borrows = format!("borrows{}", self.tmp());
2489                    uwriteln!(
2490                        self.src,
2491                        "const {borrows} = {queue};
2492                        {queue} = [];
2493                        try {{"
2494                    );
2495                    Some(borrows)
2496                } else {
2497                    None
2498                };
2499
2500                match self.err {
2501                    // If configured to do *no* error handling at all or throw
2502                    // error objects directly, we can simply perform the call
2503                    ErrHandling::None | ErrHandling::ThrowResultErr => {
2504                        if task_managed {
2505                            uwriteln!(
2506                                self.src,
2507                                r#"
2508                              try {{
2509                                 {assignment_lhs}{call};
2510                              }} catch (err) {{
2511                                  {call_err_cleanup}
2512                              }}
2513                            "#
2514                            );
2515                        } else {
2516                            uwriteln!(self.src, "{assignment_lhs}{call};");
2517                        }
2518                    }
2519                    // If configured to force all thrown errors into result objects,
2520                    // then we add a try/catch around the call
2521                    ErrHandling::ResultCatchHandler => {
2522                        let (wrapped_ok, wrapped_err) = unambiguous_result_wrapper_tags(
2523                            self.resolve,
2524                            get_thrown_type(self.resolve, func.result).unwrap().0,
2525                        );
2526                        let host_ret = format!("hostRet{}", self.tmp());
2527                        let wrapper_test = match (wrapped_ok, wrapped_err) {
2528                            (true, true) => {
2529                                format!("({host_ret}.tag === 'ok' || {host_ret}.tag === 'err')")
2530                            }
2531                            (true, false) => format!("{host_ret}.tag === 'ok'"),
2532                            (false, true) => format!("{host_ret}.tag === 'err'"),
2533                            (false, false) => "false".to_string(),
2534                        };
2535                        // result<_, string> allows JS error coercion only, while
2536                        // any other result type will trap for arbitrary JS errors.
2537                        let err_payload = if let (_, Some(Type::Id(err_ty))) =
2538                            get_thrown_type(self.resolve, func.result).unwrap()
2539                        {
2540                            match &self.resolve.types[*err_ty].kind {
2541                                TypeDefKind::Type(Type::String) => {
2542                                    self.intrinsic(Intrinsic::GetErrorPayloadString)
2543                                }
2544                                _ => self.intrinsic(Intrinsic::GetErrorPayload),
2545                            }
2546                        } else {
2547                            self.intrinsic(Intrinsic::GetErrorPayload)
2548                        };
2549                        let trap_check = task_managed.then(|| format!(
2550                            "if ({get_component_state}({component_idx_expr}).markTrapped(e)) {{ throw e; }}"
2551                        ));
2552                        uwriteln!(
2553                            self.src,
2554                            r#"
2555                            try {{
2556                                const {host_ret} = {call};
2557                                ret = {host_ret} !== null && typeof {host_ret} === 'object' && {wrapper_test}
2558                                    ? {host_ret}
2559                                    : {{ tag: 'ok', val: {host_ret} }};
2560                            }} catch (e) {{
2561                                {trap_check}
2562                                ret = {{ tag: 'err', val: {err_payload}(e) }};
2563                            }}
2564                            "#,
2565                            trap_check = trap_check.as_deref().unwrap_or_default(),
2566                        );
2567                    }
2568                }
2569
2570                if self.tracing_enabled {
2571                    let prefix = self.tracing_prefix;
2572                    let to_result_string =
2573                        self.intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToResultString));
2574                    uwriteln!(
2575                        self.src,
2576                        "console.error(`{prefix} return {}`);",
2577                        if fn_wasm_result_count > 0 || !results.is_empty() {
2578                            format!("result=${{{to_result_string}(ret)}}")
2579                        } else {
2580                            "".to_string()
2581                        }
2582                    );
2583                }
2584
2585                // TODO: if it was an async call, we may not be able to clear the borrows yet.
2586                // save them to the task/ensure they are added to the task's list of borrows?
2587                //
2588                // TODO: if there is a subtask, we must not clear borrows until subtask.deliverReturn
2589                // is called.
2590
2591                // After a high level call, we need to deactivate the component resource borrows.
2592                if self.clear_resource_borrows {
2593                    let symbol_resource_handle = self.intrinsic(Intrinsic::SymbolResourceHandle);
2594                    let cur_resource_borrows = if let Some(borrows) = borrows {
2595                        uwriteln!(self.src, "}} finally {{");
2596                        borrows
2597                    } else {
2598                        self.intrinsic(Intrinsic::Resource(ResourceIntrinsic::CurResourceBorrows))
2599                    };
2600                    uwriteln!(
2601                        self.src,
2602                        "for (const entry of {cur_resource_borrows}) {{
2603                            const rsc = entry.rsc ?? entry;
2604                            if (entry.drop) {{
2605                                if (rsc[{symbol_resource_handle}]) {{
2606                                    entry.drop(rsc[{symbol_resource_handle}]);
2607                                }}
2608                            }}
2609                            rsc[{symbol_resource_handle}] = undefined;
2610                        }}"
2611                    );
2612                    if task_managed {
2613                        uwriteln!(self.src, "{cur_resource_borrows} = [];");
2614                    } else {
2615                        uwriteln!(self.src, "}}");
2616                    }
2617                    self.clear_resource_borrows = false;
2618                }
2619            }
2620
2621            Instruction::Return {
2622                func,
2623                amt: stack_value_count,
2624            } => {
2625                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
2626                uwriteln!(
2627                    self.src,
2628                    "{debug_log_fn}('{prefix} [Instruction::Return]', {{
2629                         funcName: '{func_name}',
2630                         paramCount: {stack_value_count},
2631                         async: {is_async},
2632                         postReturn: {post_return_present}
2633                      }});",
2634                    func_name = func.name,
2635                    post_return_present = self.post_return.is_some(),
2636                    is_async = self.is_async,
2637                    prefix = self.tracing_prefix,
2638                );
2639
2640                // Get the component idx expr
2641                let component_idx_expr = if let Some(state) = &self.component_state {
2642                    let ComponentStateJsExprs { component_idx, .. } = state.get_js_exprs();
2643                    component_idx
2644                } else {
2645                    "-1".into()
2646                };
2647
2648                // Build the post return functionality
2649                // to clean up tasks and possibly return values
2650                let get_or_create_async_state_fn = self.task_intrinsic(Intrinsic::Component(
2651                    ComponentIntrinsic::GetOrCreateAsyncState,
2652                ));
2653                let gen_post_return_js =
2654                    |(post_return_call, ret_stmt): (String, Option<String>)| {
2655                        if !task_managed {
2656                            return format!("{post_return_call}\n{}", ret_stmt.unwrap_or_default());
2657                        }
2658                        format!(
2659                            r#"
2660                        let cstate = {get_or_create_async_state_fn}({component_idx_expr});
2661                        cstate.mayLeave = false;
2662                        {post_return_call}
2663                        cstate.mayLeave = true;
2664                        task.exit();
2665                        {ret_stmt}
2666                            "#,
2667                            ret_stmt = ret_stmt.unwrap_or_default(),
2668                        )
2669                    };
2670
2671                // Depending how many values are on the stack after returning, we must execute differently.
2672                //
2673                // In particular, if this function is async (distinct from whether async porcelain was necessary or not),
2674                // rather than simply executing the function we must return (or block for) the promise that was created
2675                // for the task.
2676                match stack_value_count {
2677                    // (sync) Handle no result case
2678                    0 => {
2679                        if task_managed {
2680                            uwriteln!(self.src, "task.resolve([ret]);");
2681                        }
2682                        if let Some(f) = &self.post_return {
2683                            uwriteln!(
2684                                self.src,
2685                                "{post_return_js}",
2686                                post_return_js = gen_post_return_js((
2687                                    format!("{}{f}();", if self.is_async { "await " } else { "" }),
2688                                    None,
2689                                )),
2690                            );
2691                        } else if task_managed {
2692                            uwriteln!(self.src, "task.exit();");
2693                        }
2694                        if !task_managed {
2695                            uwriteln!(self.src, "return;");
2696                        }
2697                    }
2698
2699                    // (sync) Handle single `result<t>` case
2700                    1 if self.err == ErrHandling::ThrowResultErr => {
2701                        let op = &operands[0];
2702                        let throw_err = if self.no_component_error_wrapping {
2703                            "throw retCopy.val;".to_string()
2704                        } else {
2705                            let component_err = self.intrinsic(Intrinsic::ComponentError);
2706                            format!("throw new {component_err}(retCopy.val);")
2707                        };
2708
2709                        uwriteln!(self.src, "const retCopy = {op};");
2710                        if task_managed {
2711                            uwriteln!(self.src, "task.resolve([retCopy.val]);");
2712                        }
2713
2714                        if let Some(f) = &self.post_return {
2715                            uwriteln!(
2716                                self.src,
2717                                "{}",
2718                                gen_post_return_js((
2719                                    format!(
2720                                        "{}{f}(ret);",
2721                                        if self.is_async { "await " } else { "" }
2722                                    ),
2723                                    None,
2724                                ))
2725                            );
2726                        } else if task_managed {
2727                            uwriteln!(self.src, "task.exit();");
2728                        }
2729
2730                        uwriteln!(
2731                            self.src,
2732                            r#"
2733                              if (typeof retCopy === 'object' && retCopy.tag === 'err') {{
2734                                  {throw_err}
2735                              }}
2736                              return retCopy.val;
2737                            "#
2738                        );
2739                    }
2740
2741                    // (sync) Handle all other cases (including single parameter non-result<t>)
2742                    stack_value_count => {
2743                        let ret_val = match stack_value_count {
2744                            0 => unreachable!(
2745                                "unexpectedly zero return values for synchronous return"
2746                            ),
2747                            1 => operands[0].to_string(),
2748                            _ => format!("[{}]", operands.join(", ")),
2749                        };
2750                        // The surrounding FutureValue represents the future returned by the WIT
2751                        // function, so the manual async transport must consume the lifted future
2752                        // before boxing its payload for FutureValue's start operation.
2753                        let return_val = if self.wrap_async_future_result {
2754                            format!("{{ value: await {ret_val} }}")
2755                        } else {
2756                            ret_val.clone()
2757                        };
2758
2759                        if task_managed {
2760                            uwriteln!(self.src, "task.resolve([{ret_val}]);");
2761                        }
2762
2763                        // Handle the post return if necessary
2764                        if let Some(post_return_fn) = self.post_return {
2765                            // In the case there is a post return function, we'll want to copy the value
2766                            // then perform the post return before leaving
2767
2768                            // Write out the assignment for the given return value
2769                            uwriteln!(self.src, "const retCopy = {ret_val};");
2770                            let post_return_val = if self.wrap_async_future_result {
2771                                "{ value: await retCopy }"
2772                            } else {
2773                                "retCopy"
2774                            };
2775
2776                            // Generate the JS that should perform the post return w/ the result
2777                            // and pass a copy fo the result to the actual caller
2778                            let post_return_js = gen_post_return_js((
2779                                format!(
2780                                    "{}{post_return_fn}(ret);",
2781                                    if self.is_async { "await " } else { "" }
2782                                ),
2783                                Some([format!("return {post_return_val};")].join("\n")),
2784                            ));
2785                            uwriteln!(self.src, "{post_return_js}");
2786                        } else {
2787                            if task_managed {
2788                                uwriteln!(self.src, "task.exit();");
2789                            }
2790                            uwriteln!(self.src, "return {return_val};")
2791                        }
2792                    }
2793                }
2794            }
2795
2796            Instruction::I32Load { offset } => self.load("getInt32", *offset, operands, results),
2797
2798            Instruction::I64Load { offset } => self.load("getBigInt64", *offset, operands, results),
2799
2800            Instruction::F32Load { offset } => self.load("getFloat32", *offset, operands, results),
2801
2802            Instruction::F64Load { offset } => self.load("getFloat64", *offset, operands, results),
2803
2804            Instruction::I32Load8U { offset } => self.load("getUint8", *offset, operands, results),
2805
2806            Instruction::I32Load8S { offset } => self.load("getInt8", *offset, operands, results),
2807
2808            Instruction::I32Load16U { offset } => {
2809                self.load("getUint16", *offset, operands, results)
2810            }
2811
2812            Instruction::I32Load16S { offset } => self.load("getInt16", *offset, operands, results),
2813
2814            Instruction::I32Store { offset } => self.store("setInt32", *offset, operands),
2815
2816            Instruction::I64Store { offset } => self.store("setBigInt64", *offset, operands),
2817
2818            Instruction::F32Store { offset } => self.store("setFloat32", *offset, operands),
2819
2820            Instruction::F64Store { offset } => self.store("setFloat64", *offset, operands),
2821
2822            Instruction::I32Store8 { offset } => self.store("setInt8", *offset, operands),
2823
2824            Instruction::I32Store16 { offset } => self.store("setInt16", *offset, operands),
2825
2826            Instruction::LengthStore { offset } => self.store("setUint32", *offset, operands),
2827
2828            Instruction::LengthLoad { offset } => {
2829                self.load("getUint32", *offset, operands, results)
2830            }
2831
2832            Instruction::PointerStore { offset } => self.store("setUint32", *offset, operands),
2833
2834            Instruction::PointerLoad { offset } => {
2835                self.load("getUint32", *offset, operands, results)
2836            }
2837
2838            Instruction::Malloc { size, align, .. } => {
2839                let tmp = self.tmp();
2840                let realloc = self.realloc.as_ref().unwrap();
2841                let ptr = format!("ptr{tmp}");
2842                uwriteln!(
2843                    self.src,
2844                    "var {ptr} = {realloc_call}(0, 0, {align}, {size});",
2845                    align = align.align_wasm32(),
2846                    realloc_call = if self.is_async {
2847                        format!("await {realloc}")
2848                    } else {
2849                        realloc.to_string()
2850                    },
2851                    size = size.size_wasm32()
2852                );
2853                results.push(ptr);
2854            }
2855
2856            Instruction::HandleLift { handle, .. } => {
2857                let (Handle::Own(ty) | Handle::Borrow(ty)) = handle;
2858                let resource_ty = &crate::dealias(self.resolve, *ty);
2859                let ResourceTable { imported, data } = &self.resource_map[resource_ty];
2860
2861                let is_own = matches!(handle, Handle::Own(_));
2862                let rsc = format!("rsc{}", self.tmp());
2863                let handle = format!("handle{}", self.tmp());
2864                uwriteln!(self.src, "var {handle} = {};", &operands[0]);
2865
2866                match data {
2867                    ResourceData::Host {
2868                        tid,
2869                        rid,
2870                        component_idx,
2871                        needs_task_context,
2872                        local_name,
2873                        dtor_name,
2874                    } => {
2875                        let tid = tid.as_u32();
2876                        let rid = rid.as_u32();
2877                        let symbol_dispose = self.intrinsic(Intrinsic::SymbolDispose);
2878                        let rsc_table_remove = self
2879                            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
2880                        let rsc_flag = self
2881                            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
2882                        if !imported {
2883                            let symbol_resource_handle =
2884                                self.intrinsic(Intrinsic::SymbolResourceHandle);
2885
2886                            uwriteln!(
2887                                self.src,
2888                                "var {rsc} = new.target === {local_name} ? this : Object.create({local_name}.prototype);"
2889                            );
2890
2891                            if is_own {
2892                                // Sending an own handle out to JS as a return value - set up finalizer and disposal.
2893                                let empty_func = self
2894                                    .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
2895                                uwriteln!(self.src,
2896                                            "Object.defineProperty({rsc}, {symbol_resource_handle}, {{ writable: true, value: {handle} }});
2897                                    finalizationRegistry{tid}.register({rsc}, {handle}, {rsc});");
2898                                let component_idx = component_idx.as_u32();
2899                                let dtor_call = dtor_name.as_ref().map(|dtor| {
2900                                    if *needs_task_context {
2901                                        let call_resource_destructor = self.intrinsic(
2902                                            Intrinsic::Resource(ResourceIntrinsic::ResourceDestructorCall),
2903                                        );
2904                                        format!(
2905                                            "{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {dtor}, rep: handleEntry.rep }});"
2906                                        )
2907                                    } else {
2908                                        format!("{dtor}(handleEntry.rep);")
2909                                    }
2910                                }).unwrap_or_default();
2911                                // Explicitly dropping an own handle must always release the host-side
2912                                // handle and finalizer registration. A component-defined destructor is
2913                                // an additional callback, not a prerequisite for resource cleanup.
2914                                //
2915                                // Disable Symbol.dispose and clear the handle before calling the
2916                                // component destructor so repeated or re-entrant disposal is a no-op.
2917                                uwriteln!(
2918                                            self.src,
2919                                            "Object.defineProperty({rsc}, {symbol_dispose}, {{ writable: true, value: function () {{
2920                                        finalizationRegistry{tid}.unregister({rsc});
2921                                        const handleEntry = {rsc_table_remove}(handleTable{tid}, {handle});
2922                                        {rsc}[{symbol_dispose}] = {empty_func};
2923                                        {rsc}[{symbol_resource_handle}] = undefined;
2924                                        {dtor_call}
2925                                    }}}});"
2926                                        );
2927                            } else {
2928                                // Borrow handles of local resources have rep handles, which we carry through here.
2929                                uwriteln!(
2930                                    self.src,
2931                                    "Object.defineProperty({rsc}, {symbol_resource_handle}, {{ writable: true, value: {handle} }});"
2932                                );
2933                            }
2934                        } else {
2935                            let rep = format!("rep{}", self.tmp());
2936                            // Imported handles either lift as instance capture from a previous lowering,
2937                            // or we create a new JS class to represent it.
2938                            let symbol_resource_rep = self.intrinsic(Intrinsic::SymbolResourceRep);
2939                            let symbol_resource_handle =
2940                                self.intrinsic(Intrinsic::SymbolResourceHandle);
2941
2942                            uwriteln!(
2943                                self.src,
2944                                r#"
2945                                  var {rep} = handleTable{tid}[({handle} << 1) + 1] & ~{rsc_flag};
2946                                  var {rsc} = captureTable{rid}.get({rep});
2947                                  if (!{rsc}) {{
2948                                      {rsc} = Object.create({local_name}.prototype);
2949                                      Object.defineProperty({rsc}, {symbol_resource_handle}, {{ writable: true, value: {handle} }});
2950                                      Object.defineProperty({rsc}, {symbol_resource_rep}, {{ writable: true, value: {rep} }});
2951                                  }}
2952                                "#,
2953                            );
2954
2955                            if is_own {
2956                                // An own lifting is a transfer to JS, so existing own handle is implicitly dropped.
2957                                uwriteln!(
2958                                    self.src,
2959                                    "else {{
2960                                        captureTable{rid}.delete({rep});
2961                                    }}
2962                                    {rsc_table_remove}(handleTable{tid}, {handle});"
2963                                );
2964                            }
2965                        }
2966
2967                        // Borrow handles are tracked to release after the call by CallInterface.
2968                        if !is_own {
2969                            let cur_resource_borrows = self.intrinsic(Intrinsic::Resource(
2970                                ResourceIntrinsic::CurResourceBorrows,
2971                            ));
2972                            uwriteln!(self.src, "{cur_resource_borrows}.push({rsc});");
2973                            self.clear_resource_borrows = true;
2974                        }
2975                    }
2976
2977                    ResourceData::Guest {
2978                        resource_name,
2979                        prefix,
2980                        extra,
2981                    } => {
2982                        assert!(
2983                            extra.is_none(),
2984                            "plain resource handles do not carry extra data"
2985                        );
2986
2987                        let symbol_resource_handle =
2988                            self.intrinsic(Intrinsic::SymbolResourceHandle);
2989                        let prefix = prefix.as_deref().unwrap_or("");
2990                        let lower_camel = resource_name.to_lower_camel_case();
2991
2992                        if !imported {
2993                            if is_own {
2994                                uwriteln!(
2995                                    self.src,
2996                                    "var {rsc} = repTable.get($resource_{prefix}rep${lower_camel}({handle})).rep;"
2997                                );
2998                                uwrite!(
2999                                    self.src,
3000                                    r#"
3001                                      repTable.delete({handle});
3002                                      delete {rsc}[{symbol_resource_handle}];
3003                                      finalizationRegistry_export${prefix}{lower_camel}.unregister({rsc});
3004                                    "#
3005                                );
3006                            } else {
3007                                uwriteln!(self.src, "var {rsc} = repTable.get({handle}).rep;");
3008                            }
3009                        } else {
3010                            let upper_camel = resource_name.to_upper_camel_case();
3011
3012                            uwrite!(
3013                                self.src,
3014                                r#"
3015                                  var {rsc} = new.target === import_{prefix}{upper_camel} ? this : Object.create(import_{prefix}{upper_camel}.prototype);
3016                                   Object.defineProperty({rsc}, {symbol_resource_handle}, {{ writable: true, value: {handle} }});
3017                                "#
3018                            );
3019
3020                            uwriteln!(
3021                                self.src,
3022                                "finalizationRegistry_import${prefix}{lower_camel}.register({rsc}, {handle}, {rsc});",
3023                            );
3024
3025                            if !is_own {
3026                                let cur_resource_borrows = self.intrinsic(Intrinsic::Resource(
3027                                    ResourceIntrinsic::CurResourceBorrows,
3028                                ));
3029                                uwriteln!(
3030                                    self.src,
3031                                    "{cur_resource_borrows}.push({{ rsc: {rsc}, drop: $resource_import${prefix}drop${lower_camel} }});"
3032                                );
3033                                self.clear_resource_borrows = true;
3034                            }
3035                        }
3036                    }
3037                }
3038                results.push(rsc);
3039            }
3040
3041            Instruction::HandleLower { handle, name, .. } => {
3042                let (Handle::Own(ty) | Handle::Borrow(ty)) = handle;
3043                let is_own = matches!(handle, Handle::Own(_));
3044                let ResourceTable { imported, data } =
3045                    &self.resource_map[&crate::dealias(self.resolve, *ty)];
3046
3047                let class_name = name.to_upper_camel_case();
3048                let handle = format!("handle{}", self.tmp());
3049                let symbol_resource_handle = self.intrinsic(Intrinsic::SymbolResourceHandle);
3050                let symbol_dispose = self.intrinsic(Intrinsic::SymbolDispose);
3051                let op = &operands[0];
3052
3053                match data {
3054                    ResourceData::Host {
3055                        tid,
3056                        rid,
3057                        local_name,
3058                        ..
3059                    } => {
3060                        let tid = tid.as_u32();
3061                        let rid = rid.as_u32();
3062
3063                        match (imported, is_own) {
3064                            // Imported, owned host-provided resource
3065                            (_imported @ false, _owned @ true) => {
3066                                let empty_func = self
3067                                    .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
3068                                uwriteln!(
3069                                    self.src,
3070                                    r#"
3071                                      var {handle} = {op}[{symbol_resource_handle}];
3072                                      if (!{handle}) {{
3073                                          throw new TypeError('Resource error: Not a valid \"{class_name}\" resource.');
3074                                      }}
3075                                      finalizationRegistry{tid}.unregister({op});
3076                                      {op}[{symbol_dispose}] = {empty_func};
3077                                      {op}[{symbol_resource_handle}] = undefined;
3078                                    "#,
3079                                );
3080                            }
3081
3082                            // Imported, borrowed host-provdied resource
3083                            (_imported @ false, _owned @ false) => {
3084                                // When expecting a borrow, the JS resource provided will always be an own
3085                                // handle. This is because it is not possible for borrow handles to be passed
3086                                // back reentrantly.
3087                                // We then set the handle to the rep per the local borrow rule.
3088                                let rsc_flag = self.intrinsic(Intrinsic::Resource(
3089                                    ResourceIntrinsic::ResourceTableFlag,
3090                                ));
3091                                let own_handle = format!("handle{}", self.tmp());
3092                                uwriteln!(
3093                                    self.src,
3094                                    r#"
3095                                      var {own_handle} = {op}[{symbol_resource_handle}];
3096                                      if (!{own_handle} || (handleTable{tid}[({own_handle} << 1) + 1] & {rsc_flag}) === 0) {{
3097                                          throw new TypeError('Resource error: Not a valid \"{class_name}\" resource.');
3098                                      }}
3099                                      var {handle} = handleTable{tid}[({own_handle} << 1) + 1] & ~{rsc_flag};
3100                                    "#,
3101                                );
3102                            }
3103
3104                            // Imported, owned guest-provided resource
3105                            (_imported @ true, _owned @ true) => {
3106                                // Imported resources may already have a handle if they were constructed
3107                                // by a component and then passed out.
3108                                //
3109                                // If the handle is not present, in hybrid bindgen we check for a Symbol.for('cabiRep')
3110                                // to get the resource rep.
3111                                //
3112                                // Fall back to assign a new rep in the capture table, when the imported
3113                                // resource was constructed externally.
3114                                let symbol_resource_rep =
3115                                    self.intrinsic(Intrinsic::SymbolResourceRep);
3116                                let create_own_fn = self.intrinsic(Intrinsic::Resource(
3117                                    ResourceIntrinsic::ResourceTableCreateOwn,
3118                                ));
3119
3120                                uwriteln!(
3121                                    self.src,
3122                                    r#"
3123                                      if (!({op} instanceof {local_name})) {{
3124                                          throw new TypeError('Resource error: Not a valid \"{class_name}\" resource.');
3125                                      }}
3126                                      var {handle} = {op}[{symbol_resource_handle}];
3127                                      if (!{handle}) {{
3128                                          const rep = {op}[{symbol_resource_rep}] || ++captureCnt{rid};
3129                                          captureTable{rid}.set(rep, {op});
3130                                          {handle} = {create_own_fn}(handleTable{tid}, rep);
3131                                      }}
3132                                    "#
3133                                );
3134                            }
3135
3136                            // Imported, borrowed guest-provided resource
3137                            (_imported @ true, _owned @ false) => {
3138                                // Imported resources may already have a handle if they were constructed
3139                                // by a component and then passed out.
3140                                //
3141                                // Otherwise, in hybrid bindgen we check for a Symbol.for('cabiRep')
3142                                // to get the resource rep.
3143                                // Fall back to assign a new rep in the capture table, when the imported
3144                                // resource was constructed externally.
3145
3146                                let symbol_resource_rep =
3147                                    self.intrinsic(Intrinsic::SymbolResourceRep);
3148                                let scope_id = self.intrinsic(Intrinsic::ScopeId);
3149                                let create_borrow_fn = self.intrinsic(Intrinsic::Resource(
3150                                    ResourceIntrinsic::ResourceTableCreateBorrow,
3151                                ));
3152
3153                                uwriteln!(
3154                                    self.src,
3155                                    r#"
3156                                      if (!({op} instanceof {local_name})) {{
3157                                          throw new TypeError('Resource error: Not a valid \"{class_name}\" resource.');
3158                                      }}
3159                                      var {handle} = {op}[{symbol_resource_handle}];
3160                                      if (!{handle}) {{
3161                                          const rep = {op}[{symbol_resource_rep}] || ++captureCnt{rid};
3162                                          captureTable{rid}.set(rep, {op});
3163                                          {handle} = {create_borrow_fn}(handleTable{tid}, rep, {scope_id});
3164                                      }}
3165                                    "#
3166                                );
3167                            }
3168                        }
3169                    }
3170
3171                    ResourceData::Guest {
3172                        resource_name,
3173                        prefix,
3174                        extra,
3175                    } => {
3176                        assert!(
3177                            extra.is_none(),
3178                            "plain resource handles do not carry extra data"
3179                        );
3180
3181                        let upper_camel = resource_name.to_upper_camel_case();
3182                        let lower_camel = resource_name.to_lower_camel_case();
3183                        let prefix = prefix.as_deref().unwrap_or("");
3184
3185                        let symbol_resource_handle =
3186                            self.intrinsic(Intrinsic::SymbolResourceHandle);
3187
3188                        let tmp = self.tmp();
3189                        match (imported, is_own) {
3190                            // imported owned/borrowed guest resource
3191                            (_imported @ true, _owned) => {
3192                                uwrite!(
3193                                    self.src,
3194                                    r#"
3195                                      var {handle} = {op}[{symbol_resource_handle}];
3196                                      finalizationRegistry_import${prefix}{lower_camel}.unregister({op});
3197                                    "#
3198                                );
3199                            }
3200
3201                            // Not-imported, borrowed guest resource
3202                            (_imported @ false, _owned @ false) => {
3203                                let local_rep = format!("localRep{tmp}");
3204                                uwriteln!(
3205                                    self.src,
3206                                    r#"
3207                                      if (!({op} instanceof {upper_camel})) {{
3208                                          throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
3209                                      }}
3210                                      let {handle} = {op}[{symbol_resource_handle}];
3211                                      if ({handle} === undefined) {{
3212                                          var {local_rep} = repCnt++;
3213                                          repTable.set({local_rep}, {{ rep: {op}, own: false }});
3214                                          {op}[{symbol_resource_handle}] = {local_rep};
3215                                      }}
3216                                    "#
3217                                );
3218                            }
3219
3220                            // Not-imported, owned guest resource
3221                            (_imported @ false, _owned @ true) => {
3222                                let local_rep = format!("localRep{tmp}");
3223                                uwriteln!(
3224                                    self.src,
3225                                    r#"
3226                                      if (!({op} instanceof {upper_camel})) {{
3227                                          throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
3228                                      }}
3229                                      let {handle} = {op}[{symbol_resource_handle}];
3230                                      if ({handle} === undefined) {{
3231                                          var {local_rep} = repCnt++;
3232                                          repTable.set({local_rep}, {{ rep: {op}, own: true }});
3233                                          {handle} = $resource_{prefix}new${lower_camel}({local_rep});
3234                                          {op}[{symbol_resource_handle}] = {handle};
3235                                          finalizationRegistry_export${prefix}{lower_camel}.register({op}, {handle}, {op});
3236                                      }}
3237                                    "#
3238                                );
3239                            }
3240                        }
3241                    }
3242                }
3243                results.push(handle);
3244            }
3245
3246            Instruction::DropHandle { ty } => {
3247                let _ = ty;
3248                todo!("[Instruction::DropHandle] not yet implemented")
3249            }
3250
3251            Instruction::Flush { amt } => {
3252                for item in operands.iter().take(*amt) {
3253                    results.push(item.clone());
3254                }
3255            }
3256
3257            Instruction::ErrorContextLift => {
3258                let item = operands
3259                    .first()
3260                    .expect("unexpectedly missing ErrorContextLift arg");
3261                results.push(item.clone());
3262            }
3263
3264            Instruction::ErrorContextLower => {
3265                let item = operands
3266                    .first()
3267                    .expect("unexpectedly missing ErrorContextLower arg");
3268                results.push(item.clone());
3269            }
3270
3271            Instruction::FutureLower { ty, .. } => {
3272                let future_arg = operands
3273                    .first()
3274                    .expect("unexpectedly missing FutureLower arg");
3275
3276                // Lowering is only performed inline for sync functions, and for async
3277                // functions when the operand is an incoming parameter (e.g. an async
3278                // export lowering a host-provided `Promise` param before `CallWasm`).
3279                //
3280                // For async host *imports* the operand is the host function's return
3281                // value (i.e. produced by `CallInterface`): lowering of async import
3282                // results is performed by the async return-handling machinery
3283                // (see `AsyncTaskIntrinsic::LowerImport` and `task.resolve`), so
3284                // lowering the value inline here as well would consume/settle the
3285                // `Promise` and double-lower it.
3286                if self.is_async && self.for_import.unwrap_or_default() {
3287                    results.push(future_arg.clone());
3288                    return;
3289                }
3290
3291                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
3292                let get_or_create_async_state_fn = self.intrinsic(Intrinsic::Component(
3293                    ComponentIntrinsic::GetOrCreateAsyncState,
3294                ));
3295                let gen_future_host_inject_fn = self.intrinsic(Intrinsic::AsyncFuture(
3296                    AsyncFutureIntrinsic::GenFutureHostInjectFn,
3297                ));
3298                let is_future_lowerable_object_fn = self.intrinsic(Intrinsic::AsyncFuture(
3299                    AsyncFutureIntrinsic::IsFutureLowerableObject,
3300                ));
3301                let nested_future_symbol = self.intrinsic(Intrinsic::AsyncFuture(
3302                    AsyncFutureIntrinsic::NestedFutureSymbol,
3303                ));
3304                let create_future_fn =
3305                    self.intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::CreateFuture));
3306
3307                // Build the lowering function for the type produced by the future
3308                let type_id = &crate::dealias(self.resolve, *ty);
3309                let ResourceTable {
3310                    imported: true,
3311                    data:
3312                        ResourceData::Guest {
3313                            extra:
3314                                Some(ResourceExtraData::Future {
3315                                    table_idx: future_table_idx_ty,
3316                                    nesting_level,
3317                                    elem_ty,
3318                                }),
3319                            ..
3320                        },
3321                } = self
3322                    .resource_map
3323                    .get(type_id)
3324                    .expect("missing resource mapping for future lower")
3325                else {
3326                    unreachable!("invalid resource table observed during future lower");
3327                };
3328                let future_table_idx = future_table_idx_ty.as_u32();
3329
3330                // Generate payload metadata ('elemMeta')
3331                let (
3332                    payload_type_name_js,
3333                    lift_fn_js,
3334                    lower_fn_js,
3335                    payload_is_none,
3336                    payload_is_numeric,
3337                    payload_is_borrow,
3338                    payload_is_async_value,
3339                    payload_size32_js,
3340                    payload_align32_js,
3341                    payload_flat_count_js,
3342                ) = match elem_ty {
3343                    Some(PayloadTypeMetadata {
3344                        ty: _,
3345                        iface_ty,
3346                        lift_js_expr,
3347                        lower_js_expr,
3348                        size32,
3349                        align32,
3350                        flat_count,
3351                    }) => (
3352                        format!("'{iface_ty:?}'"),
3353                        lift_js_expr.as_str(),
3354                        lower_js_expr.as_str(),
3355                        "false",
3356                        format!(
3357                            "{}",
3358                            matches!(
3359                                iface_ty,
3360                                InterfaceType::U8
3361                                    | InterfaceType::U16
3362                                    | InterfaceType::U32
3363                                    | InterfaceType::U64
3364                                    | InterfaceType::S8
3365                                    | InterfaceType::S16
3366                                    | InterfaceType::S32
3367                                    | InterfaceType::S64
3368                                    | InterfaceType::Float32
3369                                    | InterfaceType::Float64
3370                            )
3371                        ),
3372                        format!("{}", matches!(iface_ty, InterfaceType::Borrow(_))),
3373                        format!(
3374                            "{}",
3375                            matches!(
3376                                iface_ty,
3377                                InterfaceType::Stream(_) | InterfaceType::Future(_)
3378                            )
3379                        ),
3380                        size32.to_string(),
3381                        align32.to_string(),
3382                        flat_count.unwrap_or(0).to_string(),
3383                    ),
3384                    None => (
3385                        "null".into(),
3386                        "() => {{ throw new Error('no lift fn'); }}",
3387                        "() => {{ throw new Error('no lower fn'); }}",
3388                        "true",
3389                        "false".into(),
3390                        "false".into(),
3391                        "false".into(),
3392                        "null".into(),
3393                        "null".into(),
3394                        "0".into(),
3395                    ),
3396                };
3397
3398                let tmp = self.tmp();
3399                let lowered_future_waitable_idx = format!("futureWaitableIdx{tmp}");
3400
3401                let (component_idx_expr, get_realloc_fn_expr) =
3402                    if let Some(state) = &self.component_state {
3403                        let ComponentStateJsExprs {
3404                            component_idx,
3405                            get_realloc_fn,
3406                            ..
3407                        } = state.get_js_exprs();
3408                        (component_idx, get_realloc_fn)
3409                    } else {
3410                        ("-1".into(), "undefined".into())
3411                    };
3412
3413                uwriteln!(
3414                    self.src,
3415                    r#"
3416                        if (!{is_future_lowerable_object_fn}({future_arg})) {{
3417                            {debug_log_fn}('[Instruction::FutureLower] object is not a Promise/Thenable', {{ {future_arg} }});
3418                            throw new Error('unrecognized future object (not Promise/Thenable)');
3419                        }}
3420
3421                        const cstate{tmp} = {get_or_create_async_state_fn}({component_idx_expr});
3422                        if (!cstate{tmp}) {{
3423                            throw new Error(`missing component state for component [{component_idx_expr}]`);
3424                        }}
3425
3426                        // TODO(feat): facilitate non utf8 string encoding for lowered futures
3427                        const stringEncoding{tmp} = 'utf8';
3428
3429                        let outermostReadEnd{tmp};
3430                        let futuresList{tmp} = [];
3431                        let future{tmp} = {future_arg};
3432                        let nextFuture{tmp};
3433                        let openedCount{tmp} = -1;
3434                        // Lower exactly this future layer. If its payload is another
3435                        // future, elemMeta.lowerFn recursively creates that endpoint.
3436                        let futureNestingLevel{tmp} = 0;
3437
3438                        while (futureNestingLevel{tmp} >= 0) {{
3439                            const {{
3440                                writeEnd,
3441                                writeEndWaitableIdx,
3442                                readEnd,
3443                                readEndWaitableIdx
3444                            }} = {create_future_fn}(cstate{tmp}, {{
3445                                tableIdx: {future_table_idx},
3446                                elemMeta: {{
3447                                    liftFn: {lift_fn_js},
3448                                    lowerFn: {lower_fn_js},
3449                                    payloadTypeName: {payload_type_name_js},
3450                                    isNone: {payload_is_none},
3451                                    isNumeric: {payload_is_numeric},
3452                                    isBorrowed: {payload_is_borrow},
3453                                    isAsyncValue: {payload_is_async_value},
3454                                    flatCount: {payload_flat_count_js},
3455                                    align32: {payload_align32_js},
3456                                    size32: {payload_size32_js},
3457                                    stringEncoding: stringEncoding{tmp},
3458                                    getReallocFn: {get_realloc_fn_expr},
3459                                }}
3460                            }});
3461
3462                            const hostInjectFn{tmp} = {gen_future_host_inject_fn}({{
3463                                promise: future{tmp},
3464                                stringEncoding: stringEncoding{tmp},
3465                                hostWriteEnd: writeEnd,
3466                            }});
3467                            readEnd.setHostInjectFn(hostInjectFn{tmp});
3468
3469                            const meta{tmp} = {{
3470                                isInnermost: futureNestingLevel{tmp} === {nesting_level},
3471                                level: futureNestingLevel{tmp},
3472                            }};
3473
3474                            const innerFuture = future{tmp};
3475                            future{tmp} = {{ }};
3476                            future{tmp}[{nested_future_symbol}] = meta{tmp};
3477                            future{tmp}.readEndWaitableIdx = readEndWaitableIdx;
3478                            future{tmp}.writeEndWaitableIdx = writeEndWaitableIdx;
3479                            future{tmp}.futureTableIdx = {future_table_idx};
3480                            future{tmp}.componentIdx = {component_idx_expr};
3481                            future{tmp}.then = async (resolve, reject) => {{
3482                                let p;
3483                                if (openedCount{tmp} === {nesting_level}) {{
3484                                    p = innerFuture;
3485                                }} else {{
3486                                    openedCount{tmp}++;
3487                                    p = futuresList{tmp}[futuresList{tmp}.length - (openedCount{tmp} + 1)];
3488                                }}
3489
3490                                try {{
3491                                    resolve(await p);
3492                                }} catch (err) {{
3493                                    reject(err);
3494                                }}
3495                            }};
3496
3497                            outermostReadEnd{tmp} = readEnd;
3498
3499                            futuresList{tmp}.push(future{tmp});
3500                            futureNestingLevel{tmp}--;
3501                        }}
3502
3503                        const readEnd{tmp} = outermostReadEnd{tmp};
3504
3505                        // TODO: need to *lower* the internal future???
3506
3507                        const {lowered_future_waitable_idx} = readEnd{tmp}.waitableIdx();
3508                    "#
3509                );
3510
3511                results.push(lowered_future_waitable_idx);
3512            }
3513
3514            Instruction::FutureLift { payload, ty } => {
3515                let future_new_from_lift_fn = self.intrinsic(Intrinsic::AsyncFuture(
3516                    AsyncFutureIntrinsic::FutureNewFromLift,
3517                ));
3518
3519                // We must look up the type idx to find the future
3520                let type_id = &crate::dealias(self.resolve, *ty);
3521                let ResourceTable {
3522                    imported: true,
3523                    data:
3524                        ResourceData::Guest {
3525                            extra:
3526                                Some(ResourceExtraData::Future {
3527                                    table_idx: future_table_idx_ty,
3528                                    elem_ty: future_element_ty,
3529                                    ..
3530                                }),
3531                            ..
3532                        },
3533                } = self
3534                    .resource_map
3535                    .get(type_id)
3536                    .expect("missing resource mapping for future lift")
3537                else {
3538                    unreachable!("invalid resource table observed during future lift");
3539                };
3540
3541                // if a future element is present, it should match the payload we're getting
3542                let (lift_fn_js, lower_fn_js) = match future_element_ty {
3543                    Some(PayloadTypeMetadata {
3544                        ty,
3545                        lift_js_expr,
3546                        lower_js_expr,
3547                        ..
3548                    }) => {
3549                        assert_eq!(Some(*ty), **payload, "future element type mismatch");
3550                        (lift_js_expr.to_string(), lower_js_expr.to_string())
3551                    }
3552                    None => (
3553                        "() => {{ throw new Error('no lift fn'); }}".into(),
3554                        "() => {{ throw new Error('no lower fn'); }}".into(),
3555                    ),
3556                };
3557                if let Some(PayloadTypeMetadata { ty, .. }) = future_element_ty {
3558                    assert_eq!(Some(*ty), **payload, "future element type mismatch");
3559                }
3560
3561                let tmp = self.tmp();
3562                let result_var = format!("futureResult{tmp}");
3563
3564                // Optionally preform the lift for the future in question
3565                match (
3566                    self.canonical_abi_async,
3567                    self.for_import.unwrap_or_default(),
3568                ) {
3569                    // It is possible for lifting to be called both at the *start* and *end* of
3570                    // a given function depending on how it called:
3571                    //
3572                    // 1. lifting results to convert a component-produced result for use by the host *after* `CallWasm` returns
3573                    // 2. lifting parameters (`future` -> `Promise`), for use by the host, *before* `CallInterface`
3574                    //
3575                    // In (1), the function being generated must correspond to an export (from a component), and we only
3576                    // perform the lifting if we know the value is imminently ready (i.e. the sync case).
3577                    //
3578                    // In (2) the function must correspond to an import (from the host), and regardless of whether
3579                    // the function being generated is async or not, the host *must* deal in terms of lifted values
3580                    // (i.e. `Promise`, not index to a future)
3581                    //
3582                    (_is_async @ false, _for_import @ false) | (_is_async, _for_import @ true) => {
3583                        // If we're dealing with a sync function, we can use the return directly
3584                        let arg_future_end_idx = operands
3585                            .first()
3586                            .expect("unexpectedly missing future end return arg in FutureLift");
3587
3588                        let (payload_ty_size32_js, payload_ty_align32_js) =
3589                            if let Some(payload_ty) = payload {
3590                                (
3591                                    self.sizes.size(payload_ty).size_wasm32().to_string(),
3592                                    self.sizes.align(payload_ty).align_wasm32().to_string(),
3593                                )
3594                            } else {
3595                                ("null".into(), "null".into())
3596                            };
3597
3598                        let future_table_idx = future_table_idx_ty.as_u32();
3599
3600                        // Set task memory index and memory object
3601                        let component_idx_expr = if let Some(state) = &self.component_state {
3602                            let ComponentStateJsExprs { component_idx, .. } = state.get_js_exprs();
3603                            component_idx
3604                        } else {
3605                            "-1".into()
3606                        };
3607
3608                        // We only need to write the result var for use *if* the
3609                        // function that is being executed is provided by the host (i.e. `CallInterface`)
3610                        //
3611                        // The future value in question is being lifted *from* the component,
3612                        // such that the host call can use it (as a `Promise`).
3613                        //
3614                        // `hostProvided` is set hoistably in `CallWasm`/`CallInterface`
3615                        uwriteln!(
3616                            self.src,
3617                            r#"
3618                              const {result_var} = {future_new_from_lift_fn}({{
3619                                  componentIdx: {component_idx_expr},
3620                                  futureTableIdx: {future_table_idx},
3621                                  futureEndWaitableIdx: {arg_future_end_idx},
3622                                  payloadLiftFn: {lift_fn_js},
3623                                  payloadLowerFn: {lower_fn_js},
3624                                  payloadTypeSize32: {payload_ty_size32_js},
3625                                  payloadTypeAlign32: {payload_ty_align32_js},
3626                              }});
3627                            "#,
3628                        );
3629                    }
3630
3631                    // For all other cases, we do not need to perform the lift
3632                    _ => {}
3633                }
3634
3635                results.push(result_var.clone());
3636            }
3637
3638            Instruction::StreamLower { ty, .. } => {
3639                let stream_arg = operands
3640                    .first()
3641                    .expect("unexpectedly missing StreamLower arg");
3642
3643                // Lowering is only performed inline for sync functions, and for async
3644                // functions when the operand is an incoming parameter (e.g. an async
3645                // export lowering a host-provided stream param before `CallWasm`).
3646                //
3647                // For async host *imports* the operand is the host function's return
3648                // value (i.e. produced by `CallInterface`): lowering of async import
3649                // results is performed by the async return-handling machinery
3650                // (see `AsyncTaskIntrinsic::LowerImport` and `task.resolve`), so
3651                // lowering the value inline here as well would consume/lock the
3652                // stream (e.g. a host `ReadableStream`) and double-lower it.
3653                if self.is_async && self.for_import.unwrap_or_default() {
3654                    results.push(stream_arg.clone());
3655                    return;
3656                }
3657
3658                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
3659                let async_iterator_symbol = self.intrinsic(Intrinsic::SymbolAsyncIterator);
3660                let iterator_symbol = self.intrinsic(Intrinsic::SymbolIterator);
3661                let external_readable_stream_class =
3662                    self.intrinsic(Intrinsic::PlatformReadableStreamClass);
3663                let get_or_create_async_state_fn = self.intrinsic(Intrinsic::Component(
3664                    ComponentIntrinsic::GetOrCreateAsyncState,
3665                ));
3666                let gen_stream_host_inject_fn = self.intrinsic(Intrinsic::AsyncStream(
3667                    AsyncStreamIntrinsic::GenStreamHostInjectFn,
3668                ));
3669                let gen_read_fn_from_lowerable_stream_fn = self.intrinsic(Intrinsic::AsyncStream(
3670                    AsyncStreamIntrinsic::GenReadFnFromLowerableStream,
3671                ));
3672                let create_stream_fn =
3673                    self.intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::CreateStream));
3674
3675                // TODO(???): A component could end up receiving a stream that it outputted,
3676                // and the below would fail (imported: false)?
3677
3678                // Build the lowering function for the type produced by the stream
3679                let type_id = &crate::dealias(self.resolve, *ty);
3680                let ResourceTable {
3681                    imported: true,
3682                    data:
3683                        ResourceData::Guest {
3684                            extra:
3685                                Some(ResourceExtraData::Stream {
3686                                    table_idx: stream_table_idx_ty,
3687                                    elem_ty,
3688                                }),
3689                            ..
3690                        },
3691                } = self
3692                    .resource_map
3693                    .get(type_id)
3694                    .expect("missing resource mapping for stream lower")
3695                else {
3696                    unreachable!("invalid resource table observed during stream lower");
3697                };
3698
3699                let stream_table_idx = stream_table_idx_ty.as_u32();
3700
3701                let (
3702                    payload_type_name_js,
3703                    lift_fn_js,
3704                    lower_fn_js,
3705                    payload_is_none,
3706                    payload_is_numeric,
3707                    payload_is_borrow,
3708                    payload_is_async_value,
3709                    payload_size32_js,
3710                    payload_align32_js,
3711                    payload_flat_count_js,
3712                ) = match elem_ty {
3713                    Some(PayloadTypeMetadata {
3714                        ty: _,
3715                        iface_ty,
3716                        lift_js_expr,
3717                        lower_js_expr,
3718                        size32,
3719                        align32,
3720                        flat_count,
3721                    }) => (
3722                        format!("'{iface_ty:?}'"),
3723                        lift_js_expr.as_str(),
3724                        lower_js_expr.as_str(),
3725                        "false",
3726                        format!(
3727                            "{}",
3728                            matches!(
3729                                iface_ty,
3730                                InterfaceType::U8
3731                                    | InterfaceType::U16
3732                                    | InterfaceType::U32
3733                                    | InterfaceType::U64
3734                                    | InterfaceType::S8
3735                                    | InterfaceType::S16
3736                                    | InterfaceType::S32
3737                                    | InterfaceType::S64
3738                                    | InterfaceType::Float32
3739                                    | InterfaceType::Float64
3740                            )
3741                        ),
3742                        format!("{}", matches!(iface_ty, InterfaceType::Borrow(_))),
3743                        format!(
3744                            "{}",
3745                            matches!(
3746                                iface_ty,
3747                                InterfaceType::Stream(_) | InterfaceType::Future(_)
3748                            )
3749                        ),
3750                        size32.to_string(),
3751                        align32.to_string(),
3752                        flat_count.unwrap_or(0).to_string(),
3753                    ),
3754                    None => (
3755                        "null".into(),
3756                        "() => {{ throw new Error('no lift fn'); }}",
3757                        "() => {{ throw new Error('no lower fn'); }}",
3758                        "true",
3759                        "false".into(),
3760                        "false".into(),
3761                        "false".into(),
3762                        "null".into(),
3763                        "null".into(),
3764                        "0".into(),
3765                    ),
3766                };
3767
3768                // Set task memory index and memory object
3769                let (component_idx_expr, get_realloc_fn_expr) =
3770                    if let Some(state) = &self.component_state {
3771                        let ComponentStateJsExprs {
3772                            component_idx,
3773                            get_realloc_fn,
3774                            ..
3775                        } = state.get_js_exprs();
3776                        (component_idx, get_realloc_fn)
3777                    } else {
3778                        ("-1".into(), "undefined".into())
3779                    };
3780
3781                let tmp = self.tmp();
3782                let lowered_stream_waitable_idx = format!("streamWaitableIdx{tmp}");
3783                uwriteln!(
3784                    self.src,
3785                    r#"
3786                        if (!({async_iterator_symbol} in {stream_arg})
3787                            && !({iterator_symbol} in {stream_arg})
3788                            && !({stream_arg} instanceof {external_readable_stream_class})) {{
3789                            {debug_log_fn}('[Instruction::StreamLower] object with no supported stream protocol', {{ {stream_arg} }});
3790                            throw new Error('unrecognized stream object (no supported stream protocol)');
3791                        }}
3792
3793                        const cstate{tmp} = {get_or_create_async_state_fn}({component_idx_expr});
3794                        if (!cstate{tmp}) {{ throw new Error(`missing component state for component [{component_idx_expr}]`); }}
3795
3796                        const {{ writeEnd: hostWriteEnd{tmp}, readEnd: readEnd{tmp} }} = {create_stream_fn}(cstate{tmp}, {{
3797                            tableIdx: {stream_table_idx},
3798                            elemMeta: {{
3799                                liftFn: {lift_fn_js},
3800                                lowerFn: {lower_fn_js},
3801                                payloadTypeName: {payload_type_name_js},
3802                                isNone: {payload_is_none},
3803                                isNumeric: {payload_is_numeric},
3804                                isBorrowed: {payload_is_borrow},
3805                                isAsyncValue: {payload_is_async_value},
3806                                flatCount: {payload_flat_count_js},
3807                                align32: {payload_align32_js},
3808                                size32: {payload_size32_js},
3809                                // TODO(feat): facilitate non utf8 string encoding for lowered streams
3810                                stringEncoding: 'utf8',
3811                                getReallocFn: {get_realloc_fn_expr},
3812                            }},
3813                        }});
3814
3815                        const readFn{tmp} = {gen_read_fn_from_lowerable_stream_fn}({stream_arg});
3816
3817                        const hostInjectFn{tmp} = {gen_stream_host_inject_fn}({{
3818                            readFn: readFn{tmp},
3819                            hostWriteEnd: hostWriteEnd{tmp},
3820                            readEnd: readEnd{tmp},
3821                        }});
3822                        readEnd{tmp}.setHostInjectFn(hostInjectFn{tmp});
3823                        readEnd{tmp}.setHostDropFn(readFn{tmp}.drop);
3824
3825                        const {lowered_stream_waitable_idx} = readEnd{tmp}.waitableIdx();
3826                    "#
3827                );
3828
3829                results.push(lowered_stream_waitable_idx);
3830            }
3831
3832            Instruction::StreamLift { payload, ty } => {
3833                let stream_new_from_lift_fn = self.intrinsic(Intrinsic::AsyncStream(
3834                    AsyncStreamIntrinsic::StreamNewFromLift,
3835                ));
3836
3837                // We must look up the type idx to find the stream
3838                let type_id = &crate::dealias(self.resolve, *ty);
3839                let ResourceTable {
3840                    imported: true,
3841                    data:
3842                        ResourceData::Guest {
3843                            extra:
3844                                Some(ResourceExtraData::Stream {
3845                                    table_idx: stream_table_idx_ty,
3846                                    elem_ty: stream_element_ty,
3847                                }),
3848                            ..
3849                        },
3850                } = self
3851                    .resource_map
3852                    .get(type_id)
3853                    .expect("missing resource mapping for stream lift")
3854                else {
3855                    unreachable!("invalid resource table observed during stream lift");
3856                };
3857
3858                // if a stream element is present, it should match the payload we're getting
3859                let (lift_fn_js, lower_fn_js) = match stream_element_ty {
3860                    Some(PayloadTypeMetadata {
3861                        ty,
3862                        lift_js_expr,
3863                        lower_js_expr,
3864                        ..
3865                    }) => {
3866                        assert_eq!(Some(*ty), **payload, "stream element type mismatch");
3867                        (lift_js_expr.to_string(), lower_js_expr.to_string())
3868                    }
3869                    None => (
3870                        "() => {{ throw new Error('no lift fn'); }}".into(),
3871                        "() => {{ throw new Error('no lower fn'); }}".into(),
3872                    ),
3873                };
3874                if let Some(PayloadTypeMetadata { ty, .. }) = stream_element_ty {
3875                    assert_eq!(Some(*ty), **payload, "stream element type mismatch");
3876                }
3877
3878                let tmp = self.tmp();
3879                let result_var = format!("streamResult{tmp}");
3880
3881                // Optionally preform the lift for the stream in question
3882                match (
3883                    self.canonical_abi_async,
3884                    self.for_import.unwrap_or_default(),
3885                ) {
3886                    // It is possible for lifting to be called both at the *start* and *end* of
3887                    // a given function depending on how it called:
3888                    //
3889                    // 1. lifting results to convert a component-produced result for use by the host *after* `CallWasm` returns
3890                    // 2. lifting parameters (`stream` -> `AsyncIterator`), for use by the host, *before* `CallInterface`
3891                    //
3892                    // In (1), the function being generated must correspond to an export (from a component), and we only
3893                    // perform the lifting if we know the value is imminently ready (i.e. the sync case).
3894                    //
3895                    // In (2) the function must correspond to an import (from the host), and regardless of whether
3896                    // the function being generated is async or not, the host *must* deal in terms of lifted values
3897                    // (i.e. `AsyncIterator`, not index to a stream)
3898                    //
3899                    (_is_async @ false, _for_import @ false) | (_is_async, _for_import @ true) => {
3900                        let arg_stream_end_idx = operands
3901                            .first()
3902                            .expect("unexpectedly missing stream end return arg in StreamLift");
3903
3904                        let (payload_ty_size32_js, payload_ty_align32_js) =
3905                            if let Some(payload_ty) = payload {
3906                                (
3907                                    self.sizes.size(payload_ty).size_wasm32().to_string(),
3908                                    self.sizes.align(payload_ty).align_wasm32().to_string(),
3909                                )
3910                            } else {
3911                                ("null".into(), "null".into())
3912                            };
3913
3914                        let stream_table_idx = stream_table_idx_ty.as_u32();
3915
3916                        // Set task memory index and memory object
3917                        let component_idx_expr = if let Some(state) = &self.component_state {
3918                            let ComponentStateJsExprs { component_idx, .. } = state.get_js_exprs();
3919                            component_idx
3920                        } else {
3921                            "-1".into()
3922                        };
3923
3924                        uwriteln!(
3925                            self.src,
3926                            r#"
3927                              const {result_var} = {stream_new_from_lift_fn}({{
3928                                  componentIdx: {component_idx_expr},
3929                                  streamTableIdx: {stream_table_idx},
3930                                  streamEndWaitableIdx: {arg_stream_end_idx},
3931                                  payloadLiftFn: {lift_fn_js},
3932                                  payloadLowerFn: {lower_fn_js},
3933                                  payloadTypeSize32: {payload_ty_size32_js},
3934                                  payloadTypeAlign32: {payload_ty_align32_js},
3935                              }});
3936                            "#,
3937                        );
3938                    }
3939
3940                    // For other cases, we can do nothing as the future idx passes right through
3941                    _ => {}
3942                };
3943
3944                // TODO(fix): in the async case we return an uninitialized var, which should not be necessary
3945                results.push(result_var.clone());
3946            }
3947
3948            // Instruction::AsyncTaskReturn does *not* correspond to an canonical `task.return`,
3949            // but rather to a "return"/exit from an a lifted async function (e.g. pre-callback)
3950            //
3951            // To modify behavior of the `task.return` intrinsic, see:
3952            //   - `Trampoline::TaskReturn`
3953            //   - `AsyncTaskIntrinsic::TaskReturn`
3954            //
3955            // This is simply the end of the async function definition (e.g. `CallWasm`) that has been
3956            // lifted, which contains information about the async state.
3957            //
3958            // For an async function 'some-func', this instruction is triggered w/ the following `name`s:
3959            // - '[task-return]some-func'
3960            //
3961            // At this point in code generation, the following things have already been set:
3962            // - `parentTask`: A parent task, if one was executing before
3963            // - `subtask`: A subtask, if the current task is a subtask of a parent task
3964            // - `task`: the currently executing task
3965            // - `ret`: the original function return value, via (i.e. via `CallWasm`/`CallInterface`)
3966            // - `hostProvided`: whether the original function was a host-provided (i.e. host provided import)
3967            //
3968            Instruction::AsyncTaskReturn { name, params } => {
3969                let (direct_result_lift, direct_result) = self
3970                    .lift_callbackless_async_result()
3971                    .unwrap_or_else(|| (String::new(), "ret".into()));
3972                let return_direct_result = if self.wrap_async_future_result {
3973                    format!("{{ value: {direct_result} }}")
3974                } else {
3975                    direct_result.clone()
3976                };
3977                let debug_log_fn = self.intrinsic(Intrinsic::DebugLog);
3978                let is_async_js = self.requires_async_porcelain | self.is_async;
3979                let async_driver_loop_fn =
3980                    self.intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::DriverLoop));
3981                let get_or_create_async_state_fn = self.intrinsic(Intrinsic::Component(
3982                    ComponentIntrinsic::GetOrCreateAsyncState,
3983                ));
3984
3985                // Set task memory index and memory object
3986                let component_idx_expr = if let Some(state) = &self.component_state {
3987                    let ComponentStateJsExprs { component_idx, .. } = state.get_js_exprs();
3988                    component_idx
3989                } else {
3990                    "-1".into()
3991                };
3992
3993                let throw_result_err = if self.no_component_error_wrapping {
3994                    "throw taskRes.val;".to_string()
3995                } else {
3996                    let component_err = self.intrinsic(Intrinsic::ComponentError);
3997                    format!("throw new {component_err}(taskRes.val);")
3998                };
3999
4000                uwriteln!(
4001                    self.src,
4002                    "{debug_log_fn}('{prefix}  [Instruction::AsyncTaskReturn]', {{
4003                         funcName: '{name}',
4004                         paramCount: {param_count},
4005                         componentIdx: {component_idx_expr},
4006                         postReturn: {post_return_present},
4007                         hostProvided,
4008                      }});",
4009                    param_count = params.len(),
4010                    post_return_present = self.post_return.is_some(),
4011                    prefix = self.tracing_prefix,
4012                );
4013
4014                assert!(
4015                    self.is_async,
4016                    "non-async functions should not be performing async returns (func {name})",
4017                );
4018
4019                // If we're dealing with an async call, then `ret` is actually the
4020                // state of async behavior.
4021                //
4022                // The result *should* be a Promise that resolves to whatever the current task
4023                // will eventually resolve to.
4024                //
4025                // NOTE: Regardless of whether async porcelain is required here, we want to return the result
4026                // of the computation as a whole, not the current async state (which is what `ret` currently is).
4027                //
4028                // `ret` is only a Promise if we have async-lowered the function in question (e.g. via JSPI)
4029                //
4030                // ```ts
4031                // type ret = number | Promise<number>;
4032                // ```ts
4033                //
4034                // If the import was host provided we *already* have the result via
4035                // JSPI and simply calling the host provided JS function -- there is no need
4036                // to drive the async loop as with an async import that came from a component.
4037                //
4038                // If a subtask is defined, then we're in the case of a lowered async import,
4039                // which means that the first async call (to the callee fn) has occurred,
4040                // and a subtask has been created, but has not been triggered as started.
4041                //
4042                // NOTE: for host provided functions, we know that the resolution fo the
4043                // function itself are the lifted (component model -- i.e. a string not a pointer + len)
4044                // results. In those cases, we can simply return the result that was provided by the host.
4045                //
4046                // Alternatively, if we have entered an async return, and are part of a subtask
4047                // then we should start it, given that the task we have recently created (however we got to
4048                // the async return) is going to continue to be polled soon (via the driver loop).
4049                //
4050                // Host-import tasks may be parented by a canonical ABI subtask. Their
4051                // resolution is propagated to that subtask, and their own completion
4052                // promise is intentionally left unsettled, so return the lifted host
4053                // value directly after resolving and exiting the task.
4054                uwriteln!(
4055                    self.src,
4056                    r#"
4057                      if (hostProvided) {{
4058                          {debug_log_fn}('[Instruction::AsyncTaskReturn] signaling host-provided async return completion', {{
4059                              task: task.id(),
4060                              subtask: subtask?.id(),
4061                              result: ret,
4062                          }})
4063                          task.resolve([ret]);
4064                          task.exit();
4065                          return ret;
4066                      }}
4067
4068                      // An async lift without a callback (stackful) is done when its core
4069                      // function returns, but that function returns no values: the result
4070                      // comes only from `task.return`, and returning without having called
4071                      // it traps (`task.exit()` throws in that case).
4072                      if (!task.hasCallback()) {{
4073                          if (!task.isResolvedState() && ret !== undefined) {{
4074                              // (legacy: a core function that returns its result directly)
4075                              {direct_result_lift}
4076                              task.resolve([{direct_result}]);
4077                              task.exit();
4078                              return {return_direct_result};
4079                          }}
4080                          task.exit();
4081                          let taskRes = await task.completionPromise();
4082                          if (task.getErrHandling() === 'throw-result-err') {{
4083                              if (typeof taskRes !== 'object') {{
4084                                  return {return_task_res};
4085                              }}
4086                              if (taskRes.tag === 'err') {{ {throw_result_err} }}
4087                              if (taskRes.tag === 'ok') {{ taskRes = taskRes.val; }}
4088                          }}
4089                          return {return_task_res};
4090                      }}
4091
4092                      const componentState = {get_or_create_async_state_fn}({component_idx_expr});
4093                      if (!componentState) {{ throw new Error('failed to lookup current component state'); }}
4094
4095                      queueMicrotask(async (resolve, reject) => {{
4096                          try {{
4097                              {debug_log_fn}("[Instruction::AsyncTaskReturn] starting driver loop", {{
4098                                  fnName: '{name}',
4099                                  componentInstanceIdx: {component_idx_expr},
4100                                  taskID: task.id(),
4101                              }});
4102                              await {async_driver_loop_fn}({{
4103                                  componentInstanceIdx: {component_idx_expr},
4104                                  componentState,
4105                                  task,
4106                                  fnName: '{name}',
4107                                  isAsync: {is_async_js},
4108                                  callbackResult: ret,
4109                              }});
4110                          }} catch (err) {{
4111                              {debug_log_fn}("[Instruction::AsyncTaskReturn] driver loop call failure", {{ err }});
4112                          }}
4113                      }});
4114
4115                      let taskRes = await task.completionPromise();
4116                      if (task.getErrHandling() === 'throw-result-err') {{
4117                          if (typeof taskRes !== 'object') {{
4118                              return {return_task_res};
4119                          }}
4120                          if (taskRes.tag === 'err') {{ {throw_result_err} }}
4121                          if (taskRes.tag === 'ok') {{ taskRes = taskRes.val; }}
4122                      }}
4123
4124                      return {return_task_res};
4125                      "#,
4126                    // If we are returning the task result post-resolution, and it contains a future<t>,
4127                    // we must wrap the result so we can deal with nesting if present
4128                    return_task_res = if self.wrap_async_future_result {
4129                        "{ value: taskRes }"
4130                    } else {
4131                        "taskRes"
4132                    },
4133                    return_direct_result = return_direct_result,
4134                );
4135            }
4136
4137            Instruction::GuestDeallocate { size, align } => {
4138                let size = size.size_wasm32();
4139                if size != 0 {
4140                    let dealloc = self
4141                        .dealloc
4142                        .expect("guest deallocation requires a dealloc function");
4143                    uwriteln!(
4144                        self.src,
4145                        "{dealloc}(({}) >>> 0, {size}, {});",
4146                        operands[0],
4147                        align.align_wasm32()
4148                    );
4149                }
4150            }
4151
4152            Instruction::GuestDeallocateString => {
4153                let tmp = self.tmp();
4154                let ptr = format!("ptr{tmp}");
4155                let tagged_code_units = format!("taggedCodeUnits{tmp}");
4156                uwriteln!(self.src, "const {ptr} = ({}) >>> 0;", operands[0]);
4157                uwriteln!(
4158                    self.src,
4159                    "const {tagged_code_units} = ({}) >>> 0;",
4160                    operands[1]
4161                );
4162                match self.encoding {
4163                    StringEncoding::UTF8 => self.emit_guest_dealloc(&ptr, &tagged_code_units, 1, 1),
4164                    StringEncoding::UTF16 => {
4165                        self.emit_guest_dealloc(&ptr, &tagged_code_units, 2, 2)
4166                    }
4167                    StringEncoding::CompactUTF16 => {
4168                        // For wasm32, bit 31 tags a UTF-16 code-unit count; without it,
4169                        // the length counts Latin-1 bytes. See `load_string_from_range`:
4170                        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#loading
4171                        let tag = format!("tag{tmp}");
4172                        let byte_length = format!("byteLength{tmp}");
4173                        uwriteln!(self.src, "const {tag} = 2 ** 31;");
4174                        uwriteln!(
4175                            self.src,
4176                            "let {byte_length};
4177                            if ({tagged_code_units} & {tag}) {{
4178                                {byte_length} = 2 * ({tagged_code_units} ^ {tag});
4179                            }} else {{
4180                                {byte_length} = {tagged_code_units};
4181                            }}"
4182                        );
4183                        self.emit_guest_dealloc(&ptr, &byte_length, 1, 2);
4184                    }
4185                }
4186            }
4187
4188            Instruction::GuestDeallocateList { element } => {
4189                self.emit_dealloc_list_or_map(
4190                    operands,
4191                    self.sizes.size(element).size_wasm32(),
4192                    self.sizes.align(element).align_wasm32(),
4193                );
4194            }
4195
4196            Instruction::GuestDeallocateMap { key, value } => {
4197                let entry = self.sizes.record([*key, *value]);
4198                self.emit_dealloc_list_or_map(
4199                    operands,
4200                    entry.size.size_wasm32(),
4201                    entry.align.align_wasm32(),
4202                );
4203            }
4204
4205            Instruction::GuestDeallocateVariant { blocks } => {
4206                let blocks = self.blocks.split_off(self.blocks.len() - blocks);
4207                uwriteln!(self.src, "switch ({}) {{", operands[0]);
4208                for (i, (body, results)) in blocks.into_iter().enumerate() {
4209                    assert!(results.is_empty());
4210                    uwriteln!(
4211                        self.src,
4212                        "case {i}: {{
4213                            {body}
4214                            break;
4215                        }}"
4216                    );
4217                }
4218                if !self.valid_lifting_optimization {
4219                    uwriteln!(
4220                        self.src,
4221                        "default: {{
4222                            throw new TypeError('invalid variant discriminant for deallocation');
4223                        }}"
4224                    );
4225                }
4226                uwriteln!(self.src, "}}");
4227            }
4228        }
4229    }
4230}
4231
4232/// Tests whether `ty` can be represented with `null`, and if it can then
4233/// the "other type" is returned. If `Some` is returned that means that `ty`
4234/// is `null | <return>`. If `None` is returned that means that `null` can't
4235/// be used to represent `ty`.
4236pub fn as_nullable<'a>(resolve: &'a Resolve, ty: &'a Type) -> Option<&'a Type> {
4237    let id = match ty {
4238        Type::Id(id) => *id,
4239        _ => return None,
4240    };
4241    match &resolve.types[id].kind {
4242        // If `ty` points to an `option<T>`, then `ty` can be represented
4243        // with `null` if `t` itself can't be represented with null. For
4244        // example `option<option<u32>>` can't be represented with `null`
4245        // since that's ambiguous if it's `none` or `some(none)`.
4246        //
4247        // Note, oddly enough, that `option<option<option<u32>>>` can be
4248        // represented as `null` since:
4249        //
4250        // * `null` => `none`
4251        // * `{ tag: "none" }` => `some(none)`
4252        // * `{ tag: "some", val: null }` => `some(some(none))`
4253        // * `{ tag: "some", val: 1 }` => `some(some(some(1)))`
4254        //
4255        // It's doubtful anyone would actually rely on that though due to
4256        // how confusing it is.
4257        TypeDefKind::Option(t) => {
4258            if !maybe_null(resolve, t) {
4259                Some(t)
4260            } else {
4261                None
4262            }
4263        }
4264        TypeDefKind::Type(t) => as_nullable(resolve, t),
4265        _ => None,
4266    }
4267}
4268
4269pub fn maybe_null(resolve: &Resolve, ty: &Type) -> bool {
4270    as_nullable(resolve, ty).is_some()
4271}
4272
4273/// Retrieve the specialized JS array type that would contain a given element type,
4274/// if one exists.
4275///
4276/// e.g. a Wasm [`Type::U8`] would be represetned by a JS `Uint8Array`
4277///
4278/// # Arguments
4279///
4280/// * `resolve` - The [`Resolve`] used to look up nested type IDs if necessary
4281/// * `element_ty` - The [`Type`] that represents elements of the array
4282pub fn js_array_ty(resolve: &Resolve, element_ty: &Type) -> Option<&'static str> {
4283    match element_ty {
4284        Type::Bool => None,
4285        Type::U8 => Some("Uint8Array"),
4286        Type::S8 => Some("Int8Array"),
4287        Type::U16 => Some("Uint16Array"),
4288        Type::S16 => Some("Int16Array"),
4289        Type::U32 => Some("Uint32Array"),
4290        Type::S32 => Some("Int32Array"),
4291        Type::U64 => Some("BigUint64Array"),
4292        Type::S64 => Some("BigInt64Array"),
4293        Type::F32 => Some("Float32Array"),
4294        Type::F64 => Some("Float64Array"),
4295        Type::Char => None,
4296        Type::String => None,
4297        Type::ErrorContext => None,
4298        Type::Id(id) => match &resolve.types[*id].kind {
4299            // Recur to resolve type aliases, etc.
4300            TypeDefKind::Type(t) => js_array_ty(resolve, t),
4301            _ => None,
4302        },
4303    }
4304}
4305
4306/// Generate the JS `DataView` set and numeric checks for a given numeric type
4307///
4308/// # Arguments
4309///
4310/// * `ty` - the [`Type`] to check
4311///
4312fn gen_dataview_set_and_check_fn_js_for_numeric_type(
4313    resolve: &Resolve,
4314    ty: &Type,
4315) -> (&'static str, String) {
4316    let check_fn = Intrinsic::Conversion(ConversionIntrinsic::RequireValidNumericPrimitive).name();
4317    match ty {
4318        // Unsigned Integers
4319        Type::Bool => ("setUint8", format!("{check_fn}.bind(null, 'u8')",)),
4320        Type::U8 => ("setUint8", format!("{check_fn}.bind(null, 'u8')",)),
4321        Type::U16 => ("setUint16", format!("{check_fn}.bind(null, 'u16')",)),
4322        Type::U32 => ("setUint32", format!("{check_fn}.bind(null, 'u32')",)),
4323        Type::U64 => ("setBigUint64", format!("{check_fn}.bind(null, 'u64')",)),
4324        // Signed integers
4325        Type::S8 => ("setInt8", format!("{check_fn}.bind(null, 's8')",)),
4326        Type::S16 => ("setInt16", format!("{check_fn}.bind(null, 's16')",)),
4327        Type::S32 => ("setInt32", format!("{check_fn}.bind(null, 's32')",)),
4328        Type::S64 => ("setBigInt64", format!("{check_fn}.bind(null, 's64')",)),
4329        // Floating point
4330        Type::F32 => ("setFloat32", format!("{check_fn}.bind(null, 'f32')",)),
4331        Type::F64 => ("setFloat64", format!("{check_fn}.bind(null, 'f64')",)),
4332        Type::Id(id) => match resolve.types.get(*id) {
4333            // Type aliases should resolve to types that have the kind `TypeDefKind::Type`
4334            Some(TypeDef {
4335                kind: TypeDefKind::Type(inner_ty),
4336                ..
4337            }) => gen_dataview_set_and_check_fn_js_for_numeric_type(resolve, inner_ty),
4338            // We do not expect to resolve to types that *do not* have the `TypeDefKind::Type(...)`
4339            Some(inner_ty) => {
4340                unreachable!(
4341                    "unexpected non-type-kind typedef [{inner_ty:?}] (as type {ty:?}) for canonical list lower [{ty:?}]",
4342                )
4343            }
4344            // All type ids should resolve via the passed in `Resolve`
4345            None => unreachable!("missing/unresolvable type [{ty:?}]"),
4346        },
4347        _ => unreachable!("unsupported type [{ty:?}] for canonical list lower"),
4348    }
4349}
4350
4351#[cfg(test)]
4352mod tests {
4353    use super::*;
4354
4355    #[test]
4356    fn result_wrapper_detection_preserves_ambiguous_success_payloads() {
4357        let mut resolve = Resolve::new();
4358        let package = resolve
4359            .push_str(
4360                std::path::Path::new("result-wrappers.wit"),
4361                r#"
4362                    package test:result-wrappers;
4363
4364                    interface imports {
4365                        variant ordinary-variant { a(u32), b }
4366                        variant ok-variant { ok(u32), other }
4367                        record tagged-record { tag: string, val: u32 }
4368
4369                        primitive: func() -> result<u32, string>;
4370                        ordinary: func() -> result<ordinary-variant, string>;
4371                        ok-case: func() -> result<ok-variant, string>;
4372                        nested: func() -> result<result<u32, string>, string>;
4373                        tagged: func() -> result<tagged-record, string>;
4374                    }
4375                "#,
4376            )
4377            .unwrap();
4378        let interface = resolve.packages[package].interfaces["imports"];
4379
4380        let tags_for = |name: &str| {
4381            let ok = get_thrown_type(
4382                &resolve,
4383                resolve.interfaces[interface].functions[name].result,
4384            )
4385            .unwrap()
4386            .0;
4387            unambiguous_result_wrapper_tags(&resolve, ok)
4388        };
4389
4390        assert_eq!(tags_for("primitive"), (true, true));
4391        assert_eq!(tags_for("ordinary"), (true, true));
4392        assert_eq!(tags_for("ok-case"), (false, true));
4393        assert_eq!(tags_for("nested"), (false, false));
4394        assert_eq!(tags_for("tagged"), (false, false));
4395    }
4396
4397    #[test]
4398    fn test_alias_type_gen_dataview_set_and_check_fn_js_for_numeric_type() {
4399        let mut resolve = Resolve::new();
4400
4401        let owner = wit_parser::TypeOwner::Interface(resolve.interfaces.next_id());
4402
4403        let ty_id = resolve.types.alloc(wit_parser::TypeDef {
4404            name: None,
4405            kind: TypeDefKind::Type(Type::U64),
4406            docs: Default::default(),
4407            stability: Default::default(),
4408            owner,
4409            span: Default::default(),
4410            external_id: None,
4411        });
4412
4413        let ty_ = Type::Id(ty_id);
4414
4415        let (dataview_set_method, check_fn_intrinsic) =
4416            gen_dataview_set_and_check_fn_js_for_numeric_type(&resolve, &ty_);
4417
4418        assert_eq!(dataview_set_method, "setBigUint64");
4419
4420        let check_fn =
4421            Intrinsic::Conversion(ConversionIntrinsic::RequireValidNumericPrimitive).name();
4422
4423        assert_eq!(check_fn_intrinsic, format!("{check_fn}.bind(null, 'u64')",));
4424    }
4425}