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