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