Skip to main content

js_component_bindgen/
function_bindgen.rs

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