1use std::cell::RefCell;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
3use std::fmt::Write;
4use std::mem;
5use std::ops::Index;
6
7use base64::Engine as _;
8use base64::engine::general_purpose;
9use heck::{ToKebabCase, ToLowerCamelCase, ToUpperCamelCase};
10use semver::Version;
11use wasmtime_environ::component::{
12 CanonicalOptions, CanonicalOptionsDataModel, Component, ComponentExtern, ComponentTranslation,
13 ComponentTypes, CoreDef, CoreExport, Export, ExportItem, FixedEncoding, GlobalInitializer,
14 InstantiateModule, InterfaceType, LinearMemoryOptions, LoweredIndex, ResourceIndex,
15 RuntimeComponentInstanceIndex, RuntimeImportIndex, RuntimeInstanceIndex, StaticModuleIndex,
16 Trampoline, TrampolineIndex, TypeDef, TypeFuncIndex, TypeFutureTableIndex,
17 TypeResourceTableIndex, TypeStreamTableIndex,
18};
19use wasmtime_environ::component::{
20 ExtractCallback, ImportIndex, NameMapNoIntern, Transcode,
21 TypeComponentLocalErrorContextTableIndex,
22};
23use wasmtime_environ::{EntityIndex, PrimaryMap};
24use wit_bindgen_core::abi::{self, LiftLower};
25use wit_component::StringEncoding;
26use wit_parser::abi::AbiVariant;
27use wit_parser::{
28 Function, FunctionKind, Handle, Resolve, Result_, SizeAlign, Type, TypeDefKind, TypeId,
29 WorldId, WorldItem, WorldKey,
30};
31
32use crate::esm_bindgen::EsmBindgen;
33use crate::files::Files;
34use crate::function_bindgen::{
35 ErrHandling, FunctionBindgen, FunctionBindgenComponentState, PayloadTypeMetadata, ResourceData,
36 ResourceExtraData, ResourceMap, ResourceTable,
37};
38use crate::intrinsics::component::ComponentIntrinsic;
39use crate::intrinsics::js_helper::JsHelperIntrinsic;
40use crate::intrinsics::lift::LiftIntrinsic;
41use crate::intrinsics::lower::LowerIntrinsic;
42use crate::intrinsics::p3::async_future::AsyncFutureIntrinsic;
43use crate::intrinsics::p3::async_stream::AsyncStreamIntrinsic;
44use crate::intrinsics::p3::async_task::AsyncTaskIntrinsic;
45use crate::intrinsics::p3::error_context::ErrCtxIntrinsic;
46use crate::intrinsics::p3::host::HostIntrinsic;
47use crate::intrinsics::p3::waitable::WaitableIntrinsic;
48use crate::intrinsics::resource::ResourceIntrinsic;
49use crate::intrinsics::string::StringIntrinsic;
50use crate::intrinsics::webidl::WebIdlIntrinsic;
51use crate::intrinsics::{
52 AsyncDeterminismProfile, Intrinsic, RenderIntrinsicsArgs, render_intrinsics,
53};
54use crate::names::{LocalNames, is_js_reserved_word, maybe_quote_id, maybe_quote_member};
55use crate::{
56 FunctionIdentifier, ManagesIntrinsics, core, get_thrown_type, is_async_fn,
57 requires_async_porcelain, source, uwrite, uwriteln,
58};
59
60const MAX_FLAT_PARAMS: usize = 16;
63const MAX_FLAT_RESULTS: usize = 1;
65
66#[derive(Debug, Default, Clone, bon::Builder)]
67pub struct TranspileOpts {
68 pub name: String,
69 #[builder(default)]
72 pub no_typescript: bool,
73 pub instantiation_mode: Option<InstantiationMode>,
76 pub import_bindings: Option<BindingsMode>,
79 pub map: Option<HashMap<String, String>>,
82 #[builder(default)]
84 pub nodejs_compat_disabled: bool,
85 #[builder(default)]
88 pub base64_cutoff: usize,
89 #[builder(default)]
92 pub tla_compat: bool,
93 #[builder(default)]
96 pub valid_lifting_optimization: bool,
97 #[builder(default)]
99 pub tracing: bool,
100 #[builder(default)]
103 pub no_component_error_wrapping: bool,
104 #[builder(default)]
107 pub no_namespaced_exports: bool,
108 #[builder(default)]
111 pub multi_memory: bool,
112 #[builder(default)]
114 pub guest: bool,
115 pub async_mode: Option<AsyncMode>,
118 #[builder(default)]
120 pub strict: bool,
121 #[builder(default)]
123 pub flags_as_bigint: bool,
124 #[builder(default)]
127 pub variants_inline_cases: bool,
128 #[builder(default)]
131 pub use_namespace_objects: bool,
132 #[builder(default)]
134 pub enum_values_screaming_snake_case: bool,
135 #[builder(default)]
137 pub asmjs: bool,
138 #[builder(default)]
146 pub supports_wasm_exnref: bool,
147}
148
149#[derive(Default, Clone, Debug)]
150#[non_exhaustive]
151pub enum AsyncMode {
152 #[default]
153 Sync,
154 JavaScriptPromiseIntegration {
155 imports: Vec<String>,
156 exports: Vec<String>,
157 },
158}
159
160#[derive(Default, Clone, Debug)]
161#[non_exhaustive]
162pub enum InstantiationMode {
163 #[default]
164 Async,
165 Sync,
166}
167
168enum CallType {
170 Standard,
172 AsyncStandard,
174 FirstArgIsThis,
176 AsyncFirstArgIsThis,
178 CalleeResourceDispatch,
180 AsyncCalleeResourceDispatch,
182}
183
184#[derive(Default, Clone, Debug)]
185#[non_exhaustive]
186pub enum BindingsMode {
187 Hybrid,
188 #[default]
189 Js,
190 Optimized,
191 DirectOptimized,
192}
193
194struct JsBindgen<'a> {
195 local_names: LocalNames,
196
197 esm_bindgen: EsmBindgen,
198
199 src: Source,
204
205 core_module_cnt: usize,
207
208 opts: &'a TranspileOpts,
210
211 all_intrinsics: BTreeSet<Intrinsic>,
213
214 all_core_exported_funcs: Vec<(String, bool)>,
220}
221
222struct JsFunctionBindgenArgs<'a> {
224 nparams: usize,
226 call_type: CallType,
228 iface_name: Option<&'a str>,
230 callee: &'a str,
232 opts: &'a CanonicalOptions,
234 func: &'a Function,
236 resource_map: &'a ResourceMap,
237 abi: AbiVariant,
239 requires_async_porcelain: bool,
241 is_async: bool,
243 wrap_async_future_result: bool,
245 for_import: bool,
248}
249
250impl<'a> ManagesIntrinsics for JsBindgen<'a> {
251 fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
252 self.intrinsic(intrinsic);
253 }
254}
255
256#[derive(PartialEq, Eq, Clone)]
257#[non_exhaustive]
258pub enum ExportKind {
259 LiftedFunction,
261 Instance,
263}
264
265#[allow(clippy::too_many_arguments)]
266pub fn transpile_bindgen(
267 name: &str,
268 component: &ComponentTranslation,
269 modules: &PrimaryMap<StaticModuleIndex, core::Translation<'_>>,
270 types: &ComponentTypes,
271 resolve: &Resolve,
272 id: WorldId,
273 opts: TranspileOpts,
274 files: &mut Files,
275) -> (Vec<String>, Vec<(String, ExportKind)>) {
276 let (async_imports, async_exports) = match opts.async_mode.clone() {
277 None | Some(AsyncMode::Sync) => (Default::default(), Default::default()),
278 Some(AsyncMode::JavaScriptPromiseIntegration { imports, exports }) => {
279 (imports.into_iter().collect(), exports.into_iter().collect())
280 }
281 };
282
283 let mut bindgen = JsBindgen {
284 local_names: LocalNames::default(),
285 src: Source::default(),
286 esm_bindgen: EsmBindgen::default(),
287 core_module_cnt: 0,
288 opts: &opts,
289 all_intrinsics: BTreeSet::new(),
290 all_core_exported_funcs: Vec::new(),
291 };
292 bindgen.local_names.exclude_globals(
293 &Intrinsic::get_global_names()
294 .into_iter()
295 .collect::<Vec<_>>(),
296 );
297 bindgen.core_module_cnt = modules.len();
298
299 let mut stream_tables = BTreeMap::new();
301 for idx in 0..component.component.num_stream_tables {
302 let stream_table_idx = TypeStreamTableIndex::from_u32(idx as u32);
303 let stream_table_ty = &types[stream_table_idx];
304 stream_tables.insert(stream_table_idx, stream_table_ty.instance);
305 }
306
307 let mut future_tables = BTreeMap::new();
309 for idx in 0..component.component.num_future_tables {
310 let future_table_idx = TypeFutureTableIndex::from_u32(idx as u32);
311 let future_table_ty = &types[future_table_idx];
312 future_tables.insert(future_table_idx, future_table_ty.instance);
313 }
314
315 let mut err_ctx_tables = BTreeMap::new();
317 for idx in 0..component.component.num_error_context_tables {
318 let err_ctx_table_idx = TypeComponentLocalErrorContextTableIndex::from_u32(idx as u32);
319 let err_ctx_table_ty = &types[err_ctx_table_idx];
320 err_ctx_tables.insert(err_ctx_table_idx, err_ctx_table_ty.instance);
321 }
322
323 let mut instantiator = Instantiator {
326 src: Source::default(),
327 sizes: SizeAlign::default(),
328 bindgen: &mut bindgen,
329 modules,
330 instances: Default::default(),
331 error_context_component_initialized: (0..component
332 .component
333 .num_runtime_component_instances)
334 .map(|_| false)
335 .collect(),
336 error_context_component_table_initialized: (0..component
337 .component
338 .num_error_context_tables)
339 .map(|_| false)
340 .collect(),
341 resolve,
342 world: id,
343 translation: component,
344 component: &component.component,
345 types,
346 async_imports,
347 async_exports,
348 imports: Default::default(),
349 exports: Default::default(),
350 lowering_options: Default::default(),
351 used_instance_flags: Default::default(),
352 defined_resource_classes: Default::default(),
353 imports_resource_types: Default::default(),
354 imports_resource_index_types: Default::default(),
355 exports_resource_types: Default::default(),
356 exports_resource_index_types: Default::default(),
357 resource_exports: Default::default(),
358 resource_imports: Default::default(),
359 resources_initialized: BTreeMap::new(),
360 resource_tables_initialized: BTreeMap::new(),
361 stream_tables,
362 future_tables,
363 err_ctx_tables,
364 init_current_module: None,
365 context_components: Default::default(),
366 };
367 instantiator.sizes.fill(resolve);
368 instantiator.initialize();
369 instantiator.instantiate();
370
371 instantiator.resource_definitions();
372 instantiator.instance_flags();
373
374 instantiator.bindgen.src.js(&instantiator.src.js);
375 instantiator.bindgen.src.js_init(&instantiator.src.js_init);
376
377 instantiator
378 .bindgen
379 .finish_component(name, files, &opts, source::Source::default());
380
381 let exports = instantiator
382 .bindgen
383 .esm_bindgen
384 .exports()
385 .iter()
386 .map(|(export_name, canon_export_name)| {
387 let expected_export_name =
388 if canon_export_name.contains(':') || canon_export_name.starts_with("[async]") {
389 canon_export_name.to_string()
390 } else {
391 canon_export_name.to_kebab_case()
392 };
393 let (export_idx, _extern_data) = instantiator
394 .component
395 .exports
396 .get(&expected_export_name, &NameMapNoIntern)
397 .unwrap_or_else(|| panic!("failed to find component export [{expected_export_name}] (original '{canon_export_name}')"));
398
399 let export_kind = match &instantiator.component.export_items[*export_idx] {
400 wasmtime_environ::component::Export::LiftedFunction { .. } => {
401 ExportKind::LiftedFunction
402 }
403 wasmtime_environ::component::Export::Instance { .. } => {
404 ExportKind::Instance
405 }
406 _ => panic!("unexpected export kind"),
407 };
408
409
410 (
411 export_name.to_string(),
412export_kind,
413 )
414 })
415 .collect();
416
417 (bindgen.esm_bindgen.import_specifiers(), exports)
418}
419
420impl JsBindgen<'_> {
421 fn finish_component(
422 &mut self,
423 name: &str,
424 files: &mut Files,
425 opts: &TranspileOpts,
426 intrinsic_definitions: source::Source,
427 ) {
428 let mut output = source::Source::default();
429 let mut compilation_promises = source::Source::default();
430 let mut core_exported_funcs = source::Source::default();
431
432 for (core_export_fn, is_async) in self.all_core_exported_funcs.iter() {
433 let local_name = self.local_names.get(core_export_fn);
434 if *is_async {
435 uwriteln!(
436 core_exported_funcs,
437 "{local_name} = WebAssembly.promising({core_export_fn});",
438 );
439 } else {
440 uwriteln!(core_exported_funcs, "{local_name} = {core_export_fn};",);
441 }
442 }
443
444 if matches!(self.opts.instantiation_mode, Some(InstantiationMode::Async)) {
446 uwriteln!(
447 compilation_promises,
448 "if (!getCoreModule) getCoreModule = (name) => {}(new URL(`./${{name}}`, import.meta.url));",
449 self.intrinsic(Intrinsic::FetchCompile)
450 );
451 }
452
453 let mut removed = BTreeSet::new();
455 for i in 0..self.core_module_cnt {
456 let local_name = format!("module{i}");
457 let mut name_idx = core_file_name(name, i as u32);
458 if self.opts.instantiation_mode.is_some() {
459 uwriteln!(
460 compilation_promises,
461 "const {local_name} = getCoreModule('{name_idx}');"
462 );
463 } else if files.get_size(&name_idx).unwrap() < self.opts.base64_cutoff {
464 assert!(removed.insert(i));
465 let data = files.remove(&name_idx).unwrap();
466 uwriteln!(
467 compilation_promises,
468 "const {local_name} = {}('{}');",
469 self.intrinsic(Intrinsic::Base64Compile),
470 general_purpose::STANDARD_NO_PAD.encode(&data),
471 );
472 } else {
473 if let Some(&replacement) = removed.iter().next() {
476 assert!(removed.remove(&replacement) && removed.insert(i));
477 let data = files.remove(&name_idx).unwrap();
478 name_idx = core_file_name(name, replacement as u32);
479 files.push(&name_idx, &data);
480 }
481 uwriteln!(
482 compilation_promises,
483 "const {local_name} = {}(new URL('./{name_idx}', import.meta.url));",
484 self.intrinsic(Intrinsic::FetchCompile)
485 );
486 }
487 }
488
489 uwriteln!(output, r#""use components";"#);
491
492 let render_args = RenderIntrinsicsArgs::builder()
493 .intrinsics(&mut self.all_intrinsics)
494 .instantiation_occurred(self.opts.instantiation_mode.is_some())
495 .determinism_profile(AsyncDeterminismProfile::default())
496 .transpile_opts(opts)
497 .build();
498 let js_intrinsics = render_intrinsics(render_args);
499
500 if let Some(instantiation) = &self.opts.instantiation_mode {
502 uwrite!(
503 output,
504 "\
505 export function instantiate(getCoreModule, imports, instantiateCore = {}) {{
506 {}
507 {}
508 {}
509 ",
510 match instantiation {
511 InstantiationMode::Async => "WebAssembly.instantiate",
512 InstantiationMode::Sync =>
513 "(module, importObject) => new WebAssembly.Instance(module, importObject)",
514 },
515 &js_intrinsics as &str,
516 &intrinsic_definitions as &str,
517 &compilation_promises as &str,
518 );
519 }
520
521 let imports_object = if self.opts.instantiation_mode.is_some() {
523 Some("imports")
524 } else {
525 None
526 };
527 self.esm_bindgen
528 .render_imports(&mut output, imports_object, &mut self.local_names);
529
530 if self.opts.instantiation_mode.is_some() {
532 uwrite!(&mut self.src.js, "{}", &core_exported_funcs as &str);
533 self.esm_bindgen.render_exports(
534 &mut self.src.js,
535 self.opts.instantiation_mode.is_some(),
536 &mut self.local_names,
537 opts,
538 );
539 uwrite!(
540 output,
541 "\
542 let gen = (function* _initGenerator () {{
543 {}\
544 {};
545 }})();
546 let promise, resolve, reject;
547 function runNext (value) {{
548 try {{
549 let done;
550 do {{
551 ({{ value, done }} = gen.next(value));
552 }} while (!(value instanceof Promise) && !done);
553 if (done) {{
554 if (resolve) return resolve(value);
555 else return value;
556 }}
557 if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
558 value.then(nextVal => done ? resolve() : runNext(nextVal), reject);
559 }}
560 catch (e) {{
561 if (reject) reject(e);
562 else throw e;
563 }}
564 }}
565 const maybeSyncReturn = runNext(null);
566 return promise || maybeSyncReturn;
567 }};
568 ",
569 &self.src.js_init as &str,
570 &self.src.js as &str,
571 );
572 } else {
573 let (maybe_init_export, maybe_init) =
574 if self.opts.tla_compat && opts.instantiation_mode.is_none() {
575 uwriteln!(self.src.js_init, "_initialized = true;");
576 (
577 "\
578 let _initialized = false;
579 export ",
580 "",
581 )
582 } else {
583 (
584 "",
585 "
586 await $init;
587 ",
588 )
589 };
590
591 uwrite!(
592 output,
593 "\
594 {}
595 {}
596 {}
597 {maybe_init_export}const $init = (() => {{
598 let gen = (function* _initGenerator () {{
599 {}\
600 {}\
601 {}\
602 }})();
603 let promise, resolve, reject;
604 function runNext (value) {{
605 try {{
606 let done;
607 do {{
608 ({{ value, done }} = gen.next(value));
609 }} while (!(value instanceof Promise) && !done);
610 if (done) {{
611 if (resolve) resolve(value);
612 else return value;
613 }}
614 if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
615 value.then(runNext, reject);
616 }}
617 catch (e) {{
618 if (reject) reject(e);
619 else throw e;
620 }}
621 }}
622 const maybeSyncReturn = runNext(null);
623 return promise || maybeSyncReturn;
624 }})();
625 {maybe_init}\
626 ",
627 &js_intrinsics as &str,
628 &intrinsic_definitions as &str,
629 &self.src.js as &str,
630 &compilation_promises as &str,
631 &self.src.js_init as &str,
632 &core_exported_funcs as &str,
633 );
634
635 self.esm_bindgen.render_exports(
636 &mut output,
637 self.opts.instantiation_mode.is_some(),
638 &mut self.local_names,
639 opts,
640 );
641 }
642
643 self.write_util_export(&mut output);
647
648 let mut bytes = output.as_bytes();
649 if bytes[0] == b'\n' {
651 bytes = &bytes[1..];
652 }
653 files.push(&format!("{name}.js"), bytes);
654 }
655
656 fn intrinsic(&mut self, intrinsic: Intrinsic) -> String {
657 self.all_intrinsics.insert(intrinsic);
658 intrinsic.name().to_string()
659 }
660
661 fn write_util_export(&mut self, output: &mut source::Source) {
663 let maybe_ext_future_class = if self.all_intrinsics.contains(&Intrinsic::AsyncFuture(
667 AsyncFutureIntrinsic::HostFutureClass,
668 )) {
669 r#"
670 Future: class Future {
671 #value;
672 #hidden = 0;
673 constructor(value) {
674 this.#value = value;
675 }
676 get then() {
677 if (this.#hidden !== 0) {
678 return undefined;
679 }
680 return (resolve) => {
681 if (this.#value instanceof Future) {
682 this.#value.resolveAsValue(resolve);
683 } else {
684 resolve(this.#value);
685 }
686 };
687 }
688 resolveAsValue(resolve) {
689 this.#hidden++;
690 try {
691 resolve(this);
692 } finally {
693 this.#hidden--;
694 }
695 }
696 },
697 "#
698 .to_string()
699 } else {
700 "".into()
701 };
702
703 uwriteln!(
704 output,
705 r#"
706 export const _util = {{
707 {maybe_ext_future_class}
708 }}
709 "#,
710 );
711 }
712}
713
714pub(crate) struct Instantiator<'a, 'b> {
718 src: Source,
719 bindgen: &'a mut JsBindgen<'b>,
720 modules: &'a PrimaryMap<StaticModuleIndex, core::Translation<'a>>,
721 instances: PrimaryMap<RuntimeInstanceIndex, StaticModuleIndex>,
722 types: &'a ComponentTypes,
723 resolve: &'a Resolve,
724 world: WorldId,
725 sizes: SizeAlign,
726 component: &'a Component,
727
728 error_context_component_initialized: PrimaryMap<RuntimeComponentInstanceIndex, bool>,
731 error_context_component_table_initialized:
732 PrimaryMap<TypeComponentLocalErrorContextTableIndex, bool>,
733
734 translation: &'a ComponentTranslation,
736
737 exports_resource_types: BTreeMap<TypeId, ResourceIndex>,
739 exports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,
741
742 imports_resource_types: BTreeMap<TypeId, ResourceIndex>,
744 #[allow(unused)]
746 imports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,
747
748 resources_initialized: BTreeMap<ResourceIndex, bool>,
749 resource_tables_initialized: BTreeMap<TypeResourceTableIndex, bool>,
750
751 exports: BTreeMap<String, WorldKey>,
752 imports: BTreeMap<String, WorldKey>,
753 used_instance_flags: RefCell<BTreeSet<RuntimeComponentInstanceIndex>>,
755 defined_resource_classes: BTreeSet<String>,
756 async_imports: HashSet<String>,
757 async_exports: HashSet<String>,
758 lowering_options:
759 PrimaryMap<LoweredIndex, (&'a CanonicalOptions, TrampolineIndex, TypeFuncIndex)>,
760
761 stream_tables: BTreeMap<TypeStreamTableIndex, RuntimeComponentInstanceIndex>,
763
764 future_tables: BTreeMap<TypeFutureTableIndex, RuntimeComponentInstanceIndex>,
766
767 err_ctx_tables:
769 BTreeMap<TypeComponentLocalErrorContextTableIndex, RuntimeComponentInstanceIndex>,
770
771 resource_exports: ResourceMap,
773 resource_imports: ResourceMap,
775
776 init_current_module: Option<RuntimeComponentInstanceIndex>,
782
783 context_components: RefCell<BTreeSet<RuntimeComponentInstanceIndex>>,
787}
788
789impl<'a> ManagesIntrinsics for Instantiator<'a, '_> {
790 fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
791 self.bindgen.intrinsic(intrinsic);
792 }
793}
794
795impl<'a> Instantiator<'a, '_> {
796 fn initialize(&mut self) {
797 for (key, _) in &self.resolve.worlds[self.world].imports {
799 let name = &self.resolve.name_world_key(key);
800 self.imports.insert(name.to_string(), key.clone());
801 }
802 for (key, _) in &self.resolve.worlds[self.world].exports {
803 let name = &self.resolve.name_world_key(key);
804 self.exports.insert(name.to_string(), key.clone());
805 }
806
807 for (key, item) in &self.resolve.worlds[self.world].imports {
810 let name = &self.resolve.name_world_key(key);
811 let Some((_, (_, import))) = self
812 .component
813 .import_types
814 .iter()
815 .find(|(_, (impt_name, _))| impt_name == name)
816 else {
817 match item {
818 WorldItem::Interface { .. } => {
819 unreachable!("unexpected interface in import types during initialization")
820 }
821 WorldItem::Function(_) => {
822 unreachable!("unexpected function in import types during initialization")
823 }
824 WorldItem::Type { id, .. } => {
825 assert!(!matches!(
826 self.resolve.types[*id].kind,
827 TypeDefKind::Resource
828 ))
829 }
830 }
831 continue;
832 };
833 match item {
834 WorldItem::Interface { id, .. } => {
835 let TypeDef::ComponentInstance(instance) = &import.ty else {
836 unreachable!("unexpectedly non-component instance import in interface")
837 };
838 let import_ty = &self.types[*instance];
839 let iface = &self.resolve.interfaces[*id];
840 for (ty_name, ty) in &iface.types {
841 match &import_ty.exports.get(ty_name) {
842 None => {}
843 Some(ComponentExtern {
844 ty: TypeDef::Resource(resource_table_idx),
845 ..
846 }) => {
847 let ty = crate::dealias(self.resolve, *ty);
848 let resource_table_ty = &self.types[*resource_table_idx];
849 let concrete_ty = resource_table_ty.unwrap_concrete_ty();
850 self.imports_resource_types.insert(ty, concrete_ty);
851 self.imports_resource_index_types.insert(concrete_ty, ty);
852 }
853 Some(ComponentExtern {
854 ty: TypeDef::Interface(_),
855 ..
856 }) => {}
857 Some(_) => unreachable!("unexpected type in interface"),
858 }
859 }
860 }
861 WorldItem::Function(_) => {}
862 WorldItem::Type { id, .. } => match import {
863 ComponentExtern {
864 ty: TypeDef::Resource(resource),
865 ..
866 } => {
867 let ty = crate::dealias(self.resolve, *id);
868 let resource_table_ty = &self.types[*resource];
869 let concrete_ty = resource_table_ty.unwrap_concrete_ty();
870 self.imports_resource_types.insert(ty, concrete_ty);
871 self.imports_resource_index_types.insert(concrete_ty, ty);
872 }
873 ComponentExtern {
874 ty: TypeDef::Interface(_),
875 ..
876 } => {}
877 _ => unreachable!("unexpected type in import world item"),
878 },
879 }
880 }
881 self.exports_resource_types = self.imports_resource_types.clone();
882 self.exports_resource_index_types = self.imports_resource_index_types.clone();
883
884 for (key, item) in &self.resolve.worlds[self.world].exports {
885 let name = &self.resolve.name_world_key(key);
886 let (_, (export_idx, _extern_data)) = self
887 .component
888 .exports
889 .raw_iter()
890 .find(|(expt_name, _)| ***expt_name == **name)
891 .unwrap();
892 let export = &self.component.export_items[*export_idx];
893 match item {
894 WorldItem::Interface { id, .. } => {
895 let iface = &self.resolve.interfaces[*id];
896 let Export::Instance { exports, .. } = &export else {
897 unreachable!("unexpectedly non export instance item")
898 };
899 for (ty_name, ty) in &iface.types {
900 let (export_idx, _exern_data) =
901 exports.get(ty_name, &NameMapNoIntern).unwrap();
902 match self.component.export_items[*export_idx] {
903 Export::Type(TypeDef::Resource(resource)) => {
904 let ty = crate::dealias(self.resolve, *ty);
905 let resource_table_ty = &self.types[resource];
906 let concrete_ty = resource_table_ty.unwrap_concrete_ty();
907 self.exports_resource_types.insert(ty, concrete_ty);
908 self.exports_resource_index_types.insert(concrete_ty, ty);
909 }
910 Export::Type(_) => {}
911 _ => unreachable!(
912 "unexpected type in component export items on iface [{iface_name}]",
913 iface_name = iface.name.as_deref().unwrap_or("<unknown>"),
914 ),
915 }
916 }
917 }
918 WorldItem::Function(_) => {}
919 WorldItem::Type { .. } => unreachable!("unexpected exported world item type"),
920 }
921 }
922 }
923
924 fn instantiate(&mut self) {
925 for (i, trampoline) in self.translation.trampolines.iter() {
927 let Trampoline::LowerImport {
928 index,
929 lower_ty,
930 options,
931 } = trampoline
932 else {
933 continue;
934 };
935
936 let options = self
937 .component
938 .options
939 .get(*options)
940 .expect("failed to find canon options");
941
942 let i = self.lowering_options.push((options, i, *lower_ty));
943 assert_eq!(i, *index);
944 }
945
946 if let Some(InstantiationMode::Async) = self.bindgen.opts.instantiation_mode {
947 if self.modules.len() > 1 {
950 self.src.js_init.push_str("Promise.all([");
951 for i in 0..self.modules.len() {
952 if i > 0 {
953 self.src.js_init.push_str(", ");
954 }
955 self.src.js_init.push_str(&format!("module{i}"));
956 }
957 uwriteln!(self.src.js_init, "]).catch(() => {{}});");
958 }
959 }
960
961 if !self.stream_tables.is_empty() {
967 let global_stream_table_map = self.bindgen.intrinsic(Intrinsic::AsyncStream(
968 AsyncStreamIntrinsic::GlobalStreamTableMap,
969 ));
970 let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
971 for (table_idx, component_idx) in self.stream_tables.iter() {
972 self.src.js.push_str(&format!(
973 "{global_stream_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
974 table_idx.as_u32(),
975 component_idx.as_u32(),
976 ));
977 }
978 }
979
980 if !self.future_tables.is_empty() {
983 let global_future_table_map = self.bindgen.intrinsic(Intrinsic::AsyncFuture(
984 AsyncFutureIntrinsic::GlobalFutureTableMap,
985 ));
986 let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
987 for (table_idx, component_idx) in self.future_tables.iter() {
988 self.src.js.push_str(&format!(
989 "{global_future_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
990 table_idx.as_u32(),
991 component_idx.as_u32(),
992 ));
993 }
994 }
995
996 if !self.err_ctx_tables.is_empty() {
999 let global_err_ctx_table_map = self
1000 .bindgen
1001 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalErrCtxTableMap));
1002 let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
1003 for (table_idx, component_idx) in self.err_ctx_tables.iter() {
1004 self.src.js.push_str(&format!(
1005 "{global_err_ctx_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
1006 table_idx.as_u32(),
1007 component_idx.as_u32(),
1008 ));
1009 }
1010 }
1011
1012 let mut lower_import_initializers = Vec::new();
1020
1021 for init in self.component.initializers.iter() {
1023 match init {
1024 GlobalInitializer::InstantiateModule(_m, _maybe_idx) => {
1025 for lower_import_init in lower_import_initializers.drain(..) {
1027 self.instantiation_global_initializer(lower_import_init);
1028 }
1029 }
1030
1031 GlobalInitializer::LowerImport { .. } => {
1035 lower_import_initializers.push(init);
1036 continue;
1037 }
1038 _ => {}
1039 }
1040
1041 self.instantiation_global_initializer(init);
1042 }
1043
1044 for init in lower_import_initializers.drain(..) {
1046 self.instantiation_global_initializer(init);
1047 }
1048
1049 self.process_imports();
1051
1052 self.process_exports();
1054
1055 for (i, trampoline) in self
1058 .translation
1059 .trampolines
1060 .iter()
1061 .filter(|(_, t)| Instantiator::is_early_trampoline(t))
1062 {
1063 self.trampoline(i, trampoline);
1064 }
1065
1066 self.wrap_initialization_in_context_tasks();
1067
1068 if self.bindgen.opts.instantiation_mode.is_some() {
1069 let js_init = mem::take(&mut self.src.js_init);
1070 self.src.js.push_str(&js_init);
1071 }
1072
1073 for (i, trampoline) in self
1076 .translation
1077 .trampolines
1078 .iter()
1079 .filter(|(_, t)| !Instantiator::is_early_trampoline(t))
1080 {
1081 self.trampoline(i, trampoline);
1082 }
1083 }
1084
1085 fn wrap_initialization_in_context_tasks(&mut self) {
1086 let component_indices = self
1087 .context_components
1088 .borrow()
1089 .iter()
1090 .copied()
1091 .collect::<Vec<_>>();
1092 if component_indices.is_empty() {
1093 return;
1094 }
1095
1096 let create_task = self.bindgen.intrinsic(Intrinsic::AsyncTask(
1097 AsyncTaskIntrinsic::CreateNewCurrentTask,
1098 ));
1099 let clear_task = self
1100 .bindgen
1101 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::ClearCurrentTask));
1102 let set_task_meta = self
1103 .bindgen
1104 .intrinsic(Intrinsic::SetGlobalCurrentTaskMetaFn);
1105 let clear_task_meta = self
1106 .bindgen
1107 .intrinsic(Intrinsic::ClearGlobalCurrentTaskMetaFn);
1108
1109 let mut setup = source::Source::default();
1110 for component_idx in &component_indices {
1111 uwriteln!(setup, "let _initTaskID{};", component_idx.as_u32());
1112 }
1113 uwriteln!(setup, "try {{");
1114 for component_idx in &component_indices {
1115 let component_idx = component_idx.as_u32();
1116 uwriteln!(
1117 setup,
1118 r#"
1119 [, _initTaskID{component_idx}] = {create_task}({{
1120 componentIdx: {component_idx},
1121 isAsync: false,
1122 callingWasmExport: true,
1123 entryFnName: '<initialize>',
1124 }});
1125 {set_task_meta}({{ componentIdx: {component_idx}, taskID: _initTaskID{component_idx} }});
1126 "#,
1127 );
1128 }
1129 self.src.js_init.prepend_str(&setup);
1130
1131 uwriteln!(self.src.js_init, "}} finally {{");
1132 for component_idx in component_indices.iter().rev() {
1133 let component_idx = component_idx.as_u32();
1134 uwriteln!(
1135 self.src.js_init,
1136 r#"
1137 {clear_task_meta}({{ componentIdx: {component_idx}, taskID: _initTaskID{component_idx} }});
1138 {clear_task}({component_idx}, _initTaskID{component_idx});
1139 "#,
1140 );
1141 }
1142 uwriteln!(self.src.js_init, "}}");
1143 }
1144
1145 fn ensure_local_resource_class(&mut self, local_name: String) {
1146 if !self.defined_resource_classes.contains(&local_name) {
1147 uwriteln!(
1148 self.src.js,
1149 "\nclass {local_name} {{
1150 constructor () {{
1151 throw new Error('\"{local_name}\" resource does not define a constructor');
1152 }}
1153 }}"
1154 );
1155 self.defined_resource_classes.insert(local_name.to_string());
1156 }
1157 }
1158
1159 fn resource_definitions(&mut self) {
1160 for resource in 0..self.component.num_resources {
1163 let resource = ResourceIndex::from_u32(resource);
1164 let is_imported = self.component.defined_resource_index(resource).is_none();
1165 if is_imported {
1166 continue;
1167 }
1168 if let Some(local_name) = self.bindgen.local_names.try_get(resource) {
1169 self.ensure_local_resource_class(local_name.to_string());
1170 }
1171 }
1172
1173 }
1189
1190 fn ensure_error_context_local_table(
1198 &mut self,
1199 component_idx: RuntimeComponentInstanceIndex,
1200 err_ctx_tbl_idx: TypeComponentLocalErrorContextTableIndex,
1201 ) {
1202 if self.error_context_component_initialized[component_idx]
1203 && self.error_context_component_table_initialized[err_ctx_tbl_idx]
1204 {
1205 return;
1206 }
1207 let err_ctx_local_tables = self
1208 .bindgen
1209 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ComponentLocalTable));
1210 let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
1211 let c = component_idx.as_u32();
1212 if !self.error_context_component_initialized[component_idx] {
1213 uwriteln!(self.src.js, "{err_ctx_local_tables}.set({c}, new Map());");
1214 self.error_context_component_initialized[component_idx] = true;
1215 }
1216 if !self.error_context_component_table_initialized[err_ctx_tbl_idx] {
1217 let t = err_ctx_tbl_idx.as_u32();
1218 uwriteln!(
1219 self.src.js,
1220 "{err_ctx_local_tables}.get({c}).set({t}, new {rep_table_class}({{ target: `component [{c}] local error ctx table [{t}]` }}));"
1221 );
1222 self.error_context_component_table_initialized[err_ctx_tbl_idx] = true;
1223 }
1224 }
1225
1226 fn ensure_resource_table(&mut self, resource_table_idx: TypeResourceTableIndex) {
1233 if self
1234 .resource_tables_initialized
1235 .contains_key(&resource_table_idx)
1236 {
1237 return;
1238 }
1239
1240 let resource_table_ty = &self.types[resource_table_idx];
1241 let resource_idx = resource_table_ty.unwrap_concrete_ty();
1242 let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
1243
1244 let (is_imported, maybe_dtor) = if let Some(resource_idx) =
1245 self.component.defined_resource_index(resource_idx)
1246 {
1247 let resource_def = self
1248 .component
1249 .initializers
1250 .iter()
1251 .find_map(|i| match i {
1252 GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
1253 _ => None,
1254 })
1255 .unwrap();
1256
1257 if let Some(dtor) = &resource_def.dtor {
1258 let dtor = self.core_def(dtor);
1259 let maybe_dtor = if self
1260 .context_components
1261 .borrow()
1262 .contains(&resource_table_ty.unwrap_concrete_instance())
1263 {
1264 let call_resource_destructor = self.bindgen.intrinsic(Intrinsic::Resource(
1265 ResourceIntrinsic::ResourceDestructorCall,
1266 ));
1267 format!(
1268 "\n{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {}, rep }});",
1269 dtor,
1270 )
1271 } else {
1272 format!("\n{dtor}(rep);")
1273 };
1274 (false, maybe_dtor)
1275 } else {
1276 (false, "".into())
1277 }
1278 } else {
1279 (true, "".into())
1280 };
1281
1282 let handle_tables = self.bindgen.intrinsic(Intrinsic::HandleTables);
1283 let rsc_table_flag = self
1284 .bindgen
1285 .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
1286 let rsc_table_remove = self
1287 .bindgen
1288 .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
1289
1290 let rtid = resource_table_idx.as_u32();
1292 if is_imported {
1293 uwriteln!(
1295 self.src.js,
1296 r#"
1297 const handleTable{rtid} = [{rsc_table_flag}, 0];
1298 handleTable{rtid}._createdReps = new Set();
1299 "#,
1300 );
1301 if !self.resources_initialized.contains_key(&resource_idx) {
1302 let ridx = resource_idx.as_u32();
1303 uwriteln!(
1304 self.src.js,
1305 r#"
1306 const captureTable{ridx} = new Map();
1307 let captureCnt{ridx} = 0;
1308 "#
1309 );
1310 self.resources_initialized.insert(resource_idx, true);
1311 }
1312 } else {
1313 let finalization_registry_create = self
1315 .bindgen
1316 .intrinsic(Intrinsic::FinalizationRegistryCreate);
1317 uwriteln!(
1318 self.src.js,
1319 r#"
1320 const handleTable{rtid} = [{rsc_table_flag}, 0];
1321 handleTable{rtid}._createdReps = new Set();
1322 const finalizationRegistry{rtid} = {finalization_registry_create}((handle) => {{
1323 const {{ rep }} = {rsc_table_remove}(handleTable{rtid}, handle);{maybe_dtor}
1324 }});
1325 "#,
1326 );
1327 }
1328
1329 uwriteln!(self.src.js, "{handle_tables}[{rtid}] = handleTable{rtid};");
1331 self.resource_tables_initialized
1332 .insert(resource_table_idx, true);
1333 }
1334
1335 fn instance_flags(&mut self) {
1336 let used_instance_flags = self
1337 .used_instance_flags
1338 .borrow()
1339 .iter()
1340 .copied()
1341 .collect::<Vec<_>>();
1342 if used_instance_flags.is_empty() {
1343 return;
1344 }
1345
1346 let instance_flags_map = self.bindgen.intrinsic(Intrinsic::Component(
1347 ComponentIntrinsic::GlobalInstanceFlagsMap,
1348 ));
1349 let mut instance_flag_defs = String::new();
1350 for used in used_instance_flags {
1351 let i = used.as_u32();
1352 uwriteln!(
1355 &mut instance_flag_defs,
1356 "const instanceFlags{i} = new WebAssembly.Global({{ value: \"i32\", mutable: true }}, 1);",
1357 );
1358 uwriteln!(
1359 &mut instance_flag_defs,
1360 "{instance_flags_map}.set({i}, instanceFlags{i});",
1361 );
1362 }
1363 self.src.js_init.prepend_str(&instance_flag_defs);
1364 }
1365
1366 fn trampoline_may_leave_instance(
1369 &self,
1370 trampoline: &Trampoline,
1371 ) -> Option<RuntimeComponentInstanceIndex> {
1372 let instance = match trampoline {
1373 Trampoline::ResourceRep { .. }
1374 | Trampoline::ThreadIndex
1375 | Trampoline::BackpressureInc { .. }
1376 | Trampoline::BackpressureDec { .. }
1377 | Trampoline::ResourceTransferOwn
1378 | Trampoline::ResourceTransferBorrow
1379 | Trampoline::PrepareCall { .. }
1380 | Trampoline::SyncStartCall { .. }
1381 | Trampoline::AsyncStartCall { .. }
1382 | Trampoline::FutureTransfer
1383 | Trampoline::StreamTransfer
1384 | Trampoline::ErrorContextTransfer
1385 | Trampoline::Trap
1386 | Trampoline::EnterSyncCall
1387 | Trampoline::ExitSyncCall
1388 | Trampoline::Transcoder { .. } => return None,
1389
1390 Trampoline::LowerImport { options, .. } => {
1391 self.component
1392 .options
1393 .get(*options)
1394 .expect("failed to find lower import options")
1395 .instance
1396 }
1397
1398 Trampoline::ResourceNew { instance, .. }
1399 | Trampoline::ResourceDrop { instance, .. }
1400 | Trampoline::TaskReturn { instance, .. }
1401 | Trampoline::TaskCancel { instance }
1402 | Trampoline::WaitableSetNew { instance }
1403 | Trampoline::WaitableSetWait { instance, .. }
1404 | Trampoline::WaitableSetPoll { instance, .. }
1405 | Trampoline::WaitableSetDrop { instance }
1406 | Trampoline::WaitableJoin { instance }
1407 | Trampoline::ThreadYield { instance, .. }
1408 | Trampoline::ThreadNewIndirect { instance, .. }
1409 | Trampoline::ThreadSuspend { instance, .. }
1410 | Trampoline::ThreadSuspendToSuspended { instance, .. }
1411 | Trampoline::ThreadSuspendTo { instance, .. }
1412 | Trampoline::ThreadUnsuspend { instance, .. }
1413 | Trampoline::ThreadYieldToSuspended { instance, .. }
1414 | Trampoline::SubtaskDrop { instance }
1415 | Trampoline::SubtaskCancel { instance, .. }
1416 | Trampoline::ErrorContextNew { instance, .. }
1417 | Trampoline::ErrorContextDebugMessage { instance, .. }
1418 | Trampoline::ErrorContextDrop { instance, .. }
1419 | Trampoline::StreamNew { instance, .. }
1420 | Trampoline::StreamRead { instance, .. }
1421 | Trampoline::StreamWrite { instance, .. }
1422 | Trampoline::StreamCancelRead { instance, .. }
1423 | Trampoline::StreamCancelWrite { instance, .. }
1424 | Trampoline::StreamDropReadable { instance, .. }
1425 | Trampoline::StreamDropWritable { instance, .. }
1426 | Trampoline::FutureNew { instance, .. }
1427 | Trampoline::FutureRead { instance, .. }
1428 | Trampoline::FutureWrite { instance, .. }
1429 | Trampoline::FutureCancelRead { instance, .. }
1430 | Trampoline::FutureCancelWrite { instance, .. }
1431 | Trampoline::FutureDropReadable { instance, .. }
1432 | Trampoline::FutureDropWritable { instance, .. } => *instance,
1433 };
1434 Some(instance)
1435 }
1436
1437 fn trampoline_checks_may_leave_internally(trampoline: &Trampoline) -> bool {
1440 matches!(
1441 trampoline,
1442 Trampoline::LowerImport { .. }
1443 | Trampoline::SubtaskCancel { .. }
1444 | Trampoline::WaitableSetWait { .. }
1445 | Trampoline::StreamRead { .. }
1446 | Trampoline::StreamWrite { .. }
1447 | Trampoline::StreamCancelRead { .. }
1448 | Trampoline::StreamCancelWrite { .. }
1449 | Trampoline::FutureRead { .. }
1450 | Trampoline::FutureWrite { .. }
1451 | Trampoline::FutureCancelRead { .. }
1452 | Trampoline::FutureCancelWrite { .. }
1453 | Trampoline::FutureDropReadable { .. }
1454 | Trampoline::FutureDropWritable { .. }
1455 | Trampoline::ThreadYield { .. }
1456 )
1457 }
1458
1459 fn is_early_trampoline(trampoline: &Trampoline) -> bool {
1464 matches!(
1465 trampoline,
1466 Trampoline::AsyncStartCall { .. }
1467 | Trampoline::BackpressureDec { .. }
1468 | Trampoline::BackpressureInc { .. }
1469 | Trampoline::EnterSyncCall
1470 | Trampoline::ErrorContextDebugMessage { .. }
1471 | Trampoline::ErrorContextDrop { .. }
1472 | Trampoline::ErrorContextNew { .. }
1473 | Trampoline::ErrorContextTransfer
1474 | Trampoline::ExitSyncCall
1475 | Trampoline::FutureCancelRead { .. }
1476 | Trampoline::FutureCancelWrite { .. }
1477 | Trampoline::FutureDropReadable { .. }
1478 | Trampoline::FutureDropWritable { .. }
1479 | Trampoline::FutureNew { .. }
1480 | Trampoline::FutureRead { .. }
1481 | Trampoline::FutureTransfer
1482 | Trampoline::FutureWrite { .. }
1483 | Trampoline::LowerImport { .. }
1484 | Trampoline::PrepareCall { .. }
1485 | Trampoline::ResourceDrop { .. }
1486 | Trampoline::ResourceNew { .. }
1487 | Trampoline::ResourceRep { .. }
1488 | Trampoline::ResourceTransferBorrow
1489 | Trampoline::ResourceTransferOwn
1490 | Trampoline::StreamCancelRead { .. }
1491 | Trampoline::StreamCancelWrite { .. }
1492 | Trampoline::StreamDropReadable { .. }
1493 | Trampoline::StreamDropWritable { .. }
1494 | Trampoline::StreamNew { .. }
1495 | Trampoline::StreamRead { .. }
1496 | Trampoline::StreamTransfer
1497 | Trampoline::StreamWrite { .. }
1498 | Trampoline::SubtaskCancel { .. }
1499 | Trampoline::SubtaskDrop { .. }
1500 | Trampoline::SyncStartCall { .. }
1501 | Trampoline::TaskCancel { .. }
1502 | Trampoline::TaskReturn { .. }
1503 | Trampoline::ThreadYield { .. }
1504 | Trampoline::ThreadYieldToSuspended { .. }
1505 | Trampoline::WaitableJoin { .. }
1506 | Trampoline::WaitableSetDrop { .. }
1507 | Trampoline::WaitableSetNew { .. }
1508 | Trampoline::WaitableSetPoll { .. }
1509 | Trampoline::WaitableSetWait { .. }
1510 )
1511 }
1512
1513 fn trampoline(&mut self, i: TrampolineIndex, trampoline: &'a Trampoline) {
1514 let i = i.as_u32();
1515 match trampoline {
1516 Trampoline::TaskCancel { instance } => {
1517 let task_cancel_fn = self
1518 .bindgen
1519 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskCancel));
1520 uwriteln!(
1521 self.src.js,
1522 "const trampoline{i} = {task_cancel_fn}.bind(null, {instance_idx});\n",
1523 instance_idx = instance.as_u32(),
1524 );
1525 }
1526
1527 Trampoline::SubtaskCancel { instance, async_ } => {
1528 let subtask_cancel_fn = self
1529 .bindgen
1530 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskCancel));
1531 let suspending_wrap_fn =
1532 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
1533 uwriteln!(
1537 self.src.js,
1538 "const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({instance_idx}, {subtask_cancel_fn}.bind(null, {instance_idx}, {async_})));\n",
1539 instance_idx = instance.as_u32(),
1540 );
1541 }
1542
1543 Trampoline::SubtaskDrop { instance } => {
1544 let component_idx = instance.as_u32();
1545 let subtask_drop_fn = self
1546 .bindgen
1547 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskDrop));
1548 uwriteln!(
1549 self.src.js,
1550 "const trampoline{i} = {subtask_drop_fn}.bind(
1551 null,
1552 {component_idx},
1553 );"
1554 );
1555 }
1556
1557 Trampoline::WaitableSetNew { instance } => {
1558 let waitable_set_new_fn = self
1559 .bindgen
1560 .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetNew));
1561 uwriteln!(
1562 self.src.js,
1563 "const trampoline{i} = {waitable_set_new_fn}.bind(null, {});\n",
1564 instance.as_u32(),
1565 );
1566 }
1567
1568 Trampoline::WaitableSetWait { instance, options } => {
1569 let options = self
1570 .component
1571 .options
1572 .get(*options)
1573 .expect("failed to find options");
1574 assert_eq!(
1575 instance.as_u32(),
1576 options.instance.as_u32(),
1577 "options index instance must match trampoline"
1578 );
1579
1580 let CanonicalOptions {
1581 instance,
1582 async_,
1583 data_model:
1584 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
1585 ..
1586 } = options
1587 else {
1588 panic!("unexpected/missing memory data model during waitable-set.wait");
1589 };
1590
1591 let instance_idx = instance.as_u32();
1592 let memory_idx = memory
1593 .expect("missing memory idx for waitable-set.wait")
1594 .as_u32();
1595 let waitable_set_wait_fn = self
1596 .bindgen
1597 .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetWait));
1598 let suspending_wrap_fn =
1599 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
1600
1601 uwriteln!(
1602 self.src.js,
1603 r#"
1604 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({instance_idx}, {waitable_set_wait_fn}.bind(null, {{
1605 componentIdx: {instance_idx},
1606 isAsync: {async_},
1607 memoryIdx: {memory_idx},
1608 getMemoryFn: () => memory{memory_idx},
1609 }})));
1610 "#,
1611 );
1612 }
1613
1614 Trampoline::WaitableSetPoll { options, .. } => {
1615 let CanonicalOptions {
1616 instance,
1617 async_,
1618 data_model:
1619 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
1620 cancellable,
1621 ..
1622 } = self
1623 .component
1624 .options
1625 .get(*options)
1626 .expect("failed to find options")
1627 else {
1628 panic!("unexpected memory data model during waitable-set.poll");
1629 };
1630
1631 let instance_idx = instance.as_u32();
1632 let memory_idx = memory
1633 .expect("missing memory idx for waitable-set.poll")
1634 .as_u32();
1635 let waitable_set_poll_fn = self
1636 .bindgen
1637 .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetPoll));
1638
1639 uwriteln!(
1640 self.src.js,
1641 r#"
1642 const trampoline{i} = {waitable_set_poll_fn}.bind(
1643 null,
1644 {{
1645 componentIdx: {instance_idx},
1646 isAsync: {async_},
1647 isCancellable: {cancellable},
1648 memoryIdx: {memory_idx},
1649 getMemoryFn: () => memory{memory_idx},
1650 }}
1651 );
1652 "#,
1653 );
1654 }
1655
1656 Trampoline::WaitableSetDrop { instance } => {
1657 let waitable_set_drop_fn = self
1658 .bindgen
1659 .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetDrop));
1660 uwriteln!(
1661 self.src.js,
1662 "const trampoline{i} = {waitable_set_drop_fn}.bind(null, {instance_idx});\n",
1663 instance_idx = instance.as_u32(),
1664 );
1665 }
1666
1667 Trampoline::WaitableJoin { instance } => {
1668 let waitable_join_fn = self
1669 .bindgen
1670 .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableJoin));
1671 uwriteln!(
1672 self.src.js,
1673 "const trampoline{i} = {waitable_join_fn}.bind(null, {instance_idx});\n",
1674 instance_idx = instance.as_u32(),
1675 );
1676 }
1677
1678 Trampoline::StreamNew { ty, instance } => {
1679 let stream_new_fn = self
1680 .bindgen
1681 .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamNew));
1682 let instance_idx = instance.as_u32();
1683 let stream_table_idx = ty.as_u32();
1684
1685 let table_ty = &self.types[*ty];
1687 let stream_ty_idx = table_ty.ty;
1688 let stream_ty = &self.types[stream_ty_idx];
1689
1690 let payload_ty_name_js = stream_ty
1695 .payload
1696 .map(|iface_ty| format!("'{iface_ty:?}'"))
1697 .unwrap_or_else(|| "null".into());
1698
1699 let (
1701 align_32_js,
1702 size_32_js,
1703 flat_count_js,
1704 lift_fn_js,
1705 lower_fn_js,
1706 is_none_js,
1707 is_numeric_type_js,
1708 is_borrow_js,
1709 is_async_value_js,
1710 typed_array_js,
1711 ) = match stream_ty.payload {
1712 None => (
1714 "0".into(),
1715 "0".into(),
1716 "0".into(),
1717 "null".into(),
1718 "null".into(),
1719 "true",
1720 "false".into(),
1721 "false".into(),
1722 "false".into(),
1723 "undefined",
1724 ),
1725 Some(ty) => (
1727 self.types.canonical_abi(&ty).align32.to_string(),
1728 self.types.canonical_abi(&ty).size32.to_string(),
1729 self.types
1730 .canonical_abi(&ty)
1731 .flat_count
1732 .map(|v| v.to_string())
1733 .unwrap_or_else(|| "null".into()),
1734 gen_flat_lift_fn_js_expr(self, &ty, &None),
1735 gen_flat_lower_fn_js_expr(self, &ty, &None),
1736 "false",
1737 format!(
1738 "{}",
1739 matches!(
1740 ty,
1741 InterfaceType::U8
1742 | InterfaceType::U16
1743 | InterfaceType::U32
1744 | InterfaceType::U64
1745 | InterfaceType::S8
1746 | InterfaceType::S16
1747 | InterfaceType::S32
1748 | InterfaceType::S64
1749 | InterfaceType::Float32
1750 | InterfaceType::Float64
1751 )
1752 ),
1753 format!("{}", matches!(ty, InterfaceType::Borrow(_))),
1754 format!(
1755 "{}",
1756 matches!(ty, InterfaceType::Stream(_) | InterfaceType::Future(_))
1757 ),
1758 js_typed_array_ctor(&ty).unwrap_or("undefined"),
1759 ),
1760 };
1761
1762 uwriteln!(
1763 self.src.js,
1764 "const trampoline{i} = {stream_new_fn}.bind(null, {{
1765 streamTableIdx: {stream_table_idx},
1766 callerComponentIdx: {instance_idx},
1767 elemMeta: {{
1768 liftFn: {lift_fn_js},
1769 lowerFn: {lower_fn_js},
1770 payloadTypeName: {payload_ty_name_js},
1771 isNone: {is_none_js},
1772 isNumeric: {is_numeric_type_js},
1773 isBorrowed: {is_borrow_js},
1774 isAsyncValue: {is_async_value_js},
1775 typedArray: {typed_array_js},
1776 flatCount: {flat_count_js},
1777 align32: {align_32_js},
1778 size32: {size_32_js},
1779 }},
1780 }});\n",
1781 );
1782 }
1783
1784 Trampoline::StreamRead {
1785 instance,
1786 ty,
1787 options,
1788 } => {
1789 let options = self
1790 .component
1791 .options
1792 .get(*options)
1793 .expect("failed to find options");
1794 assert_eq!(
1795 instance.as_u32(),
1796 options.instance.as_u32(),
1797 "options index instance must match trampoline"
1798 );
1799
1800 let CanonicalOptions {
1801 instance,
1802 string_encoding,
1803 async_,
1804 data_model:
1805 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
1806 ..
1807 } = options
1808 else {
1809 unreachable!("missing/invalid data model for options during stream.read")
1810 };
1811 let (memory_idx_js, get_memory_fn_js) = match memory {
1812 Some(idx) => (
1813 idx.as_u32().to_string(),
1814 format!("() => memory{}", idx.as_u32()),
1815 ),
1816 None => ("undefined".into(), "undefined".into()),
1817 };
1818 let (realloc_idx, get_realloc_fn_js) = match realloc {
1819 Some(v) => {
1820 let v = v.as_u32().to_string();
1821 (v.to_string(), format!("() => realloc{v}"))
1822 }
1823 None => ("undefined".into(), "undefined".into()),
1824 };
1825
1826 let component_instance_id = instance.as_u32();
1827 let string_encoding = string_encoding_js_literal(string_encoding);
1828 let stream_table_idx = ty.as_u32();
1829 let stream_read_fn = self
1830 .bindgen
1831 .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamRead));
1832
1833 if let Some(memory_idx) = memory {
1838 let memory_idx = memory_idx.as_u32();
1839 let register_global_memory_for_component_fn = self
1840 .bindgen
1841 .intrinsic(Intrinsic::RegisterGlobalMemoryForComponent);
1842 uwriteln!(
1843 self.src.js_init,
1844 r#"{register_global_memory_for_component_fn}({{
1845 componentIdx: {component_instance_id},
1846 memoryIdx: {memory_idx},
1847 memory: memory{memory_idx},
1848 }});"#
1849 );
1850 }
1851
1852 uwriteln!(
1853 self.src.js,
1854 r#"const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_id}, {stream_read_fn}.bind(
1855 null,
1856 {{
1857 componentIdx: {component_instance_id},
1858 memoryIdx: {memory_idx_js},
1859 getMemoryFn: {get_memory_fn_js},
1860 reallocIdx: {realloc_idx},
1861 getReallocFn: {get_realloc_fn_js},
1862 stringEncoding: {string_encoding},
1863 isAsync: {async_},
1864 streamTableIdx: {stream_table_idx},
1865 }}
1866 )));
1867 "#,
1868 suspending_wrap_fn =
1869 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1870 );
1871 }
1872
1873 Trampoline::StreamWrite {
1874 instance,
1875 ty,
1876 options,
1877 } => {
1878 let options = self
1879 .component
1880 .options
1881 .get(*options)
1882 .expect("failed to find options");
1883 assert_eq!(
1884 instance.as_u32(),
1885 options.instance.as_u32(),
1886 "options index instance must match trampoline"
1887 );
1888
1889 let CanonicalOptions {
1890 instance,
1891 string_encoding,
1892 async_,
1893 data_model:
1894 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
1895 ..
1896 } = options
1897 else {
1898 unreachable!("unexpected memory data model during stream.write");
1899 };
1900 let component_instance_id = instance.as_u32();
1901 let (memory_idx_js, get_memory_fn_js) = match memory {
1902 Some(idx) => (
1903 idx.as_u32().to_string(),
1904 format!("() => memory{}", idx.as_u32()),
1905 ),
1906 None => ("undefined".into(), "undefined".into()),
1907 };
1908 let (realloc_idx, get_realloc_fn_js) = match realloc {
1909 Some(v) => {
1910 let v = v.as_u32().to_string();
1911 (v.to_string(), format!("() => realloc{v}"))
1912 }
1913 None => ("undefined".into(), "undefined".into()),
1914 };
1915
1916 let string_encoding = string_encoding_js_literal(string_encoding);
1917 let stream_table_idx = ty.as_u32();
1918 let stream_write_fn = self
1919 .bindgen
1920 .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWrite));
1921
1922 if let Some(memory_idx) = memory {
1926 let memory_idx = memory_idx.as_u32();
1927 let register_global_memory_for_component_fn = self
1928 .bindgen
1929 .intrinsic(Intrinsic::RegisterGlobalMemoryForComponent);
1930 uwriteln!(
1931 self.src.js_init,
1932 r#"{register_global_memory_for_component_fn}({{
1933 componentIdx: {component_instance_id},
1934 memoryIdx: {memory_idx},
1935 memory: memory{memory_idx},
1936 }});"#
1937 );
1938 }
1939
1940 uwriteln!(
1941 self.src.js,
1942 r#"
1943 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_id}, {stream_write_fn}.bind(
1944 null,
1945 {{
1946 componentIdx: {component_instance_id},
1947 memoryIdx: {memory_idx_js},
1948 getMemoryFn: {get_memory_fn_js},
1949 reallocIdx: {realloc_idx},
1950 getReallocFn: {get_realloc_fn_js},
1951 stringEncoding: {string_encoding},
1952 isAsync: {async_},
1953 streamTableIdx: {stream_table_idx},
1954 }}
1955 )));
1956 "#,
1957 suspending_wrap_fn =
1958 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1959 );
1960 }
1961
1962 Trampoline::StreamCancelRead {
1963 instance,
1964 ty,
1965 async_,
1966 }
1967 | Trampoline::StreamCancelWrite {
1968 instance,
1969 ty,
1970 async_,
1971 } => {
1972 let stream_cancel_fn = match trampoline {
1973 Trampoline::StreamCancelRead { .. } => self.bindgen.intrinsic(
1974 Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelRead),
1975 ),
1976 Trampoline::StreamCancelWrite { .. } => self.bindgen.intrinsic(
1977 Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelWrite),
1978 ),
1979 _ => unreachable!("unexpected trampoline"),
1980 };
1981
1982 let stream_table_idx = ty.as_u32();
1983 let component_idx = instance.as_u32();
1984 uwriteln!(
1985 self.src.js,
1986 r#"
1987 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {stream_cancel_fn}.bind(null, {{
1988 streamTableIdx: {stream_table_idx},
1989 isAsync: {async_},
1990 componentIdx: {component_idx},
1991 }})));
1992 "#,
1993 suspending_wrap_fn =
1994 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1995 );
1996 }
1997
1998 Trampoline::StreamDropReadable { ty, instance }
1999 | Trampoline::StreamDropWritable { ty, instance } => {
2000 let intrinsic_fn = match trampoline {
2001 Trampoline::StreamDropReadable { .. } => self.bindgen.intrinsic(
2002 Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropReadable),
2003 ),
2004 Trampoline::StreamDropWritable { .. } => self.bindgen.intrinsic(
2005 Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropWritable),
2006 ),
2007 _ => unreachable!("unexpected trampoline"),
2008 };
2009 let stream_idx = ty.as_u32();
2010 let instance_idx = instance.as_u32();
2011 uwriteln!(
2012 self.src.js,
2013 "const trampoline{i} = {intrinsic_fn}.bind(null, {{
2014 streamTableIdx: {stream_idx},
2015 componentIdx: {instance_idx},
2016 }});\n",
2017 );
2018 }
2019
2020 Trampoline::StreamTransfer => {
2021 let stream_transfer_fn = self
2022 .bindgen
2023 .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamTransfer));
2024 uwriteln!(self.src.js, "const trampoline{i} = {stream_transfer_fn};\n",);
2025 }
2026
2027 Trampoline::FutureNew { instance, ty } => {
2028 let future_new_fn = self
2029 .bindgen
2030 .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureNew));
2031 let future_table_idx = ty.as_u32();
2032 let component_idx = instance.as_u32();
2033
2034 let future_table_ty = &self.types[*ty];
2036 let future_ty = &self.types[future_table_ty.ty];
2037 let (
2038 payload_size32,
2039 payload_align32,
2040 payload_flat_count_js,
2041 payload_lift_fn_js,
2042 payload_lower_fn_js,
2043 is_borrowed,
2044 is_none_type,
2045 is_numeric_type,
2046 is_async_value,
2047 ) = match future_ty.payload {
2048 None => (
2049 0,
2050 0,
2051 "0".into(),
2052 "() => {{ throw new Error('empty future payload'); }}".into(),
2053 "() => {{ throw new Error('empty future payload'); }}".into(),
2054 false,
2055 true,
2056 false,
2057 false,
2058 ),
2059 Some(payload_ty) => {
2060 let cabi = self.types.canonical_abi(&payload_ty);
2061 (
2062 cabi.size32,
2063 cabi.align32,
2064 cabi.flat_count
2065 .map(|v| format!("{v}"))
2066 .unwrap_or_else(|| "null".into()),
2067 gen_flat_lift_fn_js_expr(self, &payload_ty, &None),
2068 gen_flat_lower_fn_js_expr(self, &payload_ty, &None),
2069 matches!(payload_ty, InterfaceType::Borrow(_)),
2070 false,
2071 matches!(
2072 payload_ty,
2073 InterfaceType::U8
2074 | InterfaceType::U16
2075 | InterfaceType::U32
2076 | InterfaceType::U64
2077 | InterfaceType::S8
2078 | InterfaceType::S16
2079 | InterfaceType::S32
2080 | InterfaceType::S64
2081 | InterfaceType::Float32
2082 | InterfaceType::Float64
2083 ),
2084 matches!(
2085 payload_ty,
2086 InterfaceType::Stream(_) | InterfaceType::Future(_)
2087 ),
2088 )
2089 }
2090 };
2091 let payload_ty_name_js = future_ty
2092 .payload
2093 .map(|iface_ty| format!("'{iface_ty:?}'"))
2094 .unwrap_or_else(|| "null".into());
2095
2096 uwriteln!(
2097 self.src.js,
2098 r#"
2099 const trampoline{i} = {future_new_fn}.bind(null, {{
2100 componentIdx: {component_idx},
2101 futureTableIdx: {future_table_idx},
2102 elemMeta: {{
2103 liftFn: {payload_lift_fn_js},
2104 lowerFn: {payload_lower_fn_js},
2105 payloadTypeName: {payload_ty_name_js},
2106 isNone: {is_none_type},
2107 isNumeric: {is_numeric_type},
2108 isBorrowed: {is_borrowed},
2109 isAsyncValue: {is_async_value},
2110 flatCount: {payload_flat_count_js},
2111 align32: {payload_align32},
2112 size32: {payload_size32},
2113 }},
2114 }});
2115 "#,
2116 );
2117 }
2118
2119 Trampoline::FutureWrite {
2120 instance,
2121 ty,
2122 options,
2123 }
2124 | Trampoline::FutureRead {
2125 instance,
2126 ty,
2127 options,
2128 } => {
2129 let intrinsic_fn = match trampoline {
2130 Trampoline::FutureRead { .. } => self
2131 .bindgen
2132 .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureRead)),
2133 Trampoline::FutureWrite { .. } => self
2134 .bindgen
2135 .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureWrite)),
2136 _ => unreachable!("invalid trampoline"),
2137 };
2138
2139 let options = self
2140 .component
2141 .options
2142 .get(*options)
2143 .expect("failed to find options");
2144 let CanonicalOptions {
2145 async_,
2146 string_encoding,
2147 callback,
2148 post_return,
2149 data_model:
2150 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2151 ..
2152 } = options
2153 else {
2154 unreachable!("unexpected memory data model during future intrinsic");
2155 };
2156
2157 assert_eq!(
2158 *instance, options.instance,
2159 "component instances should match"
2160 );
2161 assert!(
2162 callback.is_none(),
2163 "callback should not be present for future intrinsic"
2164 );
2165 assert!(
2166 post_return.is_none(),
2167 "post_return should not be present for future intrinsic"
2168 );
2169
2170 let future_table_idx = ty.as_u32();
2171 let component_idx = instance.as_u32();
2172 let (memory_idx_js, get_memory_fn_js) = match memory {
2173 Some(idx) => (
2174 idx.as_u32().to_string(),
2175 format!("() => memory{}", idx.as_u32()),
2176 ),
2177 None => ("undefined".into(), "undefined".into()),
2178 };
2179 let (realloc_idx, get_realloc_fn_js) = match realloc {
2180 Some(idx) => (
2181 idx.as_u32().to_string(),
2182 format!("() => realloc{}", idx.as_u32()),
2183 ),
2184 None => ("undefined".into(), "undefined".to_string()),
2185 };
2186 let string_encoding = string_encoding_js_literal(string_encoding);
2187
2188 uwriteln!(
2189 self.src.js,
2190 r#"
2191 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {intrinsic_fn}.bind(
2192 null,
2193 {{
2194 componentIdx: {component_idx},
2195 memoryIdx: {memory_idx_js},
2196 getMemoryFn: {get_memory_fn_js},
2197 reallocIdx: {realloc_idx},
2198 getReallocFn: {get_realloc_fn_js},
2199 stringEncoding: {string_encoding},
2200 futureTableIdx: {future_table_idx},
2201 isAsync: {async_},
2202 }},
2203 )));
2204 "#,
2205 suspending_wrap_fn =
2206 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2207 );
2208 }
2209
2210 Trampoline::FutureCancelRead {
2211 instance,
2212 ty,
2213 async_,
2214 }
2215 | Trampoline::FutureCancelWrite {
2216 instance,
2217 ty,
2218 async_,
2219 } => {
2220 let future_cancel_op_fn = match trampoline {
2221 Trampoline::FutureCancelRead { .. } => self.bindgen.intrinsic(
2222 Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelRead),
2223 ),
2224 Trampoline::FutureCancelWrite { .. } => self.bindgen.intrinsic(
2225 Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelWrite),
2226 ),
2227 _ => unreachable!(),
2228 };
2229
2230 let component_idx = instance.as_u32();
2231 let future_table_idx = ty.as_u32();
2232
2233 uwriteln!(
2234 self.src.js,
2235 r#"
2236 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {future_cancel_op_fn}.bind(
2237 null,
2238 {{
2239 futureTableIdx: {future_table_idx},
2240 componentIdx: {component_idx},
2241 isAsync: {async_},
2242 }},
2243 )));
2244 "#,
2245 suspending_wrap_fn =
2246 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2247 );
2248 }
2249
2250 Trampoline::FutureDropReadable { instance, ty }
2251 | Trampoline::FutureDropWritable { instance, ty } => {
2252 let future_drop_op_fn = match trampoline {
2253 Trampoline::FutureDropReadable { .. } => self.bindgen.intrinsic(
2254 Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropReadable),
2255 ),
2256 Trampoline::FutureDropWritable { .. } => self.bindgen.intrinsic(
2257 Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropWritable),
2258 ),
2259 _ => unreachable!(),
2260 };
2261
2262 let component_idx = instance.as_u32();
2263 let future_table_idx = ty.as_u32();
2264
2265 uwriteln!(
2266 self.src.js,
2267 r#"
2268 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {future_drop_op_fn}.bind(
2269 null,
2270 {{
2271 futureTableIdx: {future_table_idx},
2272 componentIdx: {component_idx},
2273 }},
2274 )));
2275 "#,
2276 suspending_wrap_fn =
2277 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2278 );
2279 }
2280
2281 Trampoline::FutureTransfer => {
2282 let future_transfer_fn = self
2283 .bindgen
2284 .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureTransfer));
2285 uwriteln!(self.src.js, "const trampoline{i} = {future_transfer_fn};");
2286 }
2287
2288 Trampoline::ErrorContextNew { ty, options, .. } => {
2289 let CanonicalOptions {
2290 instance,
2291 string_encoding,
2292 data_model:
2293 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
2294 ..
2295 } = self
2296 .component
2297 .options
2298 .get(*options)
2299 .expect("failed to find options")
2300 else {
2301 panic!("unexpected memory data model during error-context.new");
2302 };
2303
2304 self.ensure_error_context_local_table(*instance, *ty);
2305
2306 let local_err_tbl_idx = ty.as_u32();
2307 let component_idx = instance.as_u32();
2308
2309 let memory_idx = memory
2310 .expect("missing realloc fn idx for error-context.debug-message")
2311 .as_u32();
2312
2313 let decoder = match string_encoding {
2315 wasmtime_environ::component::StringEncoding::Utf8 => self
2316 .bindgen
2317 .intrinsic(Intrinsic::String(StringIntrinsic::GlobalTextDecoderUtf8)),
2318 wasmtime_environ::component::StringEncoding::Utf16 => self
2319 .bindgen
2320 .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Decoder)),
2321 enc => panic!(
2322 "unsupported string encoding [{enc:?}] for error-context.debug-message"
2323 ),
2324 };
2325 uwriteln!(
2326 self.src.js,
2327 "function trampoline{i}InputStr(ptr, len) {{
2328 return {decoder}.decode(new DataView(memory{memory_idx}.buffer, ptr, len));
2329 }}"
2330 );
2331
2332 let err_ctx_new_fn = self
2333 .bindgen
2334 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextNew));
2335 uwriteln!(
2337 self.src.js,
2338 "const trampoline{i} = {err_ctx_new_fn}.bind(
2339 null,
2340 {{
2341 componentIdx: {component_idx},
2342 localTableIdx: {local_err_tbl_idx},
2343 readStrFn: trampoline{i}InputStr,
2344 }}
2345 );
2346 "
2347 );
2348 }
2349
2350 Trampoline::ErrorContextDebugMessage {
2351 instance, options, ..
2352 } => {
2353 let CanonicalOptions {
2354 async_,
2355 callback,
2356 post_return,
2357 string_encoding,
2358 data_model:
2359 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2360 ..
2361 } = self
2362 .component
2363 .options
2364 .get(*options)
2365 .expect("failed to find options")
2366 else {
2367 panic!("unexpected memory data model during error-context.debug-message");
2368 };
2369
2370 let debug_message_fn = self
2371 .bindgen
2372 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDebugMessage));
2373
2374 let realloc_fn_idx = realloc
2375 .expect("missing realloc fn idx for error-context.debug-message")
2376 .as_u32();
2377 let memory_idx = memory
2378 .expect("missing realloc fn idx for error-context.debug-message")
2379 .as_u32();
2380
2381 match string_encoding {
2383 wasmtime_environ::component::StringEncoding::Utf8 => {
2384 let encode_fn = self
2385 .bindgen
2386 .intrinsic(Intrinsic::String(StringIntrinsic::Utf8Encode));
2387 uwriteln!(
2388 self.src.js,
2389 "function trampoline{i}OutputStr(s, outputPtr) {{
2390 const memory = memory{memory_idx};
2391 const reallocFn = realloc{realloc_fn_idx};
2392 let {{ ptr, len }} = {encode_fn}(s, reallocFn, memory);
2393 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
2394 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
2395 }}"
2396 );
2397 }
2398 wasmtime_environ::component::StringEncoding::Utf16 => {
2399 let encode_fn = self
2400 .bindgen
2401 .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Encode));
2402 uwriteln!(
2403 self.src.js,
2404 "function trampoline{i}OutputStr(s, outputPtr) {{
2405 const memory = memory{memory_idx};
2406 const reallocFn = realloc{realloc_fn_idx};
2407 let ptr = {encode_fn}(s, reallocFn, memory);
2408 let len = s.length;
2409 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
2410 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
2411 }}"
2412 );
2413 }
2414 enc => panic!(
2415 "unsupported string encoding [{enc:?}] for error-context.debug-message"
2416 ),
2417 };
2418
2419 let options_obj = format!(
2420 "{{callback:{callback}, postReturn: {post_return}, async: {async_}}}",
2421 callback = callback
2422 .map(|v| v.as_u32().to_string())
2423 .unwrap_or_else(|| "null".into()),
2424 post_return = post_return
2425 .map(|v| v.as_u32().to_string())
2426 .unwrap_or_else(|| "null".into()),
2427 );
2428
2429 let component_idx = instance.as_u32();
2430 uwriteln!(
2431 self.src.js,
2432 "const trampoline{i} = {debug_message_fn}.bind(
2433 null,
2434 {{
2435 componentIdx: {component_idx},
2436 options: {options_obj},
2437 writeStrFn: trampoline{i}OutputStr,
2438 }}
2439 );"
2440 );
2441 }
2442
2443 Trampoline::ErrorContextDrop { instance, ty } => {
2444 let drop_fn = self
2445 .bindgen
2446 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDrop));
2447 let local_err_tbl_idx = ty.as_u32();
2448 let component_idx = instance.as_u32();
2449 uwriteln!(
2450 self.src.js,
2451 r#"
2452 const trampoline{i} = {drop_fn}.bind(
2453 null,
2454 {{ componentIdx: {component_idx}, localTableIdx: {local_err_tbl_idx} }},
2455 );
2456 "#
2457 );
2458 }
2459
2460 Trampoline::ErrorContextTransfer => {
2461 let transfer_fn = self
2462 .bindgen
2463 .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextTransfer));
2464 uwriteln!(self.src.js, "const trampoline{i} = {transfer_fn};");
2465 }
2466
2467 Trampoline::PrepareCall { memory } => {
2469 let prepare_call_fn = self
2470 .bindgen
2471 .intrinsic(Intrinsic::Host(HostIntrinsic::PrepareCall));
2472 let (memory_idx_js, memory_fn_js) = memory
2473 .map(|v| {
2474 (
2475 v.as_u32().to_string(),
2476 format!("() => memory{}", v.as_u32()),
2477 )
2478 })
2479 .unwrap_or_else(|| ("null".into(), "() => null".into()));
2480 uwriteln!(
2481 self.src.js,
2482 "const trampoline{i} = {prepare_call_fn}.bind(null, {memory_idx_js}, {memory_fn_js});",
2483 )
2484 }
2485
2486 Trampoline::SyncStartCall { callback } => {
2487 let sync_start_call_fn = self
2488 .bindgen
2489 .intrinsic(Intrinsic::Host(HostIntrinsic::SyncStartCall));
2490 let (callback_idx, callback_fn) = callback
2491 .map(|v| (v.as_u32().to_string(), format!("callback_{}", v.as_u32())))
2492 .unwrap_or_else(|| ("null".into(), "null".into()));
2493
2494 uwriteln!(
2498 self.src.js,
2499 "const trampoline{i} = new WebAssembly.Suspending({sync_start_call_fn}.bind(
2500 null,
2501 {{
2502 callbackIdx: {callback_idx},
2503 getCallbackFn: () => {callback_fn},
2504 }},
2505 ));",
2506 );
2507 }
2508
2509 Trampoline::AsyncStartCall {
2512 callback,
2513 post_return,
2514 } => {
2515 let async_start_call_fn = self
2516 .bindgen
2517 .intrinsic(Intrinsic::Host(HostIntrinsic::AsyncStartCall));
2518 let (callback_idx, callback_fn) = callback
2519 .map(|v| (v.as_u32().to_string(), format!("callback_{}", v.as_u32())))
2520 .unwrap_or_else(|| ("null".into(), "null".into()));
2521 let (post_return_idx, post_return_fn) = post_return
2522 .map(|v| (v.as_u32().to_string(), format!("postReturn{}", v.as_u32())))
2523 .unwrap_or_else(|| ("null".into(), "null".into()));
2524
2525 uwriteln!(
2526 self.src.js,
2527 "const trampoline{i} = {async_start_call_fn}.bind(
2528 null,
2529 {{
2530 postReturnIdx: {post_return_idx},
2531 getPostReturnFn: () => {post_return_fn},
2532 callbackIdx: {callback_idx},
2533 getCallbackFn: () => {callback_fn},
2534 }},
2535 );",
2536 );
2537 }
2538
2539 Trampoline::LowerImport {
2540 index: _,
2541 lower_ty,
2542 options,
2543 } => {
2544 let canon_opts = self
2545 .component
2546 .options
2547 .get(*options)
2548 .expect("failed to find options");
2549
2550 let component_idx = canon_opts.instance.as_u32();
2556 let is_async = canon_opts.async_;
2557
2558 let cancellable = canon_opts.cancellable;
2559
2560 let func_ty = self.types.index(*lower_ty);
2561
2562 let param_types = &self.types.index(func_ty.params).types;
2564 let param_lift_fns_js =
2565 gen_flat_lift_fn_list_js_expr(self, param_types.iter().as_slice(), &None);
2566
2567 let result_types = &self.types.index(func_ty.results).types;
2569 let result_lower_fns_js =
2570 gen_flat_lower_fn_list_js_expr(self, result_types.iter().as_slice(), &None);
2571 let result_flat_count = result_types.iter().try_fold(0usize, |count, ty| {
2572 self.types
2573 .canonical_abi(ty)
2574 .flat_count
2575 .map(|flat_count| count + usize::from(flat_count))
2576 });
2577
2578 let get_callback_fn_js = canon_opts
2579 .callback
2580 .map(|idx| format!("() => callback_{}", idx.as_u32()))
2581 .unwrap_or_else(|| "() => null".into());
2582 let get_post_return_fn_js = canon_opts
2583 .post_return
2584 .map(|idx| format!("() => postReturn{}", idx.as_u32()))
2585 .unwrap_or_else(|| "() => null".into());
2586
2587 let (memory_exprs, realloc_expr_js) =
2589 if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
2590 memory,
2591 realloc,
2592 }) = canon_opts.data_model
2593 {
2594 (
2595 memory.map(|idx| {
2596 (
2597 idx.as_u32().to_string(),
2598 format!("() => memory{}", idx.as_u32()),
2599 )
2600 }),
2601 realloc.map(|idx| format!("() => realloc{}", idx.as_u32())),
2602 )
2603 } else {
2604 (None, None)
2605 };
2606 let (memory_idx_js, memory_expr_js) =
2607 memory_exprs.unwrap_or_else(|| ("null".into(), "() => null".into()));
2608 let realloc_expr_js = realloc_expr_js.unwrap_or_else(|| "undefined".into());
2609 let string_encoding_js = string_encoding_js_literal(&canon_opts.string_encoding);
2610
2611 let func_ty_async = func_ty.async_;
2613 let max_direct_results = if is_async || func_ty_async {
2614 0
2615 } else {
2616 MAX_FLAT_RESULTS
2617 };
2618 let has_result_pointer = result_flat_count
2619 .map(|count| count > max_direct_results)
2620 .unwrap_or(true);
2621 let call = format!(
2622 r#"{lower_import_intrinsic}.bind(
2623 null,
2624 {{
2625 trampolineIdx: {i},
2626 componentIdx: {component_idx},
2627 isAsync: {is_async},
2628 isManualAsync: _trampoline{i}.manuallyAsync,
2629 paramLiftFns: {param_lift_fns_js},
2630 resultLowerFns: {result_lower_fns_js},
2631 hasResultPointer: {has_result_pointer},
2632 funcTypeIsAsync: {func_ty_async},
2633 getCallbackFn: {get_callback_fn_js},
2634 getPostReturnFn: {get_post_return_fn_js},
2635 isCancellable: {cancellable},
2636 memoryIdx: {memory_idx_js},
2637 stringEncoding: {string_encoding_js},
2638 getMemoryFn: {memory_expr_js},
2639 getReallocFn: {realloc_expr_js},
2640 importFn: _trampoline{i},
2641 }},
2642 )"#,
2643 lower_import_intrinsic = if is_async || func_ty_async {
2644 self.bindgen
2645 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::LowerImport))
2646 } else {
2647 self.bindgen.intrinsic(Intrinsic::AsyncTask(
2648 AsyncTaskIntrinsic::LowerImportBackwardsCompat,
2649 ))
2650 }
2651 );
2652
2653 let suspending_wrap_fn =
2656 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
2657 if is_async || func_ty_async {
2658 uwriteln!(
2659 self.src.js,
2660 "let trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {call}));"
2661 );
2662 } else {
2663 uwriteln!(
2666 self.src.js,
2667 "let trampoline{i} = _trampoline{i}.manuallyAsync ? new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {call})) : {call};"
2668 );
2669 }
2670 }
2671
2672 Trampoline::Transcoder {
2673 op,
2674 from,
2675 from64,
2676 to,
2677 to64,
2678 } => {
2679 if *from64 || *to64 {
2680 unimplemented!("memory 64 transcoder");
2681 }
2682 let from = from.as_u32();
2683 let to = to.as_u32();
2684 match op {
2685 Transcode::Copy(FixedEncoding::Utf8) => {
2686 uwriteln!(
2687 self.src.js,
2688 r#"
2689 function trampoline{i} (from_ptr, len, to_ptr) {{
2690 new Uint8Array(memory{to}.buffer, to_ptr, len).set(new Uint8Array(memory{from}.buffer, from_ptr, len));
2691 }}
2692 "#
2693 );
2694 }
2695 Transcode::Copy(FixedEncoding::Utf16) => unimplemented!("utf16 copier"),
2696 Transcode::Copy(FixedEncoding::Latin1) => unimplemented!("latin1 copier"),
2697 Transcode::Latin1ToUtf16 => unimplemented!("latin to utf16 transcoder"),
2698 Transcode::Latin1ToUtf8 => unimplemented!("latin to utf8 transcoder"),
2699 Transcode::Utf16ToCompactProbablyUtf16 => {
2700 unimplemented!("utf16 to compact wtf16 transcoder")
2701 }
2702 Transcode::Utf16ToCompactUtf16 => {
2703 unimplemented!("utf16 to compact utf16 transcoder")
2704 }
2705 Transcode::Utf16ToLatin1 => unimplemented!("utf16 to latin1 transcoder"),
2706 Transcode::Utf16ToUtf8 => {
2707 uwriteln!(
2708 self.src.js,
2709 r#"
2710 function trampoline{i} (src, src_len, dst, dst_len) {{
2711 const encoder = new TextEncoder();
2712 const {{ read, written }} = encoder.encodeInto(String.fromCharCode.apply(null, new Uint16Array(memory{from}.buffer, src, src_len)), new Uint8Array(memory{to}.buffer, dst, dst_len));
2713 return [read, written];
2714 }}
2715 "#,
2716 );
2717 }
2718 Transcode::Utf8ToCompactUtf16 => {
2719 unimplemented!("utf8 to compact utf16 transcoder")
2720 }
2721 Transcode::Utf8ToLatin1 => unimplemented!("utf8 to latin1 transcoder"),
2722 Transcode::Utf8ToUtf16 => {
2723 uwriteln!(
2724 self.src.js,
2725 r#"
2726 function trampoline{i} (from_ptr, len, to_ptr) {{
2727 const decoder = new TextDecoder();
2728 const content = decoder.decode(new Uint8Array(memory{from}.buffer, from_ptr, len));
2729 const codeUnits = content.length;
2730 const view = new Uint16Array(memory{to}.buffer, to_ptr, codeUnits);
2731 for (var i = 0; i < codeUnits; i++) {{
2732 view[i] = content.charCodeAt(i);
2733 }}
2734 return codeUnits;
2735 }}
2736 "#,
2737 );
2738 }
2739 };
2740 }
2741
2742 Trampoline::ResourceNew {
2743 ty: resource_ty_idx,
2744 ..
2745 } => {
2746 self.ensure_resource_table(*resource_ty_idx);
2747 let rid = resource_ty_idx.as_u32();
2748 let rsc_table_create_own = self.bindgen.intrinsic(Intrinsic::Resource(
2749 ResourceIntrinsic::ResourceTableCreateOwn,
2750 ));
2751 uwriteln!(
2752 self.src.js,
2753 "const trampoline{i} = {rsc_table_create_own}.bind(null, handleTable{rid});"
2754 );
2755 }
2756
2757 Trampoline::ResourceRep {
2758 ty: resource_ty_idx,
2759 ..
2760 } => {
2761 self.ensure_resource_table(*resource_ty_idx);
2762 let rid = resource_ty_idx.as_u32();
2763 let rsc_table_get = self
2764 .bindgen
2765 .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableGet));
2766 uwriteln!(
2767 self.src.js,
2768 "function trampoline{i} (handle) {{
2769 return {rsc_table_get}(handleTable{rid}, handle).rep;
2770 }}"
2771 );
2772 }
2773
2774 Trampoline::ResourceDrop {
2775 ty: resource_table_ty_idx,
2776 ..
2777 } => {
2778 self.ensure_resource_table(*resource_table_ty_idx);
2779 let tid = resource_table_ty_idx.as_u32();
2780 let resource_table_ty = &self.types[*resource_table_ty_idx];
2781 let resource_ty = resource_table_ty.unwrap_concrete_ty();
2782 let rid = resource_ty.as_u32();
2783
2784 let dtor = if let Some(resource_idx) =
2786 self.component.defined_resource_index(resource_ty)
2787 {
2788 let resource_def = self
2789 .component
2790 .initializers
2791 .iter()
2792 .find_map(|i| match i {
2793 GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
2794 _ => None,
2795 })
2796 .unwrap();
2797
2798 if let Some(dtor) = &resource_def.dtor {
2800 format!(
2801 "
2802 {}(handleEntry.rep);",
2803 self.core_def(dtor)
2804 )
2805 } else {
2806 "".into()
2807 }
2808 } else {
2809 let symbol_dispose = self.bindgen.intrinsic(Intrinsic::SymbolDispose);
2816 let symbol_cabi_dispose = self.bindgen.intrinsic(Intrinsic::SymbolCabiDispose);
2817
2818 if let Some(imported_resource_local_name) =
2820 self.bindgen.local_names.try_get(resource_ty)
2821 {
2822 format!(
2823 "
2824 const rsc = captureTable{rid}.get(handleEntry.rep);
2825 if (rsc) {{
2826 if (rsc[{symbol_dispose}]) rsc[{symbol_dispose}]();
2827 captureTable{rid}.delete(handleEntry.rep);
2828 }} else if ({imported_resource_local_name}[{symbol_cabi_dispose}]) {{
2829 {imported_resource_local_name}[{symbol_cabi_dispose}](handleEntry.rep);
2830 }}"
2831 )
2832 } else {
2833 format!(
2835 "throw new TypeError('unreachable trampoline for resource [{:?}]')",
2836 resource_ty
2837 )
2838 }
2839 };
2840
2841 let rsc_table_remove = self
2842 .bindgen
2843 .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
2844 uwrite!(
2845 self.src.js,
2846 "function trampoline{i}(handle) {{
2847 const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
2848 if (handleEntry.own) {{
2849 {dtor}
2850 }}
2851 }}
2852 ",
2853 );
2854 }
2855
2856 Trampoline::ResourceTransferOwn => {
2857 let resource_transfer = self
2858 .bindgen
2859 .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTransferOwn));
2860 uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
2861 }
2862
2863 Trampoline::ResourceTransferBorrow => {
2864 let resource_transfer =
2865 self.bindgen
2866 .intrinsic(if self.bindgen.opts.valid_lifting_optimization {
2867 Intrinsic::Resource(
2868 ResourceIntrinsic::ResourceTransferBorrowValidLifting,
2869 )
2870 } else {
2871 Intrinsic::Resource(ResourceIntrinsic::ResourceTransferBorrow)
2872 });
2873 uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
2874 }
2875
2876 Trampoline::TaskReturn {
2877 results, options, ..
2878 } => {
2879 let canon_opts = self
2880 .component
2881 .options
2882 .get(*options)
2883 .expect("failed to find options");
2884 let CanonicalOptions {
2885 instance,
2886 async_,
2887 data_model:
2888 CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2889 callback,
2890 post_return,
2891 string_encoding,
2892 ..
2893 } = canon_opts
2894 else {
2895 unreachable!("unexpected memory data model during task.return");
2896 };
2897
2898 if realloc.is_some() && memory.is_none() {
2900 panic!("memory must be present if realloc is");
2901 }
2902 if *async_ && post_return.is_some() {
2903 panic!("async and post return must not be specified together");
2904 }
2905 if *async_ && callback.is_none() {
2906 panic!("callback must be specified for async");
2907 }
2908 if let Some(cb_idx) = callback {
2909 let cb_fn = &self.types[TypeFuncIndex::from_u32(cb_idx.as_u32())];
2910 match self.types[cb_fn.params].types[..] {
2911 [InterfaceType::S32, InterfaceType::S32, InterfaceType::S32] => {}
2912 _ => panic!("unexpected params for async callback fn"),
2913 }
2914 match self.types[cb_fn.results].types[..] {
2915 [InterfaceType::S32] => {}
2916 _ => panic!("unexpected results for async callback fn"),
2917 }
2918 }
2919
2920 let result_types = &self.types[*results].types;
2921
2922 let result_flat_param_total: usize = result_types
2925 .iter()
2926 .map(|t| {
2927 self.types
2928 .canonical_abi(t)
2929 .flat_count
2930 .map(usize::from)
2931 .unwrap_or(0)
2932 })
2933 .sum();
2934 let use_direct_params = result_flat_param_total < MAX_FLAT_PARAMS;
2935
2936 let mut lift_fns: Vec<String> = Vec::with_capacity(result_types.len());
2939 for result_ty in result_types {
2940 lift_fns.push(gen_flat_lift_fn_js_expr(self, result_ty, &None));
2941 }
2942 let lift_fns_js = format!("[{}]", lift_fns.join(","));
2943
2944 let mut lower_fns: Vec<String> = Vec::with_capacity(result_types.len());
2950 for result_ty in result_types {
2951 lower_fns.push(gen_flat_lower_fn_js_expr(self, result_ty, &None));
2952 }
2953 let lower_fns_js = format!("[{}]", lower_fns.join(","));
2954
2955 let get_memory_fn_js = memory
2956 .map(|idx| format!("() => memory{}", idx.as_u32()))
2957 .unwrap_or_else(|| "() => null".into());
2958 let memory_idx_js = memory
2959 .map(|idx| idx.as_u32().to_string())
2960 .unwrap_or_else(|| "null".into());
2961 let component_idx = instance.as_u32();
2962 let task_return_fn = self
2963 .bindgen
2964 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskReturn));
2965 let callback_fn_idx = callback
2966 .map(|v| v.as_u32().to_string())
2967 .unwrap_or_else(|| "null".into());
2968 let string_encoding_js = string_encoding_js_literal(string_encoding);
2969
2970 uwriteln!(
2971 self.src.js,
2972 "const trampoline{i} = {task_return_fn}.bind(
2973 null,
2974 {{
2975 componentIdx: {component_idx},
2976 useDirectParams: {use_direct_params},
2977 getMemoryFn: {get_memory_fn_js},
2978 memoryIdx: {memory_idx_js},
2979 callbackFnIdx: {callback_fn_idx},
2980 liftFns: {lift_fns_js},
2981 lowerFns: {lower_fns_js},
2982 stringEncoding: {string_encoding_js},
2983 }},
2984 );",
2985 );
2986 }
2987
2988 Trampoline::BackpressureInc { instance } => {
2989 let backpressure_inc_fn = self
2990 .bindgen
2991 .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureInc));
2992 uwriteln!(
2993 self.src.js,
2994 "const trampoline{i} = {backpressure_inc_fn}.bind(null, {instance});\n",
2995 instance = instance.as_u32(),
2996 );
2997 }
2998
2999 Trampoline::BackpressureDec { instance } => {
3000 let backpressure_dec_fn = self
3001 .bindgen
3002 .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureDec));
3003 uwriteln!(
3004 self.src.js,
3005 "const trampoline{i} = {backpressure_dec_fn}.bind(null, {instance});\n",
3006 instance = instance.as_u32(),
3007 );
3008 }
3009
3010 Trampoline::ThreadYield {
3011 cancellable,
3012 instance,
3013 } => {
3014 let yield_fn = self
3015 .bindgen
3016 .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::Yield));
3017 let suspending_wrap_fn =
3018 self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
3019 let component_instance_idx = instance.as_u32();
3020 uwriteln!(
3021 self.src.js,
3022 r#"
3023 const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_idx}, {yield_fn}.bind(null, {{
3024 isCancellable: {cancellable},
3025 componentIdx: {component_instance_idx},
3026 }})));
3027 "#,
3028 );
3029 }
3030 Trampoline::ThreadIndex => todo!("Trampoline::ThreadIndex"),
3031 Trampoline::ThreadNewIndirect { .. } => todo!("Trampoline::ThreadNewIndirect"),
3032 Trampoline::ThreadSuspend { .. } => todo!("Trampoline::ThreadSuspend"),
3033 Trampoline::ThreadSuspendTo { .. } => todo!("Trampoline::ThreadSuspendTo"),
3034 Trampoline::ThreadUnsuspend { .. } => todo!("Trampoline::ThreadUnsuspend"),
3035 Trampoline::ThreadYieldToSuspended { .. } => {
3036 todo!("Trampoline::ThreadYieldToSuspended")
3037 }
3038 Trampoline::ThreadSuspendToSuspended { .. } => {
3039 todo!("Trampoline::ThreadYieldToSuspended")
3040 }
3041
3042 Trampoline::Trap => {
3043 uwriteln!(
3044 self.src.js,
3045 "function trampoline{i}(rep) {{ throw new TypeError('Trap'); }}"
3046 );
3047 }
3048
3049 Trampoline::EnterSyncCall => {
3050 let enter_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
3051 Intrinsic::AsyncTask(AsyncTaskIntrinsic::EnterSymmetricSyncGuestCall),
3052 );
3053 let uses_jspi = matches!(
3062 self.bindgen.opts.async_mode,
3063 Some(AsyncMode::JavaScriptPromiseIntegration { .. })
3064 );
3065 if uses_jspi {
3066 uwriteln!(
3067 self.src.js,
3068 r#"
3069 const trampoline{i} = new WebAssembly.Suspending({enter_symmetric_sync_guest_call_fn});
3070 "#,
3071 );
3072 } else {
3073 uwriteln!(
3074 self.src.js,
3075 r#"
3076 const trampoline{i} = {enter_symmetric_sync_guest_call_fn};
3077 "#,
3078 );
3079 }
3080 }
3081
3082 Trampoline::ExitSyncCall => {
3083 let exit_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
3084 Intrinsic::AsyncTask(AsyncTaskIntrinsic::ExitSymmetricSyncGuestCall),
3085 );
3086 uwriteln!(
3087 self.src.js,
3088 "const trampoline{i} = {exit_symmetric_sync_guest_call_fn};\n",
3089 );
3090 }
3091 }
3092 }
3093
3094 fn instantiation_global_initializer(&mut self, init: &GlobalInitializer) {
3095 match init {
3096 GlobalInitializer::ExtractCallback(ExtractCallback { index, def }) => {
3103 let callback_idx = index.as_u32();
3104 let core_def = self.core_def(def);
3105
3106 uwriteln!(self.src.js, "let callback_{callback_idx};",);
3107
3108 uwriteln!(
3117 self.src.js_init,
3118 r#"
3119 callback_{callback_idx} = WebAssembly.promising({core_def});
3120 callback_{callback_idx}.fnName = "{core_def}";
3121 "#
3122 );
3123 }
3124
3125 GlobalInitializer::InstantiateModule(m, instance) => {
3126 self.init_current_module = *instance;
3130
3131 match m {
3132 InstantiateModule::Static(idx, args) => {
3133 self.instantiate_static_module(*idx, args, *instance);
3134 }
3135 InstantiateModule::Import(..) => unimplemented!(),
3139 }
3140 }
3141
3142 GlobalInitializer::LowerImport { index, import } => {
3143 self.lower_import(*index, *import);
3144 }
3145
3146 GlobalInitializer::ExtractMemory(m) => {
3147 let def = self.core_export_var_name(&m.export);
3148 let idx = m.index.as_u32();
3149 uwriteln!(self.src.js, "let memory{idx};");
3150 uwriteln!(self.src.js_init, "memory{idx} = {def};");
3151 }
3152
3153 GlobalInitializer::ExtractRealloc(r) => {
3154 let def = self.core_def(&r.def);
3155 let idx = r.index.as_u32();
3156 uwriteln!(self.src.js, "let realloc{idx};");
3157 uwriteln!(self.src.js, "let realloc{idx}Async;");
3158 uwriteln!(self.src.js_init, "realloc{idx} = {def};",);
3159 uwriteln!(
3162 self.src.js_init,
3163 r#"
3164 try {{
3165 realloc{idx}Async = WebAssembly.promising({def});
3166 }} catch(err) {{
3167 realloc{idx}Async = {def};
3168 }}
3169 "#
3170 );
3171 }
3172
3173 GlobalInitializer::ExtractPostReturn(p) => {
3174 let def = self.core_def(&p.def);
3175 let idx = p.index.as_u32();
3176 uwriteln!(self.src.js, "let postReturn{idx};");
3177 uwriteln!(self.src.js, "let postReturn{idx}Async;");
3178 uwriteln!(self.src.js_init, "postReturn{idx} = {def};");
3179 uwriteln!(
3182 self.src.js_init,
3183 r#"
3184 try {{
3185 postReturn{idx}Async = WebAssembly.promising({def});
3186 }} catch(err) {{
3187 postReturn{idx}Async = {def};
3188 }}
3189 "#
3190 );
3191 }
3192
3193 GlobalInitializer::Resource(_) => {}
3194
3195 GlobalInitializer::ExtractTable(_) => {}
3196 }
3197 }
3198
3199 fn instantiate_static_module(
3200 &mut self,
3201 module_idx: StaticModuleIndex,
3202 args: &[CoreDef],
3203 instance: Option<RuntimeComponentInstanceIndex>,
3204 ) {
3205 let mut import_obj = BTreeMap::new();
3210 for (module, name, arg) in self.modules[module_idx].imports(args) {
3211 let def = self.augmented_import_def(&arg);
3212 let dst = import_obj.entry(module).or_insert(BTreeMap::new());
3213 let prev = dst.insert(name, def);
3214 assert!(
3215 prev.is_none(),
3216 "unsupported duplicate import of `{module}::{name}`"
3217 );
3218 assert!(prev.is_none());
3219 }
3220
3221 if self.bindgen.opts.asmjs {
3222 let component_instance_idx = instance
3223 .expect("missing runtime component index during static module instantiation")
3224 .as_u32();
3225
3226 self.add_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
3227 self.add_intrinsic(Intrinsic::GetGlobalCurrentTaskMetaFn);
3228 let current_task_get_fn =
3229 Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
3230 let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
3231
3232 let dst = import_obj.entry("env").or_insert(BTreeMap::new());
3233 let prev = dst.insert(
3234 "setTempRet0",
3235 format!(
3236 "(x) => {{
3237 const {{ taskID }} = {get_global_current_task_meta_fn}({component_instance_idx});
3238
3239 const taskMeta = {current_task_get_fn}({component_instance_idx}, taskID);
3240 if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}
3241
3242 const task = taskMeta.task;
3243 if (!task) {{ throw new Error('invalid/missing async task'); }}
3244
3245 task.tmpRetI64HighBits = x|0;
3246 }}"
3247 ),
3248 );
3249 assert!(
3250 prev.is_none(),
3251 "unsupported duplicate import of `env::setTempRet0`"
3252 );
3253 assert!(prev.is_none());
3254 }
3255
3256 let mut imports = String::new();
3258 if !import_obj.is_empty() {
3259 imports.push_str(", {\n");
3260 for (module, names) in import_obj {
3261 imports.push_str(&maybe_quote_id(module));
3262 imports.push_str(": {\n");
3263 for (name, val) in names {
3264 imports.push_str(&maybe_quote_id(name));
3265 uwriteln!(imports, ": {val},");
3266 }
3267 imports.push_str("},\n");
3268 }
3269 imports.push('}');
3270 }
3271
3272 let i = self.instances.push(module_idx);
3273 let iu32 = i.as_u32();
3274 let instantiate = self.bindgen.intrinsic(Intrinsic::InstantiateCore);
3275 uwriteln!(self.src.js, "let exports{iu32};");
3276
3277 match self.bindgen.opts.instantiation_mode {
3278 Some(InstantiationMode::Async) | None => {
3279 uwriteln!(
3280 self.src.js_init,
3281 "({{ exports: exports{iu32} }} = yield {instantiate}(yield module{}{imports}));",
3282 module_idx.as_u32(),
3283 )
3284 }
3285
3286 Some(InstantiationMode::Sync) => {
3287 uwriteln!(
3288 self.src.js_init,
3289 "({{ exports: exports{iu32} }} = {instantiate}(module{}{imports}));",
3290 module_idx.as_u32(),
3291 );
3292 }
3293 }
3294 }
3295
3296 fn create_resource_fn_map(
3304 &mut self,
3305 func: &Function,
3306 ty_func_idx: TypeFuncIndex,
3307 resource_map: &mut ResourceMap,
3308 ) {
3309 let params_ty = &self.types[self.types[ty_func_idx].params];
3311 for (p, iface_ty) in func.params.iter().zip(params_ty.types.iter()) {
3312 if let Type::Id(id) = p.ty {
3313 self.connect_resource_types(id, iface_ty, resource_map);
3314 }
3315 }
3316 let results_ty = &self.types[self.types[ty_func_idx].results];
3318 if let (Some(Type::Id(id)), Some(iface_ty)) = (func.result, results_ty.types.first()) {
3319 self.connect_resource_types(id, iface_ty, resource_map);
3320 }
3321 }
3322
3323 fn resource_name(
3324 resolve: &Resolve,
3325 local_names: &'a mut LocalNames,
3326 resource: TypeId,
3327 resource_map: &BTreeMap<TypeId, ResourceIndex>,
3328 ) -> &'a str {
3329 let resource = crate::dealias(resolve, resource);
3330 local_names
3331 .get_or_create(
3332 resource_map[&resource],
3333 &resolve.types[resource]
3334 .name
3335 .as_ref()
3336 .unwrap()
3337 .to_upper_camel_case(),
3338 )
3339 .0
3340 }
3341
3342 fn imported_resource_name(&mut self, import_index: ImportIndex, resource: TypeId) -> String {
3353 let resolve = self.resolve;
3354 let types = self.types;
3355 let component = self.component;
3356 let resource = crate::dealias(resolve, resource);
3357 let resource_wit_name = resolve.types[resource].name.as_ref().unwrap();
3358 if let (
3359 _,
3360 ComponentExtern {
3361 ty: TypeDef::ComponentInstance(inst),
3362 ..
3363 },
3364 ) = &component.import_types[import_index]
3365 && let Some(ComponentExtern {
3366 ty: TypeDef::Resource(rt_idx),
3367 ..
3368 }) = types[*inst].exports.get(resource_wit_name)
3369 {
3370 let rid = types[*rt_idx].unwrap_concrete_ty();
3371 return self
3372 .bindgen
3373 .local_names
3374 .get_or_create(rid, &resource_wit_name.to_upper_camel_case())
3375 .0
3376 .to_string();
3377 }
3378 Instantiator::resource_name(
3381 resolve,
3382 &mut self.bindgen.local_names,
3383 resource,
3384 &self.imports_resource_types,
3385 )
3386 .to_string()
3387 }
3388
3389 fn find_import_providing_resource(
3401 &self,
3402 resource_idx: ResourceIndex,
3403 ) -> Option<(&'a str, bool)> {
3404 let component = self.component;
3405 let types = self.types;
3406 for (_, (imp_name, extern_)) in component.import_types.iter() {
3407 match &extern_.ty {
3408 TypeDef::ComponentInstance(inst) => {
3409 for (_, export) in types[*inst].exports.iter() {
3410 if let TypeDef::Resource(rt) = &export.ty
3411 && types[*rt].unwrap_concrete_ty() == resource_idx
3412 {
3413 return Some((imp_name.as_str(), true));
3414 }
3415 }
3416 }
3417 TypeDef::Resource(rt) if types[*rt].unwrap_concrete_ty() == resource_idx => {
3418 return Some((imp_name.as_str(), false));
3419 }
3420 _ => {}
3421 }
3422 }
3423 None
3424 }
3425
3426 fn lower_import(&mut self, index: LoweredIndex, import: RuntimeImportIndex) {
3427 let (options, trampoline, func_ty) = self.lowering_options[index];
3428
3429 let (import_index, path) = &self.component.imports[import];
3431 let (import_name, _) = &self.component.import_types[*import_index];
3432 let world_key = &self.imports[import_name];
3433
3434 let (func, func_name, iface_name) =
3436 match &self.resolve.worlds[self.world].imports[world_key] {
3437 WorldItem::Function(func) => {
3438 assert_eq!(path.len(), 0);
3439 (func, import_name, None)
3440 }
3441 WorldItem::Interface { id, .. } => {
3442 assert_eq!(path.len(), 1);
3443 let iface = &self.resolve.interfaces[*id];
3444 let func = &iface.functions[&path[0]];
3445 (
3446 func,
3447 &path[0],
3448 Some(iface.name.as_deref().unwrap_or_else(|| import_name)),
3449 )
3450 }
3451 WorldItem::Type { .. } => unreachable!("unexpected imported world item type"),
3452 };
3453
3454 let is_async = is_async_fn(func, options);
3455
3456 if options.async_ {
3457 assert!(
3458 options.post_return.is_none(),
3459 "async function {func_name} (import {import_name}) can't have post return",
3460 );
3461 }
3462
3463 let requires_async_porcelain = requires_async_porcelain(
3465 FunctionIdentifier::Fn(func),
3466 import_name,
3467 &self.async_imports,
3468 );
3469
3470 let implements = self.resolve.implements_value(
3475 world_key,
3476 &self.resolve.worlds[self.world].imports[world_key],
3477 );
3478
3479 let (import_specifier, maybe_iface_member) = map_import_with_implements(
3481 &self.bindgen.opts.map,
3482 if iface_name.is_some() {
3483 import_name
3484 } else {
3485 match func.kind {
3486 FunctionKind::Method(_) => {
3487 let stripped = import_name.strip_prefix("[method]").unwrap();
3488 &stripped[0..stripped.find(".").unwrap()]
3489 }
3490 FunctionKind::AsyncMethod(_) => {
3491 let stripped = import_name.strip_prefix("[async method]").unwrap();
3492 &stripped[0..stripped.find(".").unwrap()]
3493 }
3494 FunctionKind::Static(_) => {
3495 let stripped = import_name.strip_prefix("[static]").unwrap();
3496 &stripped[0..stripped.find(".").unwrap()]
3497 }
3498 FunctionKind::AsyncStatic(_) => {
3499 let stripped = import_name.strip_prefix("[async static]").unwrap();
3500 &stripped[0..stripped.find(".").unwrap()]
3501 }
3502 FunctionKind::Constructor(_) => {
3503 import_name.strip_prefix("[constructor]").unwrap()
3504 }
3505 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => import_name,
3506 }
3507 },
3508 implements.as_deref(),
3509 );
3510
3511 let mut import_resource_map = ResourceMap::new();
3513
3514 self.create_resource_fn_map(func, func_ty, &mut import_resource_map);
3515
3516 let (callee_name, call_type) = match func.kind {
3517 FunctionKind::Freestanding => (
3518 self.bindgen
3519 .local_names
3520 .get_or_create(
3521 format!(
3522 "import:{import}-{maybe_iface_member}-{func_name}",
3523 import = import_specifier,
3524 maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
3525 func_name = func.name
3526 ),
3527 &func.name,
3528 )
3529 .0
3530 .to_string(),
3531 CallType::Standard,
3532 ),
3533
3534 FunctionKind::AsyncFreestanding => (
3535 self.bindgen
3536 .local_names
3537 .get_or_create(
3538 format!(
3539 "import:async-{import}-{maybe_iface_member}-{func_name}",
3540 import = import_specifier,
3541 maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
3542 func_name = func.name
3543 ),
3544 &func.name,
3545 )
3546 .0
3547 .to_string(),
3548 CallType::AsyncStandard,
3549 ),
3550
3551 FunctionKind::Method(_) => (
3552 func.item_name().to_lower_camel_case(),
3553 CallType::CalleeResourceDispatch,
3554 ),
3555
3556 FunctionKind::AsyncMethod(_) => (
3557 func.item_name().to_lower_camel_case(),
3558 CallType::AsyncCalleeResourceDispatch,
3559 ),
3560
3561 FunctionKind::Static(resource_id) => (
3562 format!(
3563 "{}.{}",
3564 self.imported_resource_name(*import_index, resource_id),
3565 func.item_name().to_lower_camel_case()
3566 ),
3567 CallType::Standard,
3568 ),
3569
3570 FunctionKind::AsyncStatic(resource_id) => (
3571 format!(
3572 "{}.{}",
3573 self.imported_resource_name(*import_index, resource_id),
3574 func.item_name().to_lower_camel_case()
3575 ),
3576 CallType::AsyncStandard,
3577 ),
3578
3579 FunctionKind::Constructor(resource_id) => (
3580 format!(
3581 "new {}",
3582 self.imported_resource_name(*import_index, resource_id)
3583 ),
3584 CallType::Standard,
3585 ),
3586 };
3587
3588 let abi = if options.async_ {
3594 AbiVariant::GuestImportAsync
3595 } else {
3596 AbiVariant::GuestImport
3597 };
3598
3599 let core_ty = self.types[options.core_type].unwrap_func();
3604 let wasm_signature = self.resolve.wasm_signature(abi, func);
3605 assert_eq!(wasm_signature.params.len(), core_ty.params().len());
3606 assert_eq!(wasm_signature.results.len(), core_ty.results().len());
3607 let nparams = core_ty.params().len();
3608
3609 let trampoline_idx = trampoline.as_u32();
3611 match self.bindgen.opts.import_bindings {
3612 None | Some(BindingsMode::Js) | Some(BindingsMode::Hybrid) => {
3613 if is_async | requires_async_porcelain {
3615 uwrite!(
3620 self.src.js,
3621 "\nconst _trampoline{trampoline_idx} = async function"
3622 );
3623 } else {
3624 uwrite!(
3625 self.src.js,
3626 "\nconst _trampoline{trampoline_idx} = function"
3627 );
3628 }
3629
3630 let iface_name = if import_name.is_empty() {
3631 None
3632 } else {
3633 Some(import_name.to_string())
3634 };
3635
3636 self.bindgen(JsFunctionBindgenArgs {
3638 nparams,
3639 call_type,
3640 iface_name: iface_name.as_deref(),
3641 callee: &callee_name,
3642 opts: options,
3643 func,
3644 resource_map: &import_resource_map,
3645 abi,
3646 requires_async_porcelain,
3647 is_async,
3648 wrap_async_future_result: false,
3649 for_import: true,
3650 });
3651 uwriteln!(self.src.js, "");
3652
3653 uwriteln!(
3654 self.src.js,
3655 "_trampoline{trampoline_idx}.fnName = '{}#{callee_name}';",
3656 iface_name.unwrap_or_default(),
3657 );
3658
3659 if requires_async_porcelain {
3661 uwriteln!(
3662 self.src.js,
3663 "_trampoline{trampoline_idx}.manuallyAsync = true;"
3664 );
3665 }
3666 }
3667
3668 Some(BindingsMode::Optimized) | Some(BindingsMode::DirectOptimized) => {
3669 uwriteln!(self.src.js, "let trampoline{trampoline_idx};");
3670 }
3671 };
3672
3673 if !matches!(
3678 self.bindgen.opts.import_bindings,
3679 None | Some(BindingsMode::Js)
3680 ) {
3681 let (memory, realloc) =
3682 if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
3683 memory,
3684 realloc,
3685 }) = options.data_model
3686 {
3687 (
3688 memory.map(|idx| format!(" memory: memory{},", idx.as_u32())),
3689 realloc.map(|idx| format!(" realloc: realloc{},", idx.as_u32())),
3690 )
3691 } else {
3692 (None, None)
3693 };
3694 let memory = memory.unwrap_or_default();
3695 let realloc = realloc.unwrap_or_default();
3696
3697 let post_return = options
3698 .post_return
3699 .map(|idx| format!(" postReturn: postReturn{},", idx.as_u32()))
3700 .unwrap_or("".into());
3701 let string_encoding = match options.string_encoding {
3702 wasmtime_environ::component::StringEncoding::Utf8 => "",
3703 wasmtime_environ::component::StringEncoding::Utf16 => " stringEncoding: 'utf16',",
3704 wasmtime_environ::component::StringEncoding::CompactUtf16 => {
3705 " stringEncoding: 'compact-utf16',"
3706 }
3707 };
3708
3709 let callee_name = match func.kind {
3710 FunctionKind::Constructor(_) => callee_name[4..].to_string(),
3711
3712 FunctionKind::Static(_)
3713 | FunctionKind::AsyncStatic(_)
3714 | FunctionKind::Freestanding
3715 | FunctionKind::AsyncFreestanding => callee_name.to_string(),
3716
3717 FunctionKind::Method(resource_id) | FunctionKind::AsyncMethod(resource_id) => {
3718 format!(
3719 "{}.prototype.{callee_name}",
3720 self.imported_resource_name(*import_index, resource_id)
3721 )
3722 }
3723 };
3724
3725 self.resource_imports.extend(import_resource_map.clone());
3727
3728 let resource_tables = {
3729 let mut resource_table_ids: Vec<TypeResourceTableIndex> = Vec::new();
3730
3731 for (_, data) in import_resource_map {
3732 let ResourceTable {
3733 data: ResourceData::Host { tid, .. },
3734 ..
3735 } = &data
3736 else {
3737 unreachable!("unexpected non-host resource table");
3738 };
3739 resource_table_ids.push(*tid);
3740 }
3741
3742 if resource_table_ids.is_empty() {
3743 "".to_string()
3744 } else {
3745 format!(
3746 " resourceTables: [{}],",
3747 resource_table_ids
3748 .iter()
3749 .map(|x| format!("handleTable{}", x.as_u32()))
3750 .collect::<Vec<String>>()
3751 .join(", ")
3752 )
3753 }
3754 };
3755
3756 match self.bindgen.opts.import_bindings {
3758 Some(BindingsMode::Hybrid) => {
3759 let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
3760 uwriteln!(self.src.js_init, "if ({callee_name}[{symbol_cabi_lower}]) {{
3761 trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});
3762 }}", trampoline.as_u32());
3763 }
3764 Some(BindingsMode::Optimized) => {
3765 let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
3766 if !self.bindgen.opts.valid_lifting_optimization {
3767 uwriteln!(self.src.js_init, "if (!{callee_name}[{symbol_cabi_lower}]) {{
3768 throw new TypeError('import for \"{import_name}\" does not define a Symbol.for(\"cabiLower\") optimized binding');
3769 }}");
3770 }
3771 uwriteln!(
3772 self.src.js_init,
3773 "trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});",
3774 trampoline.as_u32()
3775 );
3776 }
3777 Some(BindingsMode::DirectOptimized) => {
3778 uwriteln!(
3779 self.src.js_init,
3780 "trampoline{} = {callee_name}({{{memory}{realloc}{post_return}{string_encoding}}});",
3781 trampoline.as_u32()
3782 );
3783 }
3784 None | Some(BindingsMode::Js) => unreachable!("invalid bindings mode"),
3785 };
3786 }
3787
3788 let (import_name, binding_name) = match func.kind {
3790 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
3791 (func_name.to_lower_camel_case(), callee_name)
3792 }
3793
3794 FunctionKind::Method(tid)
3795 | FunctionKind::AsyncMethod(tid)
3796 | FunctionKind::Static(tid)
3797 | FunctionKind::AsyncStatic(tid)
3798 | FunctionKind::Constructor(tid) => {
3799 let ty = &self.resolve.types[tid];
3800 let class_name = ty.name.as_ref().unwrap().to_upper_camel_case();
3801 let resource_name = self.imported_resource_name(*import_index, tid);
3802 (class_name, resource_name)
3803 }
3804 };
3805
3806 self.ensure_import(
3807 import_specifier,
3808 iface_name,
3809 maybe_iface_member.as_deref(),
3810 if iface_name.is_some() {
3811 Some(import_name.to_string())
3812 } else {
3813 None
3814 },
3815 binding_name,
3816 );
3817 }
3818
3819 fn ensure_import(
3830 &mut self,
3831 import_specifier: String,
3832 iface_name: Option<&str>,
3833 iface_member: Option<&str>,
3834 import_binding: Option<String>,
3835 local_name: String,
3836 ) {
3837 if import_specifier.starts_with("webidl:") {
3838 self.bindgen
3839 .intrinsic(Intrinsic::WebIdl(WebIdlIntrinsic::GlobalThisIdlProxy));
3840 }
3841
3842 let mut import_path = Vec::with_capacity(2);
3844 import_path.push(import_specifier);
3845 if let Some(_iface_name) = iface_name {
3846 if let Some(iface_member) = iface_member {
3849 import_path.push(iface_member.to_lower_camel_case());
3850 }
3851 import_path.push(import_binding.clone().unwrap());
3852 } else if let Some(iface_member) = iface_member {
3853 import_path.push(iface_member.into());
3854 } else if let Some(import_binding) = &import_binding {
3855 import_path.push(import_binding.into());
3856 }
3857
3858 self.bindgen
3860 .esm_bindgen
3861 .add_import_binding(&import_path, local_name);
3862 }
3863
3864 fn connect_p3_resources(
3873 &mut self,
3874 id: &TypeId,
3875 maybe_elem_ty: &Option<Type>,
3876 iface_ty: &InterfaceType,
3877 resource_map: &mut ResourceMap,
3878 ) {
3879 let remote_resource = match iface_ty {
3880 InterfaceType::Future(table_idx) => {
3881 let future_table_ty = &self.types[*table_idx];
3882 let future_ty = &self.types[future_table_ty.ty];
3883
3884 let mut future_nesting_level = 0;
3886 let mut payload_ty = future_ty.payload;
3887 while let Some(InterfaceType::Future(inner_ty)) = payload_ty {
3888 future_nesting_level += 1;
3889 payload_ty = self.types[self.types[inner_ty].ty].payload;
3890 }
3891
3892 ResourceTable {
3893 imported: true,
3894 data: ResourceData::Guest {
3895 resource_name: "Future".into(),
3896 prefix: Some(format!("${}", table_idx.as_u32())),
3897 extra: Some(ResourceExtraData::Future {
3898 table_idx: *table_idx,
3899 nesting_level: future_nesting_level,
3900 elem_ty: maybe_elem_ty.map(|ty| {
3901 let table_ty = &self.types[*table_idx];
3902 let future_ty_idx = table_ty.ty;
3903 let future_ty = &self.types[future_ty_idx];
3904 let iface_ty = future_ty.payload.expect(
3905 "missing future payload despite elem type being present",
3906 );
3907 let abi = self.types.canonical_abi(&iface_ty);
3908 PayloadTypeMetadata {
3909 ty,
3910 iface_ty,
3911
3912 lift_js_expr: gen_flat_lift_fn_js_expr(
3919 self,
3920 &iface_ty,
3921 &Some(resource_map),
3922 ),
3923 lower_js_expr: gen_flat_lower_fn_js_expr(
3924 self,
3925 &iface_ty,
3926 &Some(resource_map),
3927 ),
3928 size32: abi.size32,
3929 align32: abi.align32,
3930 flat_count: abi.flat_count,
3931 }
3932 }),
3933 }),
3934 },
3935 }
3936 }
3937 InterfaceType::Stream(table_idx) => ResourceTable {
3938 imported: true,
3939 data: ResourceData::Guest {
3940 resource_name: "Stream".into(),
3941 prefix: Some(format!("${}", table_idx.as_u32())),
3942 extra: Some(ResourceExtraData::Stream {
3943 table_idx: *table_idx,
3944 elem_ty: maybe_elem_ty.map(|ty| {
3945 let table_ty = &self.types[*table_idx];
3946 let stream_ty_idx = table_ty.ty;
3947 let stream_ty = &self.types[stream_ty_idx];
3948 let iface_ty = stream_ty
3949 .payload
3950 .expect("missing payload despite elem type being present");
3951 let abi = self.types.canonical_abi(&iface_ty);
3952 PayloadTypeMetadata {
3953 ty,
3954 iface_ty,
3955 lift_js_expr: gen_flat_lift_fn_js_expr(
3956 self,
3957 &iface_ty,
3958 &Some(resource_map),
3959 ),
3960 lower_js_expr: gen_flat_lower_fn_js_expr(
3961 self,
3962 &iface_ty,
3963 &Some(resource_map),
3964 ),
3965 size32: abi.size32,
3966 align32: abi.align32,
3967 flat_count: abi.flat_count,
3968 }
3969 }),
3970 }),
3971 },
3972 },
3973 InterfaceType::ErrorContext(table_idx) => ResourceTable {
3974 imported: true,
3975 data: ResourceData::Guest {
3976 resource_name: "ErrorContext".into(),
3977 prefix: Some(format!("${}", table_idx.as_u32())),
3978 extra: Some(ResourceExtraData::ErrorContext {
3979 table_idx: *table_idx,
3980 }),
3981 },
3982 },
3983 _ => unreachable!("unexpected interface type [{iface_ty:?}] with no type"),
3984 };
3985
3986 resource_map.insert(*id, remote_resource);
3987 }
3988
3989 fn connect_host_resource(
3998 &mut self,
3999 t: TypeId,
4000 resource_table_ty_idx: TypeResourceTableIndex,
4001 resource_map: &mut ResourceMap,
4002 ) {
4003 self.ensure_resource_table(resource_table_ty_idx);
4004
4005 let resource_table_ty = &self.types[resource_table_ty_idx];
4007 let resource_idx = resource_table_ty.unwrap_concrete_ty();
4008 let imported = self
4009 .component
4010 .defined_resource_index(resource_idx)
4011 .is_none();
4012
4013 let resource_id = crate::dealias(self.resolve, t);
4015 let ty = &self.resolve.types[resource_id];
4016
4017 let mut dtor_str = None;
4020 if let Some(resource_idx) = self.component.defined_resource_index(resource_idx) {
4021 assert!(!imported);
4022 let resource_def = self
4023 .component
4024 .initializers
4025 .iter()
4026 .find_map(|i| match i {
4027 GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
4028 _ => None,
4029 })
4030 .unwrap();
4031
4032 if let Some(dtor) = &resource_def.dtor {
4033 dtor_str = Some(self.core_def(dtor));
4034 }
4035 }
4036
4037 let resource_name = ty.name.as_ref().unwrap().to_upper_camel_case();
4039
4040 let local_name = if imported {
4041 let imported_resource_entry = self.find_import_providing_resource(resource_idx);
4044
4045 let (world_key, iface_name) = match imported_resource_entry {
4046 Some((imp_name, _is_from_instance @ true)) => {
4049 let key = self.imports[imp_name].clone();
4050 let iface_name = match &key {
4051 WorldKey::Name(name) => Some(name.clone()),
4052 WorldKey::Interface(_) => {
4053 match &self.resolve.worlds[self.world].imports[&key] {
4054 WorldItem::Interface { id, .. } => {
4055 self.resolve.interfaces[*id].name.clone()
4056 }
4057 _ => None,
4058 }
4059 }
4060 };
4061 (key, iface_name)
4062 }
4063 Some((imp_name, _is_from_instance @ false)) => {
4065 (self.imports[imp_name].clone(), None)
4066 }
4067 None => match ty.owner {
4071 wit_parser::TypeOwner::World(world) => (
4072 self.resolve.worlds[world]
4073 .imports
4074 .iter()
4075 .find(
4076 |&(_, item)| matches!(item, WorldItem::Type { id, .. } if *id == t),
4077 )
4078 .unwrap()
4079 .0
4080 .clone(),
4081 None,
4082 ),
4083 wit_parser::TypeOwner::Interface(iface) => {
4084 let key = self.resolve.worlds[self.world]
4085 .imports
4086 .iter()
4087 .find(|&(_, item)| match item {
4088 WorldItem::Interface { id, .. } => *id == iface,
4089 _ => false,
4090 })
4091 .map(|(key, _)| key)
4092 .unwrap_or_else(|| {
4093 panic!(
4094 "unable to find world import for interface [{}]",
4095 self.resolve.interfaces[iface]
4096 .name
4097 .as_deref()
4098 .unwrap_or("<unnamed>")
4099 )
4100 });
4101 (
4102 key.clone(),
4103 match key {
4104 WorldKey::Name(name) => Some(name.clone()),
4105 WorldKey::Interface(_) => {
4106 self.resolve.interfaces[iface].name.clone()
4107 }
4108 },
4109 )
4110 }
4111 wit_parser::TypeOwner::None => unimplemented!(),
4112 },
4113 };
4114 let iface_name = iface_name.as_deref();
4115
4116 let import_name = self.resolve.name_world_key(&world_key);
4117 let implements = self.resolve.worlds[self.world]
4118 .imports
4119 .get(&world_key)
4120 .and_then(|item| self.resolve.implements_value(&world_key, item));
4121 let (local_name, _) = self
4122 .bindgen
4123 .local_names
4124 .get_or_create(resource_idx, &resource_name);
4125
4126 let local_name_str = local_name.to_string();
4127
4128 let (import_specifier, maybe_iface_member) = map_import_with_implements(
4132 &self.bindgen.opts.map,
4133 &import_name,
4134 implements.as_deref(),
4135 );
4136
4137 self.ensure_import(
4139 import_specifier,
4140 iface_name,
4141 maybe_iface_member.as_deref(),
4142 iface_name.map(|_| resource_name),
4143 local_name_str.to_string(),
4144 );
4145 local_name_str
4146 } else {
4147 let (local_name, _) = self
4148 .bindgen
4149 .local_names
4150 .get_or_create(resource_idx, &resource_name);
4151 local_name.to_string()
4152 };
4153
4154 let entry = ResourceTable {
4156 imported,
4157 data: ResourceData::Host {
4158 tid: resource_table_ty_idx,
4159 rid: resource_idx,
4160 component_idx: resource_table_ty.unwrap_concrete_instance(),
4161 needs_task_context: self
4162 .context_components
4163 .borrow()
4164 .contains(&resource_table_ty.unwrap_concrete_instance()),
4165 local_name,
4166 dtor_name: dtor_str,
4167 },
4168 };
4169
4170 if let Some(existing) = resource_map.get(&resource_id) {
4173 if *existing != entry {
4179 assert!(
4180 imported && existing.imported,
4181 "conflicting resource tables for non-imported resource"
4182 );
4183 }
4184 return;
4185 }
4186
4187 resource_map.insert(resource_id, entry);
4189 }
4190
4191 fn connect_resource_types(
4204 &mut self,
4205 id: TypeId,
4206 iface_ty: &InterfaceType,
4207 resource_map: &mut ResourceMap,
4208 ) {
4209 let kind = &self.resolve.types[id].kind;
4210 match (kind, iface_ty) {
4211 (TypeDefKind::Flags(_), InterfaceType::Flags(_))
4213 | (TypeDefKind::Enum(_), InterfaceType::Enum(_)) => {}
4214
4215 (TypeDefKind::Record(t1), InterfaceType::Record(t2)) => {
4217 let t2 = &self.types[*t2];
4218 for (f1, f2) in t1.fields.iter().zip(t2.fields.iter()) {
4219 if let Type::Id(id) = f1.ty {
4220 self.connect_resource_types(id, &f2.ty, resource_map);
4221 }
4222 }
4223 }
4224
4225 (
4227 TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
4228 InterfaceType::Own(t2) | InterfaceType::Borrow(t2),
4229 ) => {
4230 self.connect_host_resource(*t1, *t2, resource_map);
4231 }
4232
4233 (TypeDefKind::Tuple(t1), InterfaceType::Tuple(t2)) => {
4235 let t2 = &self.types[*t2];
4236 for (f1, f2) in t1.types.iter().zip(t2.types.iter()) {
4237 if let Type::Id(id) = f1 {
4238 self.connect_resource_types(*id, f2, resource_map);
4239 }
4240 }
4241 }
4242
4243 (TypeDefKind::Variant(t1), InterfaceType::Variant(t2)) => {
4245 let t2 = &self.types[*t2];
4246 for (f1, f2) in t1.cases.iter().zip(t2.cases.iter()) {
4247 if let Some(Type::Id(id)) = &f1.ty {
4248 self.connect_resource_types(*id, f2.1.as_ref().unwrap(), resource_map);
4249 }
4250 }
4251 }
4252
4253 (TypeDefKind::Option(t1), InterfaceType::Option(t2)) => {
4255 let t2 = &self.types[*t2];
4256 if let Type::Id(id) = t1 {
4257 self.connect_resource_types(*id, &t2.ty, resource_map);
4258 }
4259 }
4260
4261 (TypeDefKind::Result(t1), InterfaceType::Result(t2)) => {
4263 let t2 = &self.types[*t2];
4264 if let Some(Type::Id(id)) = &t1.ok {
4265 self.connect_resource_types(*id, &t2.ok.unwrap(), resource_map);
4266 }
4267 if let Some(Type::Id(id)) = &t1.err {
4268 self.connect_resource_types(*id, &t2.err.unwrap(), resource_map);
4269 }
4270 }
4271
4272 (TypeDefKind::List(t1), InterfaceType::List(t2)) => {
4274 let t2 = &self.types[*t2];
4275 if let Type::Id(id) = t1 {
4276 self.connect_resource_types(*id, &t2.element, resource_map);
4277 }
4278 }
4279
4280 (TypeDefKind::Map(key, value), InterfaceType::Map(map)) => {
4282 let map = &self.types[*map];
4283 if let Type::Id(id) = key {
4284 self.connect_resource_types(*id, &map.key, resource_map);
4285 }
4286 if let Type::Id(id) = value {
4287 self.connect_resource_types(*id, &map.value, resource_map);
4288 }
4289 }
4290
4291 (TypeDefKind::FixedLengthList(t1, _len), InterfaceType::FixedLengthList(t2)) => {
4293 let t2 = &self.types[*t2];
4294 if let Type::Id(id) = t1 {
4295 self.connect_resource_types(*id, &t2.element, resource_map);
4296 }
4297 }
4298
4299 (TypeDefKind::Type(ty), _) => {
4301 if let Type::Id(id) = ty {
4302 self.connect_resource_types(*id, iface_ty, resource_map);
4303 }
4304 }
4305
4306 (TypeDefKind::Future(maybe_elem_ty), container_iface_ty)
4308 | (TypeDefKind::Stream(maybe_elem_ty), container_iface_ty) => {
4309 match maybe_elem_ty {
4310 None => {
4313 self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
4314 }
4315 Some(elem_ty @ Type::Id(elem_ty_id)) => {
4317 let maybe_elem_iface_ty = match container_iface_ty {
4322 InterfaceType::Future(future_table_ty_idx) => {
4323 let future_table_ty = &self.types[*future_table_ty_idx];
4324 let future = &self.types[future_table_ty.ty];
4325 future.payload
4326 }
4327 InterfaceType::Stream(stream_table_ty_idx) => {
4328 let stream_table_ty = &self.types[*stream_table_ty_idx];
4329 let stream = &self.types[stream_table_ty.ty];
4330 stream.payload
4331 }
4332 _ => unreachable!("unexpected iface type"),
4333 };
4334 if let Some(elem_iface_ty) = maybe_elem_iface_ty {
4335 self.connect_resource_types(*elem_ty_id, &elem_iface_ty, resource_map);
4343 }
4344
4345 self.connect_p3_resources(&id, &Some(*elem_ty), iface_ty, resource_map);
4346 }
4347 Some(_) => {
4349 self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
4350 }
4351 }
4352 }
4353
4354 (
4356 TypeDefKind::Result(Result_ { ok, err }),
4357 tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4358 ) => {
4359 if let Some(Type::Id(ok_t)) = ok {
4360 self.connect_resource_types(*ok_t, tk2, resource_map)
4361 }
4362 if let Some(Type::Id(err_t)) = err {
4363 self.connect_resource_types(*err_t, tk2, resource_map)
4364 }
4365 }
4366
4367 (
4369 TypeDefKind::Option(ty),
4370 tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4371 ) => {
4372 if let Type::Id(some_t) = ty {
4373 self.connect_resource_types(*some_t, tk2, resource_map)
4374 }
4375 }
4376
4377 (
4379 TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
4380 tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4381 ) => self.connect_resource_types(*t1, tk2, resource_map),
4382
4383 (TypeDefKind::Resource, InterfaceType::Future(_) | InterfaceType::Stream(_)) => {}
4384
4385 (
4387 TypeDefKind::Variant(variant),
4388 tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4389 ) => {
4390 for f1 in variant.cases.iter() {
4391 if let Some(Type::Id(id)) = &f1.ty {
4392 self.connect_resource_types(*id, tk2, resource_map);
4393 }
4394 }
4395 }
4396
4397 (
4399 TypeDefKind::Record(record),
4400 tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4401 ) => {
4402 for f1 in record.fields.iter() {
4403 if let Type::Id(id) = f1.ty {
4404 self.connect_resource_types(id, tk2, resource_map);
4405 }
4406 }
4407 }
4408
4409 (
4412 TypeDefKind::Enum(_) | TypeDefKind::Flags(_),
4413 InterfaceType::Future(_) | InterfaceType::Stream(_),
4414 ) => {}
4415
4416 (TypeDefKind::Resource, tk2) => {
4417 unreachable!(
4418 "resource types do not need to be connected (in this case, to [{tk2:?}])"
4419 )
4420 }
4421
4422 (TypeDefKind::Unknown, tk2) => {
4423 unreachable!("unknown types cannot be connected (in this case to [{tk2:?}])")
4424 }
4425
4426 (tk1, tk2) => unreachable!("invalid typedef kind combination [{tk1:?}] [{tk2:?}]",),
4427 }
4428 }
4429
4430 fn bindgen(&mut self, args: JsFunctionBindgenArgs) {
4431 let JsFunctionBindgenArgs {
4432 nparams,
4433 call_type,
4434 iface_name,
4435 callee,
4436 opts,
4437 func,
4438 resource_map,
4439 abi,
4440 requires_async_porcelain,
4441 is_async,
4442 wrap_async_future_result,
4443 for_import,
4444 } = args;
4445
4446 let (memory, realloc) =
4447 if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
4448 memory,
4449 realloc,
4450 }) = opts.data_model
4451 {
4452 (
4453 memory.map(|idx| format!("memory{}", idx.as_u32())),
4454 realloc.map(|idx| {
4455 format!(
4456 "realloc{}{}",
4457 idx.as_u32(),
4458 if is_async {
4459 "Async"
4460 } else {
4461 Default::default()
4462 }
4463 )
4464 }),
4465 )
4466 } else {
4467 (None, None)
4468 };
4469
4470 let post_return = opts.post_return.map(|idx| {
4471 format!(
4472 "postReturn{}{}",
4473 idx.as_u32(),
4474 if is_async {
4475 "Async"
4476 } else {
4477 Default::default()
4478 }
4479 )
4480 });
4481
4482 let tracing_prefix = format!(
4483 "[iface=\"{}\", function=\"{}\"]",
4484 iface_name.unwrap_or("<no iface>"),
4485 func.name
4486 );
4487
4488 self.src.js("(");
4492 let mut params = Vec::new();
4493 let mut first = true;
4494 for i in 0..nparams {
4495 if i == 0
4496 && matches!(
4497 call_type,
4498 CallType::FirstArgIsThis | CallType::AsyncFirstArgIsThis
4499 )
4500 {
4501 params.push("this".into());
4502 continue;
4503 }
4504 if !first {
4505 self.src.js(", ");
4506 } else {
4507 first = false;
4508 }
4509 let param = format!("arg{i}");
4510 self.src.js(¶m);
4511 params.push(param);
4512 }
4513 uwriteln!(self.src.js, ") {{");
4514 if wrap_async_future_result {
4515 let future_value = self.bindgen.intrinsic(Intrinsic::AsyncFuture(
4516 AsyncFutureIntrinsic::FutureValueClass,
4517 ));
4518 uwriteln!(
4519 self.src.js,
4520 "return new {future_value}(() => (async () => {{"
4521 );
4522 }
4523
4524 if self.bindgen.opts.tracing {
4526 let event_fields = func
4527 .params
4528 .iter()
4529 .enumerate()
4530 .map(|(i, p)| format!("{}=${{arguments[{i}]}}", p.name))
4531 .collect::<Vec<String>>();
4532 uwriteln!(
4533 self.src.js,
4534 "console.error(`{tracing_prefix} call {}`);",
4535 event_fields.join(", ")
4536 );
4537 }
4538
4539 if self.bindgen.opts.tla_compat
4541 && matches!(abi, AbiVariant::GuestExport)
4542 && self.bindgen.opts.instantiation_mode.is_none()
4543 {
4544 let throw_uninitialized = self.bindgen.intrinsic(Intrinsic::ThrowUninitialized);
4545 uwrite!(
4546 self.src.js,
4547 "\
4548 if (!_initialized) {throw_uninitialized}();
4549 "
4550 );
4551 }
4552
4553 let mut f = FunctionBindgen {
4555 resource_map,
4556 clear_resource_borrows: false,
4557 intrinsics: &mut self.bindgen.all_intrinsics,
4558 valid_lifting_optimization: self.bindgen.opts.valid_lifting_optimization,
4559 flags_as_bigint: self.bindgen.opts.flags_as_bigint,
4560 enum_values_screaming_snake_case: self.bindgen.opts.enum_values_screaming_snake_case,
4561 sizes: &self.sizes,
4562 err: if get_thrown_type(self.resolve, func.result).is_some() {
4563 match abi {
4564 AbiVariant::GuestExport
4565 | AbiVariant::GuestExportAsync
4566 | AbiVariant::GuestExportAsyncStackful => ErrHandling::ThrowResultErr,
4567 AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4568 ErrHandling::ResultCatchHandler
4569 }
4570 }
4571 } else {
4572 ErrHandling::None
4573 },
4574 block_storage: Vec::new(),
4575 blocks: Vec::new(),
4576 callee,
4577 callee_resource_dynamic: matches!(
4578 call_type,
4579 CallType::CalleeResourceDispatch | CallType::AsyncCalleeResourceDispatch
4580 ),
4581 memory: memory.as_ref(),
4582 realloc: realloc.as_ref(),
4583 tmp: 0,
4584 params,
4585 post_return: post_return.as_ref(),
4586 tracing_prefix: &tracing_prefix,
4587 tracing_enabled: self.bindgen.opts.tracing,
4588 no_component_error_wrapping: self.bindgen.opts.no_component_error_wrapping,
4589 encoding: match opts.string_encoding {
4590 wasmtime_environ::component::StringEncoding::Utf8 => StringEncoding::UTF8,
4591 wasmtime_environ::component::StringEncoding::Utf16 => StringEncoding::UTF16,
4592 wasmtime_environ::component::StringEncoding::CompactUtf16 => {
4593 StringEncoding::CompactUTF16
4594 }
4595 },
4596 src: source::Source::default(),
4597 resolve: self.resolve,
4598 requires_async_porcelain,
4599 is_async,
4600 wrap_async_future_result,
4601 iface_name,
4602 asmjs: self.bindgen.opts.asmjs,
4603 component_state: Some(FunctionBindgenComponentState {
4604 component_idx: opts.instance,
4605 realloc_fn_idx: if let CanonicalOptionsDataModel::LinearMemory(
4606 LinearMemoryOptions { realloc, .. },
4607 ) = opts.data_model
4608 {
4609 realloc
4610 } else {
4611 None
4612 },
4613 memory_idx: opts.memory(),
4614 callback_fn_idx: opts.callback,
4615 }),
4616 for_import: Some(for_import),
4617 };
4618
4619 let is_guest_export = matches!(
4620 abi,
4621 AbiVariant::GuestExport
4622 | AbiVariant::GuestExportAsync
4623 | AbiVariant::GuestExportAsyncStackful
4624 );
4625 if is_guest_export {
4626 f.start_wasm_export_task();
4627 f.begin_wasm_export_body();
4628 }
4629
4630 abi::call(
4633 self.resolve,
4634 abi,
4635 match abi {
4636 AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4637 LiftLower::LiftArgsLowerResults
4638 }
4639 AbiVariant::GuestExport
4640 | AbiVariant::GuestExportAsync
4641 | AbiVariant::GuestExportAsyncStackful => LiftLower::LowerArgsLiftResults,
4642 },
4643 func,
4644 &mut f,
4645 is_async,
4646 );
4647
4648 if is_guest_export {
4649 f.end_wasm_export_body();
4650 }
4651
4652 self.src.js(&f.src);
4654 if wrap_async_future_result {
4655 self.src.js("})());");
4656 }
4657
4658 self.src.js("}");
4660 }
4661
4662 fn augmented_import_def(&mut self, def: &core::AugmentedImport<'_>) -> String {
4663 match def {
4664 core::AugmentedImport::CoreDef(def) => self.core_def(def),
4665 core::AugmentedImport::Memory { mem, op } => {
4666 let mem = self.core_def(mem);
4667 match op {
4668 core::AugmentedOp::I32Load => {
4669 format!(
4670 "(ptr, off) => new DataView({mem}.buffer).getInt32(ptr + off, true)"
4671 )
4672 }
4673 core::AugmentedOp::I32Load8U => {
4674 format!(
4675 "(ptr, off) => new DataView({mem}.buffer).getUint8(ptr + off, true)"
4676 )
4677 }
4678 core::AugmentedOp::I32Load8S => {
4679 format!("(ptr, off) => new DataView({mem}.buffer).getInt8(ptr + off, true)")
4680 }
4681 core::AugmentedOp::I32Load16U => {
4682 format!(
4683 "(ptr, off) => new DataView({mem}.buffer).getUint16(ptr + off, true)"
4684 )
4685 }
4686 core::AugmentedOp::I32Load16S => {
4687 format!(
4688 "(ptr, off) => new DataView({mem}.buffer).getInt16(ptr + off, true)"
4689 )
4690 }
4691 core::AugmentedOp::I64Load => {
4692 format!(
4693 "(ptr, off) => new DataView({mem}.buffer).getBigInt64(ptr + off, true)"
4694 )
4695 }
4696 core::AugmentedOp::F32Load => {
4697 format!(
4698 "(ptr, off) => new DataView({mem}.buffer).getFloat32(ptr + off, true)"
4699 )
4700 }
4701 core::AugmentedOp::F64Load => {
4702 format!(
4703 "(ptr, off) => new DataView({mem}.buffer).getFloat64(ptr + off, true)"
4704 )
4705 }
4706 core::AugmentedOp::I32Store8 => {
4707 format!(
4708 "(ptr, val, offset) => {{
4709 new DataView({mem}.buffer).setInt8(ptr + offset, val, true);
4710 }}"
4711 )
4712 }
4713 core::AugmentedOp::I32Store16 => {
4714 format!(
4715 "(ptr, val, offset) => {{
4716 new DataView({mem}.buffer).setInt16(ptr + offset, val, true);
4717 }}"
4718 )
4719 }
4720 core::AugmentedOp::I32Store => {
4721 format!(
4722 "(ptr, val, offset) => {{
4723 new DataView({mem}.buffer).setInt32(ptr + offset, val, true);
4724 }}"
4725 )
4726 }
4727 core::AugmentedOp::I64Store => {
4728 format!(
4729 "(ptr, val, offset) => {{
4730 new DataView({mem}.buffer).setBigInt64(ptr + offset, val, true);
4731 }}"
4732 )
4733 }
4734 core::AugmentedOp::F32Store => {
4735 format!(
4736 "(ptr, val, offset) => {{
4737 new DataView({mem}.buffer).setFloat32(ptr + offset, val, true);
4738 }}"
4739 )
4740 }
4741 core::AugmentedOp::F64Store => {
4742 format!(
4743 "(ptr, val, offset) => {{
4744 new DataView({mem}.buffer).setFloat64(ptr + offset, val, true);
4745 }}"
4746 )
4747 }
4748 core::AugmentedOp::MemorySize => {
4749 format!("ptr => {mem}.buffer.byteLength / 65536")
4750 }
4751 }
4752 }
4753 }
4754 }
4755
4756 fn core_def(&mut self, def: &CoreDef) -> String {
4757 match def {
4758 CoreDef::Export(e) => self.core_export_var_name(e),
4759 CoreDef::TaskMayBlock => self
4760 .bindgen
4761 .intrinsic(AsyncTaskIntrinsic::CurrentTaskMayBlock.into()),
4762 CoreDef::Trampoline(i) => {
4763 let trampoline = &self.translation.trampolines[*i];
4764 let name = format!("trampoline{}", i.as_u32());
4765 let Some(instance) = self.trampoline_may_leave_instance(trampoline) else {
4766 return name;
4767 };
4768
4769 self.used_instance_flags.borrow_mut().insert(instance);
4770 if Self::trampoline_checks_may_leave_internally(trampoline) {
4771 name
4772 } else {
4773 let guard_may_leave_fn = self
4774 .bindgen
4775 .intrinsic(Intrinsic::Component(ComponentIntrinsic::GuardMayLeave));
4776 format!("{guard_may_leave_fn}({}, {name})", instance.as_u32())
4777 }
4778 }
4779 CoreDef::InstanceFlags(i) => {
4780 self.used_instance_flags.borrow_mut().insert(*i);
4782 format!("instanceFlags{}", i.as_u32())
4783 }
4784 CoreDef::UnsafeIntrinsic(ui) => match ui {
4785 wasmtime_environ::component::UnsafeIntrinsic::ContextGetI32_0 => {
4786 let context_get_fn = self
4787 .bindgen
4788 .intrinsic(AsyncTaskIntrinsic::ContextGet.into());
4789 let component_idx = self.init_current_module.expect("missing current module");
4790 self.context_components.borrow_mut().insert(component_idx);
4791 format!(
4792 "{context_get_fn}.bind(null, {{ componentIdx: {}, slot: 0 }})",
4793 component_idx.as_u32(),
4794 )
4795 }
4796 wasmtime_environ::component::UnsafeIntrinsic::ContextSetI32_0 => {
4797 let context_set_fn = self
4798 .bindgen
4799 .intrinsic(AsyncTaskIntrinsic::ContextSet.into());
4800 let component_idx = self.init_current_module.expect("missing current module");
4801 self.context_components.borrow_mut().insert(component_idx);
4802 format!(
4803 "{context_set_fn}.bind(null, {{ componentIdx: {}, slot: 0 }})",
4804 component_idx.as_u32(),
4805 )
4806 }
4807 wasmtime_environ::component::UnsafeIntrinsic::ContextGetI32_1 => {
4808 let context_get_fn = self
4809 .bindgen
4810 .intrinsic(AsyncTaskIntrinsic::ContextGet.into());
4811 let component_idx = self.init_current_module.expect("missing current module");
4812 self.context_components.borrow_mut().insert(component_idx);
4813 format!(
4814 "{context_get_fn}.bind(null, {{ componentIdx: {}, slot: 1 }})",
4815 component_idx.as_u32(),
4816 )
4817 }
4818 wasmtime_environ::component::UnsafeIntrinsic::ContextSetI32_1 => {
4819 let context_set_fn = self
4820 .bindgen
4821 .intrinsic(AsyncTaskIntrinsic::ContextSet.into());
4822 let component_idx = self.init_current_module.expect("missing current module");
4823 self.context_components.borrow_mut().insert(component_idx);
4824 format!(
4825 "{context_set_fn}.bind(null, {{ componentIdx: {}, slot: 1 }})",
4826 component_idx.as_u32(),
4827 )
4828 }
4829
4830 ui => {
4832 let idx = ui.index();
4833 format!("unsafeIntrinsic{idx}")
4834 }
4835 },
4836 }
4837 }
4838
4839 fn core_export_var_name<T>(&self, export: &CoreExport<T>) -> String
4840 where
4841 T: Into<EntityIndex> + Copy,
4842 {
4843 let name = match &export.item {
4844 ExportItem::Index(idx) => {
4845 let module_idx = self
4846 .instances
4847 .get(export.instance)
4848 .expect("unexpectedly missing export instance");
4849 let module = &self
4850 .modules
4851 .get(*module_idx)
4852 .expect("unexpectedly missing module by idx");
4853 let idx = (*idx).into();
4854 module
4855 .exports()
4856 .iter()
4857 .find_map(|(name, i)| if *i == idx { Some(name) } else { None })
4858 .unwrap()
4859 .to_string()
4860 }
4861 ExportItem::Name(s) => s.to_string(),
4862 };
4863 let i = export.instance.as_u32() as usize;
4864 let quoted = maybe_quote_member(&name);
4865 format!("exports{i}{quoted}")
4866 }
4867
4868 fn process_imports(&mut self) {
4870 let mut import_resource_map = ResourceMap::new();
4871 for (_import_name, (import_idx, _import_path)) in self.component.imports.iter() {
4872 let (import_name, import_type_def) = &self.component.import_types[*import_idx];
4873 let import_world_key = &self
4874 .imports
4875 .get(import_name)
4876 .expect("missing import mapping");
4877 let import_world_item = &self
4878 .resolve
4879 .worlds
4880 .get(self.world)
4881 .expect("missing world")
4882 .imports
4883 .get(*import_world_key)
4884 .expect("missing import in world for import");
4885
4886 match import_world_item {
4888 WorldItem::Interface { id: iface_id, .. } => {
4889 let iface = &self.resolve.interfaces[*iface_id];
4890
4891 for (fn_name, iface_fn) in iface.functions.iter() {
4894 match import_type_def {
4895 ComponentExtern {
4896 ty: TypeDef::ComponentInstance(instance_ty),
4897 ..
4898 } => {
4899 if let Some(ComponentExtern {
4900 ty: TypeDef::ComponentFunc(type_func_index),
4901 ..
4902 }) = &self.types[*instance_ty].exports.get(fn_name)
4903 {
4904 self.create_resource_fn_map(
4905 iface_fn,
4906 *type_func_index,
4907 &mut import_resource_map,
4908 );
4909 }
4910 }
4911 ComponentExtern {
4912 ty: TypeDef::ComponentFunc(type_func_idx),
4913 ..
4914 } => {
4915 self.create_resource_fn_map(
4916 iface_fn,
4917 *type_func_idx,
4918 &mut import_resource_map,
4919 );
4920 }
4921 _ => {}
4922 }
4923 }
4924 }
4925
4926 WorldItem::Function(func) => {
4928 let TypeDef::ComponentFunc(func_ty_idx) = &import_type_def.ty else {
4929 unreachable!("invalid fn export");
4930 };
4931 self.create_resource_fn_map(func, *func_ty_idx, &mut import_resource_map);
4932 }
4933 WorldItem::Type { .. } => {}
4935 }
4936 }
4937
4938 self.resource_imports.extend(import_resource_map);
4939 }
4940
4941 fn process_exports(&mut self) {
4943 self.resource_exports.extend(self.resource_imports.clone());
4945
4946 for (export_name, (export_idx, _extern_data)) in self.component.exports.raw_iter() {
4948 let export_name = export_name.as_ref().to_string();
4949 let export = &self.component.export_items[*export_idx];
4950 let world_key = &self.exports[&export_name];
4951 let item = &self.resolve.worlds[self.world].exports[world_key];
4952 let mut export_resource_map = ResourceMap::new();
4953
4954 match export {
4955 Export::LiftedFunction {
4956 func: def,
4957 options,
4958 ty: func_ty,
4959 } => {
4960 let func = match item {
4961 WorldItem::Function(f) => f,
4962 WorldItem::Interface { .. } | WorldItem::Type { .. } => {
4963 unreachable!("unexpectedly non-function lifted function export")
4964 }
4965 };
4966
4967 self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
4968
4969 let local_name = String::from(match func.kind {
4970 FunctionKind::Constructor(resource_id)
4972 | FunctionKind::Method(resource_id)
4973 | FunctionKind::AsyncMethod(resource_id)
4974 | FunctionKind::Static(resource_id)
4975 | FunctionKind::AsyncStatic(resource_id) => Instantiator::resource_name(
4976 self.resolve,
4977 &mut self.bindgen.local_names,
4978 resource_id,
4979 &self.exports_resource_types,
4980 ),
4981 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
4983 self.bindgen.local_names.create_once(&export_name)
4984 }
4985 });
4986
4987 let options = self
4988 .component
4989 .options
4990 .get(*options)
4991 .expect("failed to find options");
4992
4993 self.export_bindgen(
4994 &local_name,
4995 def,
4996 options,
4997 func,
4998 func_ty,
4999 &export_name,
5000 &export_resource_map,
5001 );
5002
5003 let js_binding_name = match func.kind {
5004 FunctionKind::Constructor(ty)
5006 | FunctionKind::Method(ty)
5007 | FunctionKind::AsyncMethod(ty)
5008 | FunctionKind::Static(ty)
5009 | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5010 .name
5011 .as_ref()
5012 .unwrap()
5013 .to_upper_camel_case(),
5014 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5016 export_name.to_lower_camel_case()
5017 }
5018 };
5019
5020 self.bindgen.esm_bindgen.add_export_binding(
5022 None,
5023 local_name,
5024 js_binding_name,
5025 func,
5026 );
5027 }
5028
5029 Export::Instance { exports, .. } => {
5030 let iface_id = match item {
5031 WorldItem::Interface { id, .. } => *id,
5032 WorldItem::Function(_) | WorldItem::Type { .. } => {
5033 unreachable!("unexpectedly non-interface export instance")
5034 }
5035 };
5036
5037 if self.bindgen.opts.flags_as_bigint || self.bindgen.opts.use_namespace_objects
5038 {
5039 let mut namespace_locals = BTreeMap::<TypeId, String>::new();
5040 for (type_name, type_id) in &self.resolve.interfaces[iface_id].types {
5041 let type_id = crate::dealias(self.resolve, *type_id);
5042 let kind = &self.resolve.types[type_id].kind;
5043 let generate = matches!(kind, TypeDefKind::Flags(_))
5044 && self.bindgen.opts.flags_as_bigint
5045 || matches!(kind, TypeDefKind::Enum(_) | TypeDefKind::Variant(_))
5046 && self.bindgen.opts.use_namespace_objects;
5047 if !generate {
5048 continue;
5049 }
5050
5051 let local_name = self
5052 .bindgen
5053 .local_names
5054 .create_once(&type_name.to_upper_camel_case())
5055 .to_string();
5056 if let Some(existing) = namespace_locals.get(&type_id) {
5057 uwriteln!(self.src.js, "const {local_name} = {existing};");
5058 } else {
5059 uwriteln!(self.src.js, "const {local_name} = Object.freeze({{");
5060 match kind {
5061 TypeDefKind::Flags(flags) => {
5062 for (index, flag) in flags.flags.iter().enumerate() {
5063 uwriteln!(
5064 self.src.js,
5065 "{}: 1n << {index}n,",
5066 flag.name.to_upper_camel_case()
5067 );
5068 }
5069 }
5070 TypeDefKind::Enum(enum_) => {
5071 for case in &enum_.cases {
5072 let case_value = crate::enum_case_name(
5073 &case.name,
5074 self.bindgen.opts.enum_values_screaming_snake_case,
5075 );
5076 uwriteln!(
5077 self.src.js,
5078 "{}: '{}',",
5079 case.name.to_upper_camel_case(),
5080 case_value
5081 );
5082 }
5083 }
5084 TypeDefKind::Variant(variant) => {
5085 for case in &variant.cases {
5086 let case_name = case.name.to_upper_camel_case();
5087 if case.ty.is_some() {
5088 uwriteln!(
5089 self.src.js,
5090 "{case_name}: (val) => ({{ tag: '{}', val }}),",
5091 case.name
5092 );
5093 } else {
5094 uwriteln!(
5095 self.src.js,
5096 "{case_name}: () => ({{ tag: '{}' }}),",
5097 case.name
5098 );
5099 }
5100 }
5101 }
5102 _ => unreachable!(),
5103 }
5104 uwriteln!(self.src.js, "}});");
5105 namespace_locals.insert(type_id, local_name.clone());
5106 }
5107 self.bindgen.esm_bindgen.add_export_constant(
5108 &export_name,
5109 local_name,
5110 type_name.to_upper_camel_case(),
5111 );
5112 }
5113 }
5114
5115 for (func_name, (export_idx, _extern_data)) in exports.raw_iter() {
5117 let func_name = func_name.as_ref().to_string();
5118 let export = &self.component.export_items[*export_idx];
5119
5120 let (def, options, func_ty) = match export {
5122 Export::LiftedFunction { func, options, ty } => (func, options, ty),
5123 Export::Type(_) => continue, _ => unreachable!("unexpected non-lifted function export"),
5125 };
5126
5127 let func = &self.resolve.interfaces[iface_id].functions[&func_name];
5128
5129 self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
5130
5131 let local_name = String::from(match func.kind {
5132 FunctionKind::Constructor(resource_id)
5134 | FunctionKind::Method(resource_id)
5135 | FunctionKind::AsyncMethod(resource_id)
5136 | FunctionKind::Static(resource_id)
5137 | FunctionKind::AsyncStatic(resource_id) => {
5138 Instantiator::resource_name(
5139 self.resolve,
5140 &mut self.bindgen.local_names,
5141 resource_id,
5142 &self.exports_resource_types,
5143 )
5144 }
5145 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5147 self.bindgen.local_names.create_once(&func_name)
5148 }
5149 });
5150
5151 let options = self
5152 .component
5153 .options
5154 .get(*options)
5155 .expect("failed to find options");
5156
5157 self.export_bindgen(
5158 &local_name,
5159 def,
5160 options,
5161 func,
5162 func_ty,
5163 &export_name,
5164 &export_resource_map,
5165 );
5166
5167 let export_binding_name = match func.kind {
5169 FunctionKind::Constructor(ty)
5171 | FunctionKind::Method(ty)
5172 | FunctionKind::AsyncMethod(ty)
5173 | FunctionKind::Static(ty)
5174 | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5175 .name
5176 .as_ref()
5177 .unwrap()
5178 .to_upper_camel_case(),
5179 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5181 func_name.to_lower_camel_case()
5182 }
5183 };
5184
5185 self.bindgen.esm_bindgen.add_export_binding(
5187 Some(&export_name),
5188 local_name,
5189 export_binding_name,
5190 func,
5191 );
5192 }
5193 }
5194
5195 Export::Type(_) => {}
5197
5198 Export::ModuleStatic { .. } | Export::ModuleImport { .. } => unimplemented!(),
5200 }
5201
5202 self.resource_exports.extend(export_resource_map);
5204 }
5205
5206 self.bindgen.esm_bindgen.populate_export_aliases();
5207 }
5208
5209 #[allow(clippy::too_many_arguments)]
5210 fn export_bindgen(
5211 &mut self,
5212 local_name: &str,
5213 def: &CoreDef,
5214 options: &CanonicalOptions,
5215 func: &Function,
5216 _func_ty_idx: &TypeFuncIndex,
5217 export_name: &String,
5218 export_resource_map: &ResourceMap,
5219 ) {
5220 let requires_async_porcelain = requires_async_porcelain(
5222 FunctionIdentifier::Fn(func),
5223 export_name,
5224 &self.async_exports,
5225 );
5226 if options.async_ {
5228 assert!(
5229 options.post_return.is_none(),
5230 "async function {local_name} (export {export_name}) can't have post return"
5231 );
5232 }
5233
5234 let is_async = is_async_fn(func, options);
5235
5236 let wrap_async_future_result = (requires_async_porcelain || is_async)
5237 && matches!(
5238 func.result.as_ref(),
5239 Some(Type::Id(id))
5240 if matches!(
5241 self.resolve.types[crate::dealias(self.resolve, *id)].kind,
5242 TypeDefKind::Future(_)
5243 )
5244 );
5245
5246 let maybe_async = if (requires_async_porcelain || is_async) && !wrap_async_future_result {
5247 "async "
5248 } else {
5249 ""
5250 };
5251 let wrapped_function_target = wrap_async_future_result.then(|| match func.kind {
5252 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => local_name.to_string(),
5253 FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => format!(
5254 "{local_name}.prototype.{}",
5255 func.item_name().to_lower_camel_case()
5256 ),
5257 FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => {
5258 format!("{local_name}.{}", func.item_name().to_lower_camel_case())
5259 }
5260 FunctionKind::Constructor(_) => {
5261 unreachable!("constructors cannot return futures")
5262 }
5263 });
5264
5265 let core_export_fn = self.core_def(def);
5267 let callee = match self
5268 .bindgen
5269 .local_names
5270 .get_or_create(&core_export_fn, &core_export_fn)
5271 {
5272 (local_name, true) => local_name.to_string(),
5273 (local_name, false) => {
5274 let local_name = local_name.to_string();
5275 uwriteln!(self.src.js, "let {local_name};");
5276 self.bindgen
5277 .all_core_exported_funcs
5278 .push((core_export_fn.clone(), is_async | requires_async_porcelain));
5282 local_name
5283 }
5284 };
5285
5286 let iface_name = if export_name.is_empty() {
5287 None
5288 } else {
5289 Some(export_name)
5290 };
5291
5292 match func.kind {
5294 FunctionKind::Freestanding => {
5295 uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5296 }
5297 FunctionKind::Method(_) => {
5298 self.ensure_local_resource_class(local_name.to_string());
5299 let method_name = func.item_name().to_lower_camel_case();
5300
5301 uwrite!(
5302 self.src.js,
5303 "\n{local_name}.prototype.{method_name} = {maybe_async}function {}",
5304 if !is_js_reserved_word(&method_name) {
5305 method_name.to_string()
5306 } else {
5307 format!("${method_name}")
5308 }
5309 );
5310 }
5311 FunctionKind::Static(_) => {
5312 self.ensure_local_resource_class(local_name.to_string());
5313 let method_name = func.item_name().to_lower_camel_case();
5314 uwrite!(
5315 self.src.js,
5316 "\n{local_name}.{method_name} = function {}",
5317 if !is_js_reserved_word(&method_name) {
5318 method_name.to_string()
5319 } else {
5320 format!("${method_name}")
5321 }
5322 );
5323 }
5324 FunctionKind::Constructor(_) => {
5325 if self.defined_resource_classes.contains(local_name) {
5326 panic!(
5327 "Internal error: Resource constructor must be defined before other methods and statics"
5328 );
5329 }
5330 uwrite!(
5331 self.src.js,
5332 "
5333 class {local_name} {{
5334 constructor"
5335 );
5336 self.defined_resource_classes.insert(local_name.to_string());
5337 }
5338 FunctionKind::AsyncFreestanding => {
5339 uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5340 }
5341 FunctionKind::AsyncMethod(_) => {
5342 self.ensure_local_resource_class(local_name.to_string());
5343 let method_name = func.item_name().to_lower_camel_case();
5344 let fn_name = if !is_js_reserved_word(&method_name) {
5345 method_name.to_string()
5346 } else {
5347 format!("${method_name}")
5348 };
5349 uwrite!(
5350 self.src.js,
5351 "\n{local_name}.prototype.{method_name} = {maybe_async}function {fn_name}",
5352 );
5353 }
5354 FunctionKind::AsyncStatic(_) => {
5355 self.ensure_local_resource_class(local_name.to_string());
5356 let method_name = func.item_name().to_lower_camel_case();
5357 let fn_name = if !is_js_reserved_word(&method_name) {
5358 method_name.to_string()
5359 } else {
5360 format!("${method_name}")
5361 };
5362 uwrite!(
5363 self.src.js,
5364 "\n{local_name}.{method_name} = {maybe_async}function {fn_name}",
5365 );
5366 }
5367 };
5368
5369 self.bindgen(JsFunctionBindgenArgs {
5371 nparams: func.params.len(),
5372 call_type: match func.kind {
5373 FunctionKind::Method(_) => CallType::FirstArgIsThis,
5374 FunctionKind::AsyncMethod(_) => CallType::AsyncFirstArgIsThis,
5375 FunctionKind::Freestanding
5376 | FunctionKind::Static(_)
5377 | FunctionKind::Constructor(_) => CallType::Standard,
5378 FunctionKind::AsyncFreestanding | FunctionKind::AsyncStatic(_) => {
5379 CallType::AsyncStandard
5380 }
5381 },
5382 iface_name: iface_name.map(|v| v.as_str()),
5383 callee: &callee,
5384 opts: options,
5385 func,
5386 resource_map: export_resource_map,
5387 abi: AbiVariant::GuestExport,
5388 requires_async_porcelain,
5389 is_async,
5390 wrap_async_future_result,
5391 for_import: false,
5392 });
5393 if let Some(target) = wrapped_function_target {
5394 let async_fn_ctor = self.bindgen.intrinsic(Intrinsic::AsyncFunctionCtor);
5395 uwriteln!(
5396 self.src.js,
5397 "\nObject.setPrototypeOf({target}, {async_fn_ctor}.prototype);"
5398 );
5399 }
5400
5401 match func.kind {
5403 FunctionKind::AsyncFreestanding | FunctionKind::Freestanding => self.src.js("\n"),
5404 FunctionKind::AsyncMethod(_)
5405 | FunctionKind::AsyncStatic(_)
5406 | FunctionKind::Method(_)
5407 | FunctionKind::Static(_) => self.src.js(";\n"),
5408 FunctionKind::Constructor(_) => self.src.js("\n}\n"),
5409 }
5410 }
5411}
5412
5413#[derive(Default)]
5414pub struct Source {
5415 pub js: source::Source,
5416 pub js_init: source::Source,
5417}
5418
5419impl Source {
5420 pub fn js(&mut self, s: &str) {
5421 self.js.push_str(s);
5422 }
5423 pub fn js_init(&mut self, s: &str) {
5424 self.js_init.push_str(s);
5425 }
5426}
5427
5428fn semver_compat_key(version_str: &str) -> Option<(String, Version)> {
5439 let version = Version::parse(version_str).ok()?;
5440 if !version.pre.is_empty() {
5441 None
5442 } else if version.major != 0 {
5443 Some((format!("{}", version.major), version))
5444 } else if version.minor != 0 {
5445 Some((format!("0.{}", version.minor), version))
5446 } else {
5447 None
5448 }
5449}
5450
5451fn parse_mapping(mapping: &str) -> (String, Option<String>) {
5452 if mapping.len() > 1
5453 && let Some(hash_idx) = mapping[1..].find('#')
5454 {
5455 return (
5456 mapping[0..hash_idx + 1].to_string(),
5457 Some(mapping[hash_idx + 2..].into()),
5458 );
5459 }
5460 (mapping.into(), None)
5461}
5462
5463fn resolve_wildcard_mapping(key: &str, mapping: &str, impt: &str) -> Option<String> {
5464 let idx = key.find('*')?;
5465 let lhs = &key[..idx];
5466 let rhs = &key[idx + 1..];
5467
5468 if !impt.starts_with(lhs) || !impt.ends_with(rhs) {
5469 return None;
5470 }
5471
5472 let matched_len = impt.len() - lhs.len() - rhs.len();
5473 let matched = &impt[lhs.len()..lhs.len() + matched_len];
5474 Some(mapping.replace('*', matched))
5475}
5476
5477fn map_import_with_implements(
5482 map: &Option<HashMap<String, String>>,
5483 impt: &str,
5484 implements: Option<&str>,
5485) -> (String, Option<String>) {
5486 let (specifier, iface_member) = map_import(map, impt);
5487 if specifier == impt
5488 && iface_member.is_none()
5489 && let Some(target) = implements
5490 {
5491 let (mapped, member) = map_import(map, target);
5492 let target_sans_version = match target.find('@') {
5494 Some(version_idx) => &target[0..version_idx],
5495 None => target,
5496 };
5497 if mapped != target_sans_version || member.is_some() {
5498 return (mapped, member);
5499 }
5500 }
5501 (specifier, iface_member)
5502}
5503
5504fn map_import(map: &Option<HashMap<String, String>>, impt: &str) -> (String, Option<String>) {
5505 let impt_sans_version = match impt.find('@') {
5506 Some(version_idx) => &impt[0..version_idx],
5507 None => impt,
5508 };
5509 if let Some(map) = map.as_ref() {
5510 if let Some(mapping) = map.get(impt) {
5512 return parse_mapping(mapping);
5513 }
5514
5515 if let Some(mapping) = map.get(impt_sans_version) {
5517 return parse_mapping(mapping);
5518 }
5519
5520 for (key, mapping) in map {
5522 if !key.contains('@') {
5523 continue;
5524 }
5525 if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt) {
5526 return parse_mapping(&mapping);
5527 }
5528 }
5529
5530 for (key, mapping) in map {
5532 if key.contains('@') {
5533 continue;
5534 }
5535 if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt_sans_version) {
5536 return parse_mapping(&mapping);
5537 }
5538 }
5539
5540 if let Some(at) = impt.find('@') {
5543 let impt_ver_str = &impt[at + 1..];
5544 if let Some((impt_compat, _)) = semver_compat_key(impt_ver_str) {
5545 let mut best_match: Option<(String, Version)> = None;
5546
5547 for (key, mapping) in map {
5548 let key_at = match key.find('@') {
5549 Some(at) => at,
5550 None => continue,
5551 };
5552 let key_base = &key[..key_at];
5553 let key_ver_str = &key[key_at + 1..];
5554
5555 let (key_compat, key_ver) = match semver_compat_key(key_ver_str) {
5556 Some(k) => k,
5557 None => continue,
5558 };
5559 if impt_compat != key_compat {
5560 continue;
5561 }
5562
5563 let resolved = if let Some(mapping) =
5564 resolve_wildcard_mapping(key_base, mapping, impt_sans_version)
5565 {
5566 Some(mapping)
5567 } else if key_base == impt_sans_version {
5568 Some(mapping.clone())
5569 } else {
5570 None
5571 };
5572
5573 if let Some(resolved_mapping) = resolved {
5574 match &best_match {
5575 Some((_, prev_ver)) if key_ver <= *prev_ver => {}
5576 _ => {
5577 best_match = Some((resolved_mapping, key_ver));
5578 }
5579 }
5580 }
5581 }
5582
5583 if let Some((mapping, _)) = best_match {
5584 return parse_mapping(&mapping);
5585 }
5586 }
5587 }
5588 }
5589 (impt_sans_version.to_string(), None)
5590}
5591
5592pub fn parse_world_key(name: &str) -> Option<(&str, &str, &str)> {
5593 let registry_idx = name.find(':')?;
5594 let ns = &name[0..registry_idx];
5595 match name.rfind('/') {
5596 Some(sep_idx) => {
5597 let end = if let Some(version_idx) = name.rfind('@') {
5598 version_idx
5599 } else {
5600 name.len()
5601 };
5602 Some((
5603 ns,
5604 &name[registry_idx + 1..sep_idx],
5605 &name[sep_idx + 1..end],
5606 ))
5607 }
5608 None => Some((ns, &name[registry_idx + 1..], "")),
5610 }
5611}
5612
5613fn core_file_name(name: &str, idx: u32) -> String {
5614 let i_str = if idx == 0 {
5615 String::from("")
5616 } else {
5617 (idx + 1).to_string()
5618 };
5619 format!("{name}.core{i_str}.wasm")
5620}
5621
5622fn string_encoding_js_literal(val: &wasmtime_environ::component::StringEncoding) -> &'static str {
5624 match val {
5625 wasmtime_environ::component::StringEncoding::Utf8 => "'utf8'",
5626 wasmtime_environ::component::StringEncoding::Utf16 => "'utf16'",
5627 wasmtime_environ::component::StringEncoding::CompactUtf16 => "'compact-utf16'",
5628 }
5629}
5630
5631pub fn gen_flat_lift_fn_list_js_expr(
5640 instantiator: &mut Instantiator,
5641 types: &[InterfaceType],
5642 extra_resource_map: &Option<&mut ResourceMap>,
5643) -> String {
5644 let mut lift_fns: Vec<String> = Vec::with_capacity(types.len());
5645 for ty in types.iter() {
5646 lift_fns.push(gen_flat_lift_fn_js_expr(
5647 instantiator,
5648 ty,
5649 extra_resource_map,
5650 ));
5651 }
5652 format!("[{}]", lift_fns.join(","))
5653}
5654
5655fn flat_count_js_expr(flat_count: &Option<u8>) -> String {
5656 flat_count
5657 .map(|count| count.to_string())
5658 .unwrap_or_else(|| "null".into())
5659}
5660
5661fn join_flat_core_types(a: &'static str, b: &'static str) -> &'static str {
5664 if a == b {
5665 a
5666 } else if (a == "i32" && b == "f32") || (a == "f32" && b == "i32") {
5667 "i32"
5668 } else {
5669 "i64"
5670 }
5671}
5672
5673fn flat_core_types(
5679 component_types: &ComponentTypes,
5680 ty: &InterfaceType,
5681) -> Option<Vec<&'static str>> {
5682 component_types
5683 .canonical_abi(ty)
5684 .flat_count(MAX_FLAT_PARAMS)?;
5685 let mut flat = Vec::new();
5686 push_flat_core_types(component_types, ty, &mut flat);
5687 Some(flat)
5688}
5689
5690fn flat_core_types_variant_payload_join<'a>(
5694 component_types: &ComponentTypes,
5695 cases: impl Iterator<Item = Option<&'a InterfaceType>>,
5696) -> Vec<&'static str> {
5697 let mut joined: Vec<&'static str> = Vec::new();
5698 for maybe_ty in cases {
5699 let Some(ty) = maybe_ty else { continue };
5700 let mut case_flat = Vec::new();
5701 push_flat_core_types(component_types, ty, &mut case_flat);
5702 for (idx, flat_ty) in case_flat.into_iter().enumerate() {
5703 match joined.get_mut(idx) {
5704 Some(existing) => {
5705 *existing = join_flat_core_types(existing, flat_ty);
5706 }
5707 None => joined.push(flat_ty),
5708 }
5709 }
5710 }
5711 joined
5712}
5713
5714fn push_flat_core_types(
5715 component_types: &ComponentTypes,
5716 ty: &InterfaceType,
5717 flat: &mut Vec<&'static str>,
5718) {
5719 match ty {
5720 InterfaceType::Bool
5721 | InterfaceType::S8
5722 | InterfaceType::U8
5723 | InterfaceType::S16
5724 | InterfaceType::U16
5725 | InterfaceType::S32
5726 | InterfaceType::U32
5727 | InterfaceType::Char
5728 | InterfaceType::Flags(_)
5729 | InterfaceType::Enum(_)
5730 | InterfaceType::Own(_)
5731 | InterfaceType::Borrow(_)
5732 | InterfaceType::Future(_)
5733 | InterfaceType::Stream(_)
5734 | InterfaceType::ErrorContext(_) => flat.push("i32"),
5735
5736 InterfaceType::S64 | InterfaceType::U64 => flat.push("i64"),
5737
5738 InterfaceType::Float32 => flat.push("f32"),
5739 InterfaceType::Float64 => flat.push("f64"),
5740
5741 InterfaceType::String | InterfaceType::List(_) | InterfaceType::Map(_) => {
5742 flat.push("i32");
5743 flat.push("i32");
5744 }
5745
5746 InterfaceType::Record(ty_idx) => {
5747 for field in &component_types[*ty_idx].fields {
5748 push_flat_core_types(component_types, &field.ty, flat);
5749 }
5750 }
5751
5752 InterfaceType::Tuple(ty_idx) => {
5753 for ty in &component_types[*ty_idx].types {
5754 push_flat_core_types(component_types, ty, flat);
5755 }
5756 }
5757
5758 InterfaceType::FixedLengthList(ty_idx) => {
5759 let list_ty = &component_types[*ty_idx];
5760 for _ in 0..list_ty.size {
5761 push_flat_core_types(component_types, &list_ty.element, flat);
5762 }
5763 }
5764
5765 InterfaceType::Variant(ty_idx) => {
5766 let variant_ty = &component_types[*ty_idx];
5767 flat.push("i32");
5768 flat.extend(flat_core_types_variant_payload_join(
5769 component_types,
5770 variant_ty.cases.iter().map(|(_, ty)| ty.as_ref()),
5771 ));
5772 }
5773
5774 InterfaceType::Option(ty_idx) => {
5775 let option_ty = &component_types[*ty_idx];
5776 flat.push("i32");
5777 flat.extend(flat_core_types_variant_payload_join(
5778 component_types,
5779 [None, Some(&option_ty.ty)].into_iter(),
5780 ));
5781 }
5782
5783 InterfaceType::Result(ty_idx) => {
5784 let result_ty = &component_types[*ty_idx];
5785 flat.push("i32");
5786 flat.extend(flat_core_types_variant_payload_join(
5787 component_types,
5788 [result_ty.ok.as_ref(), result_ty.err.as_ref()].into_iter(),
5789 ));
5790 }
5791 }
5792}
5793
5794fn flat_core_types_js_expr(flat: &Option<Vec<&'static str>>) -> String {
5796 match flat {
5797 Some(flat) => format!(
5798 "[{}]",
5799 flat.iter()
5800 .map(|t| format!("'{t}'"))
5801 .collect::<Vec<_>>()
5802 .join(",")
5803 ),
5804 None => "null".into(),
5805 }
5806}
5807
5808pub fn gen_flat_lift_fn_js_expr(
5829 instantiator: &mut Instantiator,
5830 ty: &InterfaceType,
5831 extra_resource_map: &Option<&mut ResourceMap>,
5832) -> String {
5833 let component_types = instantiator.types;
5834
5835 match ty {
5836 InterfaceType::Bool => {
5837 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBool));
5838 Intrinsic::Lift(LiftIntrinsic::LiftFlatBool).name().into()
5839 }
5840
5841 InterfaceType::S8 => {
5842 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS8));
5843 Intrinsic::Lift(LiftIntrinsic::LiftFlatS8).name().into()
5844 }
5845
5846 InterfaceType::U8 => {
5847 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU8));
5848 Intrinsic::Lift(LiftIntrinsic::LiftFlatU8).name().into()
5849 }
5850
5851 InterfaceType::S16 => {
5852 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS16));
5853 Intrinsic::Lift(LiftIntrinsic::LiftFlatS16).name().into()
5854 }
5855
5856 InterfaceType::U16 => {
5857 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU16));
5858 Intrinsic::Lift(LiftIntrinsic::LiftFlatU16).name().into()
5859 }
5860
5861 InterfaceType::S32 => {
5862 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS32));
5863 Intrinsic::Lift(LiftIntrinsic::LiftFlatS32).name().into()
5864 }
5865
5866 InterfaceType::U32 => {
5867 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU32));
5868 Intrinsic::Lift(LiftIntrinsic::LiftFlatU32).name().into()
5869 }
5870
5871 InterfaceType::S64 => {
5872 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS64));
5873 Intrinsic::Lift(LiftIntrinsic::LiftFlatS64).name().into()
5874 }
5875
5876 InterfaceType::U64 => {
5877 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU64));
5878 Intrinsic::Lift(LiftIntrinsic::LiftFlatU64).name().into()
5879 }
5880
5881 InterfaceType::Float32 => {
5882 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32));
5883 Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32)
5884 .name()
5885 .into()
5886 }
5887
5888 InterfaceType::Float64 => {
5889 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64));
5890 Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64)
5891 .name()
5892 .into()
5893 }
5894
5895 InterfaceType::Char => {
5896 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatChar));
5897 Intrinsic::Lift(LiftIntrinsic::LiftFlatChar).name().into()
5898 }
5899
5900 InterfaceType::String => {
5901 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny));
5902 Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny)
5903 .name()
5904 .into()
5905 }
5906
5907 InterfaceType::Record(ty_idx) => {
5908 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord));
5909 let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord).name();
5910 let record_ty = &component_types[*ty_idx];
5911 let size32 = record_ty.abi.size32;
5912 let align32 = record_ty.abi.align32;
5913 let mut keys_and_lifts_expr = String::from("[");
5914 for f in &record_ty.fields {
5918 let field_abi = component_types.canonical_abi(&f.ty);
5919 let field_size32 = field_abi.size32;
5920 let field_align32 = field_abi.align32;
5921 keys_and_lifts_expr.push_str(&format!(
5922 "['{}', {}, {}, {}],",
5923 f.name.to_lower_camel_case(),
5924 gen_flat_lift_fn_js_expr(instantiator, &f.ty, extra_resource_map),
5925 field_size32,
5926 field_align32,
5927 ));
5928 }
5929 keys_and_lifts_expr.push(']');
5930 format!(
5931 "{lift_fn}({{ fieldMetas: {keys_and_lifts_expr}, size32: {size32}, align32: {align32} }})"
5932 )
5933 }
5934
5935 InterfaceType::Variant(ty_idx) => {
5936 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant));
5937 let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant).name();
5938 let variant_ty = &component_types[*ty_idx];
5939 let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
5940 let variant_size32 = variant_ty.abi.size32;
5941 let variant_align32 = variant_ty.abi.align32;
5942 let variant_payload_offset32 = variant_ty.info.payload_offset32;
5943 let variant_payload_flat_types = flat_core_types_js_expr(
5944 &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
5945 );
5946
5947 let mut lift_metas_expr = String::from("[");
5948 for (name, maybe_ty) in &variant_ty.cases {
5949 let (lift_fn_js, case_size32, case_align32, case_flat_count, case_flat_types) =
5950 match maybe_ty {
5951 Some(ty) => {
5952 let cabi_info = component_types.canonical_abi(ty);
5953 (
5954 gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map),
5955 cabi_info.size32.to_string(),
5956 cabi_info.align32.to_string(),
5957 cabi_info
5958 .flat_count(MAX_FLAT_PARAMS)
5959 .map(|v| v.to_string())
5960 .unwrap_or_else(|| "null".into()),
5961 flat_core_types_js_expr(&flat_core_types(component_types, ty)),
5962 )
5963 }
5964 None => (
5965 "null".into(),
5966 "0".into(),
5967 "0".into(),
5968 "0".into(),
5969 "[]".into(),
5970 ),
5971 };
5972
5973 lift_metas_expr.push_str(&format!(
5974 "['{name}', {lift_fn_js}, {case_size32}, {case_align32}, {case_flat_count}, {case_flat_types}],",
5975 ));
5976 }
5977 lift_metas_expr.push(']');
5978
5979 format!(
5980 "{lift_fn}({{
5981 caseMetas: {lift_metas_expr},
5982 variantSize32: {variant_size32},
5983 variantAlign32: {variant_align32},
5984 variantPayloadOffset32: {variant_payload_offset32},
5985 variantFlatCount: {variant_flat_count},
5986 variantPayloadFlatTypes: {variant_payload_flat_types},
5987 }} )"
5988 )
5989 }
5990
5991 InterfaceType::List(ty_idx) => {
5992 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
5993 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
5994 let list_ty = &component_types[*ty_idx];
5995 let lift_fn_expr =
5996 gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
5997 let elem_cabi = component_types.canonical_abi(&list_ty.element);
5998 let elem_align32 = elem_cabi.align32;
5999 let elem_size32 = elem_cabi.size32;
6000 let typed_array = js_typed_array_ctor(&list_ty.element).unwrap_or("undefined");
6001 format!(
6002 "{f}({{
6003 elemLiftFn: {lift_fn_expr},
6004 elemAlign32: {elem_align32},
6005 elemSize32: {elem_size32},
6006 typedArray: {typed_array},
6007 }})"
6008 )
6009 }
6010
6011 InterfaceType::FixedLengthList(ty_idx) => {
6012 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
6013 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
6014 let list_ty = &component_types[*ty_idx];
6015 let list_size32 = list_ty.abi.size32;
6016 let list_align32 = list_ty.abi.align32;
6017 let lift_fn_expr =
6018 gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6019 let list_len = list_ty.size;
6020 let elem_cabi = component_types.canonical_abi(&list_ty.element);
6021 let elem_align32 = elem_cabi.align32;
6022 let elem_size32 = elem_cabi.size32;
6023 format!(
6024 "{f}({{
6025 elemLiftFn: {lift_fn_expr},
6026 elemAlign32: {elem_align32},
6027 elemSize32: {elem_size32},
6028 listSize32: {list_size32},
6029 listAlign32: {list_align32},
6030 knownLen: {list_len},
6031 }})"
6032 )
6033 }
6034
6035 InterfaceType::Tuple(ty_idx) => {
6036 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple));
6037 let tuple_ty = &component_types[*ty_idx];
6038 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple).name();
6039 let size_u32 = tuple_ty.abi.size32;
6040 let align_u32 = tuple_ty.abi.align32;
6041
6042 let mut elem_lifts_expr = String::from("[");
6043 for ty in &tuple_ty.types {
6044 let lift_fn_js = gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map);
6045 let elem_abi = component_types.canonical_abi(ty);
6046 let elem_size32 = elem_abi.size32;
6047 let elem_align32 = elem_abi.align32;
6048 elem_lifts_expr
6049 .push_str(&format!("[{lift_fn_js}, {elem_size32}, {elem_align32}],"));
6050 }
6051 elem_lifts_expr.push(']');
6052
6053 format!(
6054 "{f}({{ elemLiftFns: {elem_lifts_expr}, size32: {size_u32}, align32: {align_u32} }})"
6055 )
6056 }
6057
6058 InterfaceType::Flags(ty_idx) => {
6059 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags));
6060 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags).name();
6061 let flags_ty = &component_types[*ty_idx];
6062 let size_u32 = flags_ty.abi.size32;
6063 let align_u32 = flags_ty.abi.align32;
6064 let names_expr = format!(
6065 "[{}]",
6066 flags_ty
6067 .names
6068 .iter()
6069 .map(|s| format!("'{}'", s.to_lower_camel_case()))
6070 .collect::<Vec<_>>()
6071 .join(",")
6072 );
6073 let num_flags = flags_ty.names.len();
6074 let elem_size = if num_flags <= 8 {
6075 1
6076 } else if num_flags <= 16 {
6077 2
6078 } else {
6079 4
6080 };
6081
6082 format!(
6083 "{f}({{ names: {names_expr}, size32: {size_u32}, align32: {align_u32}, intSizeBytes: {elem_size} }})"
6084 )
6085 }
6086
6087 InterfaceType::Enum(ty_idx) => {
6088 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum));
6089 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum).name();
6090 let enum_ty = &component_types[*ty_idx];
6091 let enum_size32 = enum_ty.abi.size32;
6092 let enum_align32 = enum_ty.abi.align32;
6093 let enum_payload_offset32 = enum_ty.info.payload_offset32;
6094 let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
6095
6096 let mut elem_lifts_expr = String::from("[");
6097 for name in &enum_ty.names {
6098 let name = crate::enum_case_name(
6099 name,
6100 instantiator.bindgen.opts.enum_values_screaming_snake_case,
6101 );
6102 elem_lifts_expr.push_str(&format!(
6103 "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
6104 ));
6105 }
6106 elem_lifts_expr.push(']');
6107
6108 format!(
6109 r#"
6110 {f}({{
6111 caseMetas: {elem_lifts_expr},
6112 variantSize32: {enum_size32},
6113 variantAlign32: {enum_align32},
6114 variantPayloadOffset32: {enum_payload_offset32},
6115 variantFlatCount: {enum_flat_count},
6116 }})
6117 "#
6118 )
6119 }
6120
6121 InterfaceType::Option(ty_idx) => {
6122 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOption));
6123 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOption).name();
6124 let option_ty = &component_types[*ty_idx];
6125 let option_payload_offset32 = option_ty.info.payload_offset32;
6126 let option_align32 = option_ty.abi.align32;
6127 let option_size32 = option_ty.abi.size32;
6128 let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
6129 let option_payload_flat_types = flat_core_types_js_expr(
6130 &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6131 );
6132
6133 let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
6134 let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
6135 let some_ty_size32 = some_ty_abi.size32;
6136 let some_ty_align32 = some_ty_abi.align32;
6137 let some_ty_flat_types =
6138 flat_core_types_js_expr(&flat_core_types(component_types, &option_ty.ty));
6139 let some_ty_lift_fn_js =
6140 gen_flat_lift_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
6141
6142 format!(
6143 r#"
6144 {f}({{
6145 caseMetas: [
6146 ['none', null, 0, 0, 0, [] ],
6147 ['some', {some_ty_lift_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}, {some_ty_flat_types} ],
6148 ],
6149 variantSize32: {option_size32},
6150 variantAlign32: {option_align32},
6151 variantPayloadOffset32: {option_payload_offset32},
6152 variantFlatCount: {option_flat_count},
6153 variantPayloadFlatTypes: {option_payload_flat_types},
6154 }})
6155 "#
6156 )
6157 }
6158
6159 InterfaceType::Result(ty_idx) => {
6160 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatResult));
6161 let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatResult).name();
6162 let result_ty = &component_types[*ty_idx];
6163 let result_size32 = result_ty.abi.size32;
6164 let result_align32 = result_ty.abi.align32;
6165 let result_payload_offset32 = result_ty.info.payload_offset32;
6166 let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
6167 let result_payload_flat_types = flat_core_types_js_expr(
6168 &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6169 );
6170
6171 let mut cases_and_lifts_expr = String::from("[");
6172 if let Some(ok_ty) = result_ty.ok {
6173 let ok_ty_abi = component_types.canonical_abi(&ok_ty);
6174 let ok_ty_size32 = ok_ty_abi.size32;
6175 let ok_ty_align32 = ok_ty_abi.align32;
6176 let ok_flat_count = flat_count_js_expr(&ok_ty_abi.flat_count);
6177 let ok_ty_flat_types =
6178 flat_core_types_js_expr(&flat_core_types(component_types, &ok_ty));
6179 let ok_ty_lift_fn =
6180 gen_flat_lift_fn_js_expr(instantiator, &ok_ty, extra_resource_map);
6181 cases_and_lifts_expr.push_str(&format!(
6182 "['ok', {ok_ty_lift_fn}, {ok_ty_size32}, {ok_ty_align32}, {ok_flat_count}, {ok_ty_flat_types}],",
6183 ))
6184 } else {
6185 cases_and_lifts_expr.push_str("['ok', null, 0, 0, 0, []],");
6186 }
6187
6188 if let Some(err_ty) = &result_ty.err {
6189 let err_ty_abi = component_types.canonical_abi(err_ty);
6190 let err_ty_size32 = err_ty_abi.size32;
6191 let err_ty_align32 = err_ty_abi.align32;
6192 let err_ty_flat_count = flat_count_js_expr(&err_ty_abi.flat_count);
6193 let err_ty_flat_types =
6194 flat_core_types_js_expr(&flat_core_types(component_types, err_ty));
6195 let err_ty_lift_fn =
6196 gen_flat_lift_fn_js_expr(instantiator, err_ty, extra_resource_map);
6197 cases_and_lifts_expr.push_str(&format!(
6198 "['err', {err_ty_lift_fn}, {err_ty_size32}, {err_ty_align32}, {err_ty_flat_count}, {err_ty_flat_types}],",
6199 ))
6200 } else {
6201 cases_and_lifts_expr.push_str("['err', null, 0, 0, 0, []],");
6202 }
6203 cases_and_lifts_expr.push(']');
6204
6205 format!(
6206 r#"
6207 {lift_fn}({{
6208 caseMetas: {cases_and_lifts_expr},
6209 variantSize32: {result_size32},
6210 variantAlign32: {result_align32},
6211 variantPayloadOffset32: {result_payload_offset32},
6212 variantFlatCount: {result_flat_count},
6213 variantPayloadFlatTypes: {result_payload_flat_types},
6214 }})
6215 "#
6216 )
6217 }
6218
6219 InterfaceType::Own(ty_idx) => {
6220 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn));
6221 instantiator.add_intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
6222 instantiator.add_intrinsic(Intrinsic::SymbolResourceHandle);
6223 instantiator.add_intrinsic(Intrinsic::SymbolResourceRep);
6224 instantiator.add_intrinsic(Intrinsic::SymbolDispose);
6225 instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
6226 instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
6227 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn).name();
6228 let table_ty = &component_types[*ty_idx];
6229 let resource_component_idx = table_ty.unwrap_concrete_instance();
6230 let component_idx = resource_component_idx.as_u32();
6231 if instantiator
6232 .context_components
6233 .borrow()
6234 .contains(&resource_component_idx)
6235 {
6236 instantiator.add_intrinsic(Intrinsic::Resource(
6237 ResourceIntrinsic::ResourceDestructorCall,
6238 ));
6239 }
6240 let resource_idx = table_ty.unwrap_concrete_ty();
6241
6242 match instantiator.exports_resource_index_types.get(&resource_idx) {
6244 None => format!(
6246 r#"{f}({{
6247 componentIdx: {component_idx},
6248 classNameFn: () => null,
6249 createResourceFn: () => {{ throw new Error('invalid/missing resource type data'); }},
6250 }})
6251 "#,
6252 ),
6253
6254 Some(resource_typedef) => {
6257 let (resource_class_name, create_resource_fn_js) = match (
6259 instantiator.resource_exports.get(resource_typedef),
6260 extra_resource_map
6261 .as_ref()
6262 .and_then(|v| v.get(resource_typedef)),
6263 ) {
6264 (None, None) => (
6266 "null".into(),
6267 "() => {{ throw new Error('missing resource information'); }}".into(),
6268 ),
6269
6270 (Some(ResourceTable { imported, data }), _)
6272 | (_, Some(ResourceTable { imported, data })) => match data {
6273 ResourceData::Guest { .. } => {
6274 unimplemented!(
6275 "owned resources created by guests should must have host-side data"
6276 )
6277 }
6278 ResourceData::Host {
6279 tid,
6280 rid,
6281 component_idx,
6282 needs_task_context,
6283 local_name,
6284 dtor_name,
6285 } => {
6286 let empty_func = JsHelperIntrinsic::EmptyFunc.name();
6287 let symbol_resource_handle = Intrinsic::SymbolResourceHandle.name();
6288 let symbol_dispose = Intrinsic::SymbolDispose.name();
6289 let rsc_table_remove =
6290 ResourceIntrinsic::ResourceTableRemove.name();
6291 let tid = tid.as_u32();
6292 let rsc_flag = ResourceIntrinsic::ResourceTableFlag.name();
6293 let component_idx = component_idx.as_u32();
6294
6295 let create_resource_fn_js = if *imported {
6297 let symbol_resource_rep = Intrinsic::SymbolResourceRep.name();
6298 let rid = rid.as_u32();
6299 format!(
6300 r#"
6301 (handle) => {{
6302 const rep = handleTable{tid}[(handle << 1) + 1] & ~{rsc_flag};
6303 let resourceObj = captureTable{rid}.get(rep);
6304 if (!resourceObj) {{
6305 resourceObj = Object.create({local_name}.prototype);
6306 Object.defineProperty(resourceObj, {symbol_resource_handle}, {{ writable: true, value: handle }});
6307 Object.defineProperty(resourceObj, {symbol_resource_rep}, {{ writable: true, value: rep }});
6308 }} else {{
6309 captureTable{rid}.delete(rep);
6310 }}
6311 {rsc_table_remove}(handleTable{tid}, handle);
6312 return resourceObj;
6313 }}
6314 "#
6315 )
6316 } else {
6317 let dtor_setup_js = dtor_name
6318 .as_ref()
6319 .map(|dtor| {
6320 let dtor_call = if *needs_task_context {
6321 let call_resource_destructor =
6322 ResourceIntrinsic::ResourceDestructorCall.name();
6323 format!(
6324 "{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {dtor}, rep: handleEntry.rep }});"
6325 )
6326 } else {
6327 format!("{dtor}(handleEntry.rep);")
6328 };
6329 format!(
6330 r#"
6331 Object.defineProperty(
6332 resourceObj,
6333 {symbol_dispose},
6334 {{
6335 writable: true,
6336 value: function() {{
6337 finalizationRegistry{tid}.unregister(resourceObj);
6338 const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
6339 resourceObj[{symbol_dispose}] = {empty_func};
6340 resourceObj[{symbol_resource_handle}] = undefined;
6341 {dtor_call}
6342 }}
6343 }}
6344 );
6345 "#
6346 )
6347 })
6348 .unwrap_or_default();
6349
6350 format!(
6351 r#"
6352 (handle) => {{
6353 const resourceObj = Object.create({local_name}.prototype);
6354 Object.defineProperty(resourceObj, {symbol_resource_handle}, {{
6355 writable: true,
6356 value: handle,
6357 }});
6358 finalizationRegistry{tid}.register(resourceObj, handle, resourceObj);
6359 {dtor_setup_js}
6360 return resourceObj;
6361 }}
6362 "#
6363 )
6364 };
6365
6366 (local_name.to_string(), create_resource_fn_js)
6367 }
6368 },
6369 };
6370
6371 format!(
6372 r#"{f}({{
6373 componentIdx: {component_idx},
6374 classNameFn: () => {resource_class_name},
6375 createResourceFn: {create_resource_fn_js},
6376 }})
6377 "#,
6378 )
6379 }
6380 }
6381 }
6382
6383 InterfaceType::Borrow(ty_idx) => {
6384 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow));
6385 let table_idx = ty_idx.as_u32();
6386 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow).name();
6387 format!("{f}.bind(null, {table_idx})")
6388 }
6389
6390 InterfaceType::Future(ty_idx) => {
6391 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture));
6392 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture).name();
6393 let table_idx = ty_idx.as_u32();
6394 let table_ty = &component_types[*ty_idx];
6395 let component_idx = table_ty.instance.as_u32();
6396 format!("{f}({{ futureTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6397 }
6398
6399 InterfaceType::Stream(ty_idx) => {
6400 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStream));
6401 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatStream).name();
6402 let table_idx = ty_idx.as_u32();
6403 let table_ty = &component_types[*ty_idx];
6404 let component_idx = table_ty.instance.as_u32();
6405 format!("{f}({{ streamTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6406 }
6407
6408 InterfaceType::ErrorContext(ty_idx) => {
6409 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext));
6410 let table_idx = ty_idx.as_u32();
6411 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext).name();
6412 format!("{f}.bind(null, {table_idx})")
6413 }
6414
6415 InterfaceType::Map(ty_idx) => {
6416 instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatMap));
6417 let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatMap).name();
6418 let map_ty = &component_types[*ty_idx];
6419 let key_lift = gen_flat_lift_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
6420 let value_lift =
6421 gen_flat_lift_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
6422 let entry_size32 = map_ty.entry_abi.size32;
6423 let entry_align32 = map_ty.entry_abi.align32;
6424 let value_offset32 = map_ty.value_offset32;
6425 format!(
6426 "{f}({{
6427 keyLiftFn: {key_lift},
6428 valueLiftFn: {value_lift},
6429 entrySize32: {entry_size32},
6430 entryAlign32: {entry_align32},
6431 valueOffset32: {value_offset32},
6432 }})"
6433 )
6434 }
6435 }
6436}
6437
6438fn js_typed_array_ctor(ty: &InterfaceType) -> Option<&'static str> {
6439 match ty {
6440 InterfaceType::U8 => Some("Uint8Array"),
6441 InterfaceType::S8 => Some("Int8Array"),
6442 InterfaceType::U16 => Some("Uint16Array"),
6443 InterfaceType::S16 => Some("Int16Array"),
6444 InterfaceType::U32 => Some("Uint32Array"),
6445 InterfaceType::S32 => Some("Int32Array"),
6446 InterfaceType::U64 => Some("BigUint64Array"),
6447 InterfaceType::S64 => Some("BigInt64Array"),
6448 InterfaceType::Float32 => Some("Float32Array"),
6449 InterfaceType::Float64 => Some("Float64Array"),
6450 _ => None,
6451 }
6452}
6453
6454pub fn gen_flat_lower_fn_list_js_expr(
6463 instantiator: &mut Instantiator,
6464 types: &[InterfaceType],
6465 extra_import_map: &Option<&mut ResourceMap>,
6466) -> String {
6467 let mut lower_fns: Vec<String> = Vec::with_capacity(types.len());
6468 for ty in types.iter() {
6469 lower_fns.push(gen_flat_lower_fn_js_expr(
6470 instantiator,
6471 ty,
6472 extra_import_map,
6473 ));
6474 }
6475 format!("[{}]", lower_fns.join(","))
6476}
6477
6478pub fn gen_flat_lower_fn_js_expr(
6499 instantiator: &mut Instantiator,
6500 ty: &InterfaceType,
6501 extra_resource_map: &Option<&mut ResourceMap>,
6502) -> String {
6503 let component_types = instantiator.types;
6504 match ty {
6505 InterfaceType::Bool => {
6506 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBool));
6507 Intrinsic::Lower(LowerIntrinsic::LowerFlatBool)
6508 .name()
6509 .into()
6510 }
6511
6512 InterfaceType::S8 => {
6513 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS8));
6514 Intrinsic::Lower(LowerIntrinsic::LowerFlatS8).name().into()
6515 }
6516
6517 InterfaceType::U8 => {
6518 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU8));
6519 Intrinsic::Lower(LowerIntrinsic::LowerFlatU8).name().into()
6520 }
6521
6522 InterfaceType::S16 => {
6523 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS16));
6524 Intrinsic::Lower(LowerIntrinsic::LowerFlatS16).name().into()
6525 }
6526
6527 InterfaceType::U16 => {
6528 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU16));
6529 Intrinsic::Lower(LowerIntrinsic::LowerFlatU16).name().into()
6530 }
6531
6532 InterfaceType::S32 => {
6533 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS32));
6534 Intrinsic::Lower(LowerIntrinsic::LowerFlatS32).name().into()
6535 }
6536
6537 InterfaceType::U32 => {
6538 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU32));
6539 Intrinsic::Lower(LowerIntrinsic::LowerFlatU32).name().into()
6540 }
6541
6542 InterfaceType::S64 => {
6543 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS64));
6544 Intrinsic::Lower(LowerIntrinsic::LowerFlatS64).name().into()
6545 }
6546
6547 InterfaceType::U64 => {
6548 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU64));
6549 Intrinsic::Lower(LowerIntrinsic::LowerFlatU64).name().into()
6550 }
6551
6552 InterfaceType::Float32 => {
6553 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32));
6554 Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32)
6555 .name()
6556 .into()
6557 }
6558
6559 InterfaceType::Float64 => {
6560 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64));
6561 Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64)
6562 .name()
6563 .into()
6564 }
6565
6566 InterfaceType::Char => {
6567 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatChar));
6568 Intrinsic::Lower(LowerIntrinsic::LowerFlatChar)
6569 .name()
6570 .into()
6571 }
6572
6573 InterfaceType::String => {
6574 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny));
6575 Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny)
6576 .name()
6577 .into()
6578 }
6579
6580 InterfaceType::Record(ty_idx) => {
6581 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord));
6582 let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord).name();
6583 let record_ty = &component_types[*ty_idx];
6584 let size32 = record_ty.abi.size32;
6585 let align32 = record_ty.abi.align32;
6586 let mut keys_and_lowers_expr = String::from("[");
6587 for f in &record_ty.fields {
6588 let field_abi = component_types.canonical_abi(&f.ty);
6592 let field_size32 = field_abi.size32;
6593 let field_align32 = field_abi.align32;
6594 keys_and_lowers_expr.push_str(&format!(
6595 "['{}', {}, {}, {} ],",
6596 f.name.to_lower_camel_case(),
6597 gen_flat_lower_fn_js_expr(instantiator, &f.ty, &None),
6598 field_size32,
6599 field_align32,
6600 ));
6601 }
6602 keys_and_lowers_expr.push(']');
6603 format!(
6604 "{lower_fn}({{ fieldMetas: {keys_and_lowers_expr}, size32: {size32}, align32: {align32} }})"
6605 )
6606 }
6607
6608 InterfaceType::Variant(ty_idx) => {
6609 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
6610 let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant).name();
6611 let variant_ty = &component_types[*ty_idx];
6612 let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
6613 let size32 = variant_ty.abi.size32;
6614 let align32 = variant_ty.abi.align32;
6615 let payload_offset32 = variant_ty.info.payload_offset32;
6616
6617 let mut lower_metas_expr = String::from("[");
6618 for (name, maybe_ty) in variant_ty.cases.iter() {
6619 let (case_size32, case_align32, case_flat_count) = if let Some(iface_ty) = maybe_ty
6620 {
6621 let cabi_info = component_types.canonical_abi(iface_ty);
6622 (
6623 cabi_info.size32.to_string(),
6624 cabi_info.align32.to_string(),
6625 cabi_info
6626 .flat_count(MAX_FLAT_PARAMS)
6627 .map(|v| v.to_string())
6628 .unwrap_or_else(|| "null".into()),
6629 )
6630 } else {
6631 ("0".into(), "0".into(), "0".into())
6632 };
6633
6634 lower_metas_expr.push_str(&format!(
6635 "[ '{name}', {}, {case_size32}, {case_align32}, {case_flat_count} ],",
6636 maybe_ty
6637 .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, &None))
6638 .unwrap_or_else(|| "null".into()),
6639 ));
6640 }
6641 lower_metas_expr.push(']');
6642
6643 format!(
6644 "{lower_fn}({{
6645 caseMetas: {lower_metas_expr},
6646 variantSize32: {size32},
6647 variantAlign32: {align32},
6648 variantPayloadOffset32: {payload_offset32},
6649 variantFlatCount: {variant_flat_count},
6650 }} )"
6651 )
6652 }
6653
6654 InterfaceType::List(ty_idx) => {
6655 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
6656 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
6657 let list_ty = &component_types[*ty_idx];
6658 let elem_ty_lower_expr =
6659 gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6660 let elem_cabi = component_types.canonical_abi(&list_ty.element);
6661 let elem_align32 = elem_cabi.align32;
6662 let elem_size32 = elem_cabi.size32;
6663
6664 format!(
6665 "{f}({{
6666 elemLowerFn: {elem_ty_lower_expr},
6667 elemSize32: {elem_size32},
6668 elemAlign32: {elem_align32},
6669 }})"
6670 )
6671 }
6672
6673 InterfaceType::FixedLengthList(ty_idx) => {
6674 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
6675 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
6676 let list_ty = &component_types[*ty_idx];
6677 let elem_ty_lower_expr =
6678 gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6679 let list_len = list_ty.size;
6680 let list_align32 = list_ty.abi.size32;
6681 let list_size32 = list_ty.abi.size32;
6682 let elem_cabi = component_types.canonical_abi(&list_ty.element);
6683 let elem_align32 = elem_cabi.align32;
6684 let elem_size32 = elem_cabi.size32;
6685
6686 format!(
6687 r#"{f}({{
6688 elemLowerFn: {elem_ty_lower_expr},
6689 elemAlign32: {elem_align32},
6690 elemSize32: {elem_size32},
6691 align32: {list_align32},
6692 size32: {list_size32},
6693 knownLen: {list_len},
6694 }})"#
6695 )
6696 }
6697
6698 InterfaceType::Tuple(ty_idx) => {
6699 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple));
6700 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple).name();
6701 let tuple_ty = &component_types[*ty_idx];
6702 let size_u32 = tuple_ty.abi.size32;
6703 let align_u32 = tuple_ty.abi.align32;
6704
6705 let mut elem_lowers_expr = String::from("[");
6706 for ty in &tuple_ty.types {
6707 let lower_fn_js = gen_flat_lower_fn_js_expr(instantiator, ty, extra_resource_map);
6708 let elem_abi = component_types.canonical_abi(ty);
6709 let elem_size32 = elem_abi.size32;
6710 let elem_align32 = elem_abi.align32;
6711 elem_lowers_expr
6712 .push_str(&format!("[{lower_fn_js}, {elem_size32}, {elem_align32}],"));
6713 }
6714 elem_lowers_expr.push(']');
6715
6716 format!(
6717 "{f}({{ elemLowerMetas: {elem_lowers_expr}, size32: {size_u32}, align32: {align_u32} }})"
6718 )
6719 }
6720
6721 InterfaceType::Flags(ty_idx) => {
6722 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags));
6723 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags).name();
6724 let flags_ty = &component_types[*ty_idx];
6725 let size32 = flags_ty.abi.size32;
6726 let align32 = flags_ty.abi.align32;
6727 let names_list_js = format!(
6728 "[{}]",
6729 flags_ty
6730 .names
6731 .iter()
6732 .map(|s| format!("'{}'", s.to_lower_camel_case()))
6733 .collect::<Vec<_>>()
6734 .join(",")
6735 );
6736 let num_flags = flags_ty.names.len();
6737 let elem_size = if num_flags <= 8 {
6738 1
6739 } else if num_flags <= 16 {
6740 2
6741 } else {
6742 4
6743 };
6744
6745 format!(
6746 "{f}({{ names: {names_list_js}, size32: {size32}, align32: {align32}, intSizeBytes: {elem_size} }})"
6747 )
6748 }
6749
6750 InterfaceType::Enum(ty_idx) => {
6751 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum));
6752 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum).name();
6753 let enum_ty = &component_types[*ty_idx];
6754 let enum_size32 = enum_ty.abi.size32;
6755 let enum_align32 = enum_ty.abi.align32;
6756 let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
6757 let enum_payload_offset32 = enum_ty.info.payload_offset32;
6758
6759 let mut elem_lowers_expr = String::from("[");
6760 for name in &enum_ty.names {
6761 let name = crate::enum_case_name(
6762 name,
6763 instantiator.bindgen.opts.enum_values_screaming_snake_case,
6764 );
6765 elem_lowers_expr.push_str(&format!(
6766 "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
6767 ));
6768 }
6769 elem_lowers_expr.push(']');
6770
6771 format!(
6772 r#"
6773 {f}({{
6774 caseMetas: {elem_lowers_expr},
6775 variantSize32: {enum_size32},
6776 variantAlign32: {enum_align32},
6777 variantPayloadOffset32: {enum_payload_offset32},
6778 variantFlatCount: {enum_flat_count},
6779 }})
6780 "#
6781 )
6782 }
6783
6784 InterfaceType::Option(ty_idx) => {
6785 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOption));
6786 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOption).name();
6787 let option_ty = &component_types[*ty_idx];
6788 let option_size32 = option_ty.abi.size32;
6789 let option_align32 = option_ty.abi.align32;
6790 let option_payload_offset32 = option_ty.info.payload_offset32;
6791 let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
6792
6793 let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
6794 let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
6795 let some_ty_size32 = some_ty_abi.size32;
6796 let some_ty_align32 = some_ty_abi.align32;
6797 let some_ty_lower_fn_js =
6798 gen_flat_lower_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
6799
6800 format!(
6801 r#"
6802 {f}({{
6803 caseMetas: [
6804 [ 'none', null, 0, 0, 0 ],
6805 [ 'some', {some_ty_lower_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}],
6806 ],
6807 variantSize32: {option_size32},
6808 variantAlign32: {option_align32},
6809 variantPayloadOffset32: {option_payload_offset32},
6810 variantFlatCount: {option_flat_count},
6811 }})
6812 "#
6813 )
6814 }
6815
6816 InterfaceType::Result(ty_idx) => {
6817 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatResult));
6818 let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatResult).name();
6819 let result_ty = &component_types[*ty_idx];
6820 let result_size32 = result_ty.abi.size32;
6821 let result_align32 = result_ty.abi.align32;
6822 let result_payload_offset32 = result_ty.info.payload_offset32;
6823 let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
6824
6825 let ok_lower_fn_js = result_ty
6826 .ok
6827 .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
6828 .unwrap_or_else(|| "null".into());
6829 let err_lower_fn_js = result_ty
6830 .err
6831 .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
6832 .unwrap_or_else(|| "null".into());
6833
6834 format!(
6835 r#"
6836 {lower_fn}({{
6837 caseMetas: [
6838 [ 'ok', {ok_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
6839 [ 'err', {err_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
6840 ],
6841 variantSize32: {result_size32},
6842 variantAlign32: {result_align32},
6843 variantPayloadOffset32: {result_payload_offset32},
6844 variantFlatCount: {result_flat_count},
6845 }})
6846 "#
6847 )
6848 }
6849
6850 InterfaceType::Own(ty_idx) => {
6851 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn));
6852 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn).name();
6853 let resource_table_ty = &component_types[*ty_idx];
6854 let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
6855 let resource_idx = resource_table_ty.unwrap_concrete_ty();
6856
6857 let (_, ResourceTable { imported, data }) = match (
6861 instantiator.imports_resource_index_types.get(&resource_idx),
6862 instantiator.exports_resource_index_types.get(&resource_idx),
6863 ) {
6864 (Some(import_ty_id), _) => {
6865 let ty = crate::dealias(instantiator.resolve, *import_ty_id);
6866 let maybe_resource_table =
6867 instantiator.resource_imports.get(&ty).or(extra_resource_map
6868 .as_ref()
6869 .and_then(|m| m.get(import_ty_id)));
6870 (
6871 ty,
6872 maybe_resource_table.expect("missing imported resource table information"),
6873 )
6874 }
6875 (_, Some(export_ty_id)) => {
6876 let ty = crate::dealias(instantiator.resolve, *export_ty_id);
6877 let maybe_resource_table =
6878 instantiator.resource_exports.get(&ty).or(extra_resource_map
6879 .as_ref()
6880 .and_then(|m| m.get(export_ty_id)));
6881 (
6882 ty,
6883 maybe_resource_table.expect("missing exported resource table information"),
6884 )
6885 }
6886
6887 (None, None) => {
6889 return format!(
6890 "{f}({{
6891 componentIdx: {component_idx},
6892 lowerFn: () => {{ throw new Error('missing/invalid resource metadata'); }}
6893 }})"
6894 );
6895 }
6896 };
6897
6898 let lower_fn_js = match data {
6900 ResourceData::Host {
6902 tid,
6903 rid,
6904 local_name,
6905 ..
6906 } => {
6907 let tid = tid.as_u32();
6908 let rid = rid.as_u32();
6909 let symbol_resource_rep =
6910 instantiator.bindgen.intrinsic(Intrinsic::SymbolResourceRep);
6911 let symbol_resource_handle = instantiator
6912 .bindgen
6913 .intrinsic(Intrinsic::SymbolResourceHandle);
6914 let symbol_dispose = instantiator.bindgen.intrinsic(Intrinsic::SymbolDispose);
6915
6916 if *imported {
6917 let create_own_fn = instantiator.bindgen.intrinsic(Intrinsic::Resource(
6920 ResourceIntrinsic::ResourceTableCreateOwn,
6921 ));
6922 format!(
6923 r#"
6924 function lowerImportedOwnedHost_{local_name}(obj) {{
6925 if (!(obj instanceof {local_name})) {{
6926 throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
6927 }}
6928 let handle = obj[{symbol_resource_handle}];
6929 if (!handle) {{
6930 const rep = obj[{symbol_resource_rep}] || ++captureCnt{rid};
6931 captureTable{rid}.set(rep, obj);
6932 handle = {create_own_fn}(handleTable{tid}, rep);
6933 }}
6934 return handle;
6935 }}
6936 "#
6937 )
6938 } else {
6939 let empty_func = instantiator
6945 .bindgen
6946 .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
6947 format!(
6948 r#"
6949 function lowerExportedOwnedHost_{local_name}(obj) {{
6950 let handle = obj[{symbol_resource_handle}];
6951 if (!handle) {{
6952 throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
6953 }}
6954 finalizationRegistry{tid}.unregister(obj);
6955 obj[{symbol_dispose}] = {empty_func};
6956 obj[{symbol_resource_handle}] = undefined;
6957 return handle;
6958 }}
6959 "#
6960 )
6961 }
6962 }
6963
6964 ResourceData::Guest {
6966 resource_name,
6967 prefix,
6968 extra,
6969 } => {
6970 assert!(
6971 extra.is_none(),
6972 "plain resource handles do not carry extra data"
6973 );
6974
6975 let upper_camel = resource_name.to_upper_camel_case();
6976 let lower_camel = resource_name.to_lower_camel_case();
6977 let prefix = prefix.as_deref().unwrap_or("");
6978
6979 if *imported {
6980 let symbol_resource_handle = instantiator
6983 .bindgen
6984 .intrinsic(Intrinsic::SymbolResourceHandle);
6985 format!(
6986 r#"
6987 function lowerImportedOwnedGuest_{upper_camel}(obj) {{
6988 const handle = obj[{symbol_resource_handle}];
6989 finalizationRegistry_import${prefix}{lower_camel}.unregister(obj);
6990 return handle;
6991 }}
6992 "#
6993 )
6994 } else {
6995 let symbol_resource_handle = instantiator
6999 .bindgen
7000 .intrinsic(Intrinsic::SymbolResourceHandle);
7001 format!(
7002 r#"
7003 function lowerExportedOwnedGuest_{upper_camel}(obj) {{
7004 if (!(obj instanceof {upper_camel})) {{
7005 throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
7006 }}
7007 let handle = obj[{symbol_resource_handle}];
7008 if (handle === undefined) {{
7009 const localRep = repCnt++;
7010 repTable.set(localRep, {{ rep: obj, own: true }});
7011 handle = $resource_{prefix}new${lower_camel}(localRep);
7012 obj[{symbol_resource_handle}] = handle;
7013 finalizationRegistry_export${prefix}{lower_camel}.register(obj, handle, obj);
7014 }}
7015 return handle;
7016 }}
7017 "#
7018 )
7019 }
7020 }
7021 };
7022
7023 format!(
7024 "{f}({{
7025 componentIdx: {component_idx},
7026 lowerFn: {lower_fn_js},
7027 }})"
7028 )
7029 }
7030
7031 InterfaceType::Borrow(ty_idx) => {
7032 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow));
7033 let table_idx = ty_idx.as_u32();
7034 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow).name();
7035 format!("{f}.bind(null, {table_idx})")
7036 }
7037
7038 InterfaceType::Future(ty_idx) => {
7039 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture));
7040 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture).name();
7041 let table_idx = ty_idx.as_u32();
7042 let table_ty = &component_types[*ty_idx];
7043 let component_idx = table_ty.instance.as_u32();
7044 let future_ty_idx = table_ty.ty;
7045 let future_ty = &component_types[future_ty_idx];
7046 let payload = future_ty.payload;
7047 let payload_ty_name_js = future_ty
7048 .payload
7049 .map(|iface_ty| format!("'{iface_ty:?}'"))
7050 .unwrap_or_else(|| "null".into());
7051
7052 let (
7054 payload_size32,
7055 payload_align32,
7056 payload_flat_count_js,
7057 payload_lift_fn_js,
7058 payload_lower_fn_js,
7059 is_borrowed,
7060 is_none_type,
7061 is_numeric_type,
7062 is_async_value,
7063 ) = match payload {
7064 None => (
7065 0,
7066 0,
7067 "0".into(),
7068 "() => {{ throw new Error('empty future payload'); }}".into(),
7069 "() => {{ throw new Error('empty future payload'); }}".into(),
7070 false,
7071 true,
7072 false,
7073 false,
7074 ),
7075 Some(payload_ty) => {
7076 let cabi = instantiator.types.canonical_abi(&payload_ty);
7077 (
7078 cabi.size32,
7079 cabi.align32,
7080 cabi.flat_count
7081 .map(|v| format!("{v}"))
7082 .unwrap_or_else(|| "null".into()),
7083 gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7084 gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7085 matches!(payload_ty, InterfaceType::Borrow(_)),
7086 false,
7087 matches!(
7088 payload_ty,
7089 InterfaceType::U8
7090 | InterfaceType::U16
7091 | InterfaceType::U32
7092 | InterfaceType::U64
7093 | InterfaceType::S8
7094 | InterfaceType::S16
7095 | InterfaceType::S32
7096 | InterfaceType::S64
7097 | InterfaceType::Float32
7098 | InterfaceType::Float64
7099 ),
7100 matches!(
7101 payload_ty,
7102 InterfaceType::Stream(_) | InterfaceType::Future(_)
7103 ),
7104 )
7105 }
7106 };
7107
7108 let mut future_nesting_level = 0;
7110 let mut payload_ty = future_ty.payload;
7111 while let Some(InterfaceType::Future(inner_ty)) = payload_ty {
7112 future_nesting_level += 1;
7113 payload_ty = component_types[component_types[inner_ty].ty].payload;
7114 }
7115
7116 format!(
7117 r#"{f}({{
7118 futureTableIdx: {table_idx},
7119 futureNestingLevel: {future_nesting_level},
7120 componentIdx: {component_idx},
7121 elemMeta: {{
7122 liftFn: {payload_lift_fn_js},
7123 lowerFn: {payload_lower_fn_js},
7124 payloadTypeName: {payload_ty_name_js},
7125 isNone: {is_none_type},
7126 isNumeric: {is_numeric_type},
7127 isBorrowed: {is_borrowed},
7128 isAsyncValue: {is_async_value},
7129 flatCount: {payload_flat_count_js},
7130 align32: {payload_align32},
7131 size32: {payload_size32},
7132 }},
7133 }})
7134 "#
7135 )
7136 }
7137
7138 InterfaceType::Stream(ty_idx) => {
7139 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStream));
7140 let table_idx = ty_idx.as_u32();
7141 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatStream).name();
7142 let table_ty = &component_types[*ty_idx];
7143 let component_idx = table_ty.instance.as_u32();
7144 let stream_ty_idx = table_ty.ty;
7145 let stream_ty = &component_types[stream_ty_idx];
7146 let payload = stream_ty.payload;
7147 let payload_ty_name_js = stream_ty
7148 .payload
7149 .map(|iface_ty| format!("'{iface_ty:?}'"))
7150 .unwrap_or_else(|| "null".into());
7151
7152 let (
7155 payload_size32,
7156 payload_align32,
7157 payload_flat_count_js,
7158 payload_lift_fn_js,
7159 payload_lower_fn_js,
7160 is_borrowed,
7161 is_none_type,
7162 is_numeric_type,
7163 is_async_value,
7164 typed_array_js,
7165 ) = match payload {
7166 None => (
7167 0,
7168 0,
7169 "0".into(),
7170 "() => {{ throw new Error('empty stream payload'); }}".into(),
7171 "() => {{ throw new Error('empty stream payload'); }}".into(),
7172 false,
7173 true,
7174 false,
7175 false,
7176 "undefined",
7177 ),
7178 Some(payload_ty) => {
7179 let cabi = instantiator.types.canonical_abi(&payload_ty);
7180 (
7181 cabi.size32,
7182 cabi.align32,
7183 cabi.flat_count
7184 .map(|v| format!("{v}"))
7185 .unwrap_or_else(|| "null".into()),
7186 gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7187 gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7188 matches!(payload_ty, InterfaceType::Borrow(_)),
7189 false,
7190 matches!(
7191 payload_ty,
7192 InterfaceType::U8
7193 | InterfaceType::U16
7194 | InterfaceType::U32
7195 | InterfaceType::U64
7196 | InterfaceType::S8
7197 | InterfaceType::S16
7198 | InterfaceType::S32
7199 | InterfaceType::S64
7200 | InterfaceType::Float32
7201 | InterfaceType::Float64
7202 ),
7203 matches!(
7204 payload_ty,
7205 InterfaceType::Stream(_) | InterfaceType::Future(_)
7206 ),
7207 js_typed_array_ctor(&payload_ty).unwrap_or("undefined"),
7208 )
7209 }
7210 };
7211
7212 format!(
7213 r#"{f}({{
7214 streamTableIdx: {table_idx},
7215 componentIdx: {component_idx},
7216 elemMeta: {{
7217 liftFn: {payload_lift_fn_js},
7218 lowerFn: {payload_lower_fn_js},
7219 payloadTypeName: {payload_ty_name_js},
7220 isNone: {is_none_type},
7221 isNumeric: {is_numeric_type},
7222 isBorrowed: {is_borrowed},
7223 isAsyncValue: {is_async_value},
7224 typedArray: {typed_array_js},
7225 flatCount: {payload_flat_count_js},
7226 align32: {payload_align32},
7227 size32: {payload_size32},
7228 }},
7229 }})
7230 "#
7231 )
7232 }
7233
7234 InterfaceType::ErrorContext(ty_idx) => {
7235 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext));
7236 let table_idx = ty_idx.as_u32();
7237 let lower_flat_err_ctx_fn =
7238 Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext).name();
7239 format!("{lower_flat_err_ctx_fn}.bind(null, {table_idx})")
7240 }
7241
7242 InterfaceType::Map(ty_idx) => {
7243 instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatMap));
7244 let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatMap).name();
7245 let map_ty = &component_types[*ty_idx];
7246 let key_lower =
7247 gen_flat_lower_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
7248 let value_lower =
7249 gen_flat_lower_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
7250 let entry_size32 = map_ty.entry_abi.size32;
7251 let entry_align32 = map_ty.entry_abi.align32;
7252 let value_offset32 = map_ty.value_offset32;
7253 format!(
7254 "{f}({{
7255 keyLowerFn: {key_lower},
7256 valueLowerFn: {value_lower},
7257 entrySize32: {entry_size32},
7258 entryAlign32: {entry_align32},
7259 valueOffset32: {value_offset32},
7260 }})"
7261 )
7262 }
7263 }
7264}
7265
7266#[cfg(test)]
7267mod tests {
7268 use super::*;
7269
7270 fn compat_key(version_str: &str) -> Option<String> {
7272 semver_compat_key(version_str).map(|(key, _)| key)
7273 }
7274
7275 #[test]
7276 fn test_semver_compat_key() {
7277 assert_eq!(compat_key("1.0.0"), Some("1".into()));
7278 assert_eq!(compat_key("1.2.3"), Some("1".into()));
7279 assert_eq!(compat_key("2.0.0"), Some("2".into()));
7280 assert_eq!(compat_key("0.2.0"), Some("0.2".into()));
7281 assert_eq!(compat_key("0.2.10"), Some("0.2".into()));
7282 assert_eq!(compat_key("0.1.0"), Some("0.1".into()));
7283 assert_eq!(compat_key("0.0.1"), None);
7284 assert_eq!(compat_key("1.0.0-rc.1"), None);
7285 assert_eq!(compat_key("0.2.0-pre"), None);
7286 assert_eq!(compat_key("not-a-version"), None);
7287 }
7288
7289 #[test]
7290 fn test_semver_compat_key_returns_parsed_version() {
7291 let (key, ver) = semver_compat_key("1.2.3").unwrap();
7292 assert_eq!(key, "1");
7293 assert_eq!(ver, Version::new(1, 2, 3));
7294 }
7295
7296 #[test]
7297 fn test_map_import_exact_match() {
7298 let mut map = HashMap::new();
7299 map.insert("wasi:http/types@0.2.0".into(), "./http.js#types".into());
7300 let map = Some(map);
7301 assert_eq!(
7302 map_import(&map, "wasi:http/types@0.2.0"),
7303 ("./http.js".into(), Some("types".into()))
7304 );
7305 }
7306
7307 #[test]
7308 fn test_map_import_sans_version_match() {
7309 let mut map = HashMap::new();
7310 map.insert("wasi:http/types".into(), "./http.js".into());
7311 let map = Some(map);
7312 assert_eq!(
7313 map_import(&map, "wasi:http/types@0.2.10"),
7314 ("./http.js".into(), None)
7315 );
7316 }
7317
7318 #[test]
7319 fn test_map_import_wildcard_sans_version() {
7320 let mut map = HashMap::new();
7322 map.insert("wasi:http/*".into(), "./http.js#*".into());
7323 let map = Some(map);
7324 assert_eq!(
7325 map_import(&map, "wasi:http/types@0.2.10"),
7326 ("./http.js".into(), Some("types".into()))
7327 );
7328 }
7329
7330 #[test]
7331 fn test_map_import_semver_exact_key() {
7332 let mut map = HashMap::new();
7334 map.insert("wasi:http/types@0.2.0".into(), "./http.js".into());
7335 let map = Some(map);
7336 assert_eq!(
7337 map_import(&map, "wasi:http/types@0.2.10"),
7338 ("./http.js".into(), None)
7339 );
7340 }
7341
7342 #[test]
7343 fn test_map_import_semver_wildcard_key() {
7344 let mut map = HashMap::new();
7346 map.insert("wasi:http/*@0.2.1".into(), "./http.js#*".into());
7347 let map = Some(map);
7348 assert_eq!(
7349 map_import(&map, "wasi:http/types@0.2.10"),
7350 ("./http.js".into(), Some("types".into()))
7351 );
7352 }
7353
7354 #[test]
7355 fn test_map_import_semver_lower_import_version() {
7356 let mut map = HashMap::new();
7358 map.insert("wasi:http/types@0.2.10".into(), "./http.js".into());
7359 let map = Some(map);
7360 assert_eq!(
7361 map_import(&map, "wasi:http/types@0.2.1"),
7362 ("./http.js".into(), None)
7363 );
7364 }
7365
7366 #[test]
7367 fn test_map_import_semver_no_cross_minor() {
7368 let mut map = HashMap::new();
7370 map.insert("wasi:http/types@0.3.0".into(), "./http.js".into());
7371 let map = Some(map);
7372 assert_eq!(
7373 map_import(&map, "wasi:http/types@0.2.10"),
7374 ("wasi:http/types".into(), None)
7375 );
7376 }
7377
7378 #[test]
7379 fn test_map_import_semver_prefers_highest() {
7380 let mut map = HashMap::new();
7382 map.insert("wasi:http/types@0.2.1".into(), "./http-old.js".into());
7383 map.insert("wasi:http/types@0.2.5".into(), "./http-new.js".into());
7384 let map = Some(map);
7385 assert_eq!(
7386 map_import(&map, "wasi:http/types@0.2.10"),
7387 ("./http-new.js".into(), None)
7388 );
7389 }
7390
7391 #[test]
7392 fn test_map_import_no_match_prerelease() {
7393 let mut map = HashMap::new();
7394 map.insert("wasi:http/types@0.2.0-rc.1".into(), "./http.js".into());
7395 let map = Some(map);
7396 assert_eq!(
7397 map_import(&map, "wasi:http/types@0.2.0"),
7398 ("wasi:http/types".into(), None)
7399 );
7400 }
7401
7402 #[test]
7403 fn test_map_import_prerelease_versioned_wildcard_wins_over_unversioned_wildcard() {
7404 let mut map = HashMap::new();
7407 map.insert(
7408 "wasi:cli/*".into(),
7409 "@bytecodealliance/preview2-shim/cli#*".into(),
7410 );
7411 map.insert(
7412 "wasi:cli/*@0.3.0".into(),
7413 "@bytecodealliance/preview3-shim/cli#*".into(),
7414 );
7415 let map = Some(map);
7416 assert_eq!(
7417 map_import(&map, "wasi:cli/stdout@0.3.0"),
7418 (
7419 "@bytecodealliance/preview3-shim/cli".into(),
7420 Some("stdout".into())
7421 )
7422 );
7423 assert_eq!(
7425 map_import(&map, "wasi:cli/stdout@0.2.6"),
7426 (
7427 "@bytecodealliance/preview2-shim/cli".into(),
7428 Some("stdout".into())
7429 )
7430 );
7431 assert_eq!(
7433 map_import(&map, "wasi:cli/stdout"),
7434 (
7435 "@bytecodealliance/preview2-shim/cli".into(),
7436 Some("stdout".into())
7437 )
7438 );
7439 }
7440
7441 #[test]
7442 fn test_map_import_no_match_zero_zero() {
7443 let mut map = HashMap::new();
7444 map.insert("wasi:http/types@0.0.1".into(), "./http.js".into());
7445 let map = Some(map);
7446 assert_eq!(
7447 map_import(&map, "wasi:http/types@0.0.2"),
7448 ("wasi:http/types".into(), None)
7449 );
7450 }
7451
7452 #[test]
7453 fn test_map_import_semver_major_version() {
7454 let mut map = HashMap::new();
7456 map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7457 let map = Some(map);
7458 assert_eq!(
7459 map_import(&map, "wasi:http/types@1.2.3"),
7460 ("./http.js".into(), None)
7461 );
7462 }
7463
7464 #[test]
7465 fn test_map_import_semver_no_cross_major() {
7466 let mut map = HashMap::new();
7468 map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7469 let map = Some(map);
7470 assert_eq!(
7471 map_import(&map, "wasi:http/types@2.0.0"),
7472 ("wasi:http/types".into(), None)
7473 );
7474 }
7475
7476 #[test]
7477 fn test_map_import_no_map() {
7478 assert_eq!(
7480 map_import(&None, "wasi:http/types@0.2.0"),
7481 ("wasi:http/types".into(), None)
7482 );
7483 }
7484
7485 #[test]
7486 fn test_map_import_no_map_unversioned() {
7487 assert_eq!(
7489 map_import(&None, "wasi:http/types"),
7490 ("wasi:http/types".into(), None)
7491 );
7492 }
7493
7494 #[test]
7495 fn test_parse_mapping_with_hash() {
7496 assert_eq!(
7497 parse_mapping("./http.js#types"),
7498 ("./http.js".into(), Some("types".into()))
7499 );
7500 }
7501
7502 #[test]
7503 fn test_parse_mapping_without_hash() {
7504 assert_eq!(parse_mapping("./http.js"), ("./http.js".into(), None));
7505 }
7506
7507 #[test]
7508 fn test_parse_mapping_leading_hash() {
7509 assert_eq!(parse_mapping("#foo"), ("#foo".into(), None));
7511 }
7512
7513 #[test]
7514 fn test_parse_mapping_empty() {
7515 assert_eq!(parse_mapping(""), ("".into(), None));
7516 }
7517}