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