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