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