Skip to main content

js_component_bindgen/
function_bindgen.rs

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