forked from bytecodealliance/ComponentizeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindgen.rs
More file actions
1356 lines (1249 loc) · 50.2 KB
/
bindgen.rs
File metadata and controls
1356 lines (1249 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write;
use anyhow::Result;
use heck::*;
use js_component_bindgen::function_bindgen::{
ErrHandling, FunctionBindgen, ResourceData, ResourceMap, ResourceTable,
};
use js_component_bindgen::intrinsics::{Intrinsic, render_intrinsics};
use js_component_bindgen::names::LocalNames;
use js_component_bindgen::source::Source;
use wit_bindgen_core::abi::{self, LiftLower};
use wit_bindgen_core::wit_parser::Resolve;
use wit_bindgen_core::wit_parser::{
Function, FunctionKind, Handle, InterfaceId, SizeAlign, Type, TypeDefKind, TypeId, TypeOwner,
WorldId, WorldItem,
};
use wit_component::StringEncoding;
use wit_parser::abi::WasmType;
use wit_parser::abi::{AbiVariant, WasmSignature};
use crate::wit::exports::local::spidermonkey_embedding_splicer::splicer::Feature;
use crate::{uwrite, uwriteln};
#[derive(Debug)]
pub enum Resource {
None,
Constructor(String),
Static(String),
Method(String),
}
impl Resource {
pub fn canon_string(&self, fn_name: &str) -> String {
match self {
Resource::None => fn_name.to_string(),
Resource::Constructor(name) => format!("[constructor]{name}"),
Resource::Static(name) => format!("[static]{name}.{fn_name}"),
Resource::Method(name) => format!("[method]{name}.{fn_name}"),
}
}
fn func_name(&self, fn_name: &str) -> String {
match self {
Resource::None => fn_name.to_lower_camel_case(),
Resource::Constructor(name) => {
format!(
"{}${}",
name.to_lower_camel_case(),
fn_name.to_lower_camel_case()
)
}
Resource::Method(name) => {
format!(
"{}$method${}",
name.to_lower_camel_case(),
fn_name.to_lower_camel_case()
)
}
Resource::Static(name) => {
format!(
"{}$static${}",
name.to_lower_camel_case(),
fn_name.to_lower_camel_case()
)
}
}
}
}
#[derive(Debug)]
pub struct BindingItem {
pub iface: bool,
pub iface_name: Option<String>,
pub binding_name: String,
pub resource: Resource,
pub name: String,
pub func: CoreFn,
}
struct JsBindgen<'a> {
/// The source code for the "main" file that's going to be created for the
/// component we're generating bindings for. This is incrementally added to
/// over time and primarily contains the main `instantiate` function as well
/// as a type-description of the input/output interfaces.
src: Source,
/// List of all intrinsics emitted to `src` so far.
all_intrinsics: BTreeSet<Intrinsic>,
esm_bindgen: EsmBindgen,
local_names: LocalNames,
resolve: &'a Resolve,
world: WorldId,
sizes: SizeAlign,
memory: String,
realloc: String,
// export "name"
exports: Vec<(String, BindingItem)>,
// imports "specifier"
imports: Vec<(String, BindingItem)>,
resource_directions: HashMap<TypeId, AbiVariant>,
imported_resources: BTreeSet<TypeId>,
/// Features that were enabled at the time of generation
features: &'a Vec<Feature>,
}
#[derive(Debug)]
pub enum CoreTy {
I32,
I64,
F32,
F64,
}
#[derive(Debug)]
pub struct CoreFn {
pub params: Vec<CoreTy>,
pub ret: Option<CoreTy>,
pub retptr: bool,
pub retsize: u32,
pub paramptr: bool,
}
#[derive(Debug)]
pub struct Componentization {
pub js_bindings: String,
pub exports: Vec<(String, BindingItem)>,
pub imports: Vec<(String, BindingItem)>,
pub resource_imports: Vec<(String, String, u32)>,
}
pub fn componentize_bindgen(
resolve: &Resolve,
wid: WorldId,
features: &Vec<Feature>,
) -> Result<Componentization> {
let mut bindgen = JsBindgen {
src: Source::default(),
esm_bindgen: EsmBindgen::default(),
local_names: LocalNames::default(),
all_intrinsics: BTreeSet::new(),
resolve,
world: wid,
sizes: SizeAlign::default(),
memory: "$memory".to_string(),
realloc: "$realloc".to_string(),
exports: Vec::new(),
imports: Vec::new(),
resource_directions: HashMap::new(),
imported_resources: BTreeSet::new(),
features,
};
bindgen.sizes.fill(resolve);
bindgen
.local_names
.exclude_globals(Intrinsic::get_global_names());
bindgen.imports_bindgen();
bindgen.exports_bindgen()?;
bindgen.esm_bindgen.populate_export_aliases();
// consolidate import specifiers and generate wrappers
// we do this separately because function index order matters
let mut import_bindings = Vec::new();
for (specifier, item) in bindgen.imports.iter() {
// this import binding order matters
import_bindings.push(generate_binding_name_import(
&item.resource.func_name(&item.name),
&item.iface_name,
specifier,
));
}
let by_specifier_by_resource = bindgen.imports.iter().fold(
BTreeMap::<_, BTreeMap<_, Vec<_>>>::new(),
|mut map, (specifier, item)| {
map.entry(specifier)
.or_default()
.entry(match &item.resource {
Resource::None => None,
Resource::Method(name)
| Resource::Static(name)
| Resource::Constructor(name) => Some(name),
})
.or_default()
.push(item);
map
},
);
let mut import_wrappers = Vec::new();
for (specifier, by_resource) in by_specifier_by_resource {
let mut specifier_list = Vec::new();
for (resource, items) in by_resource {
let item = items.first().unwrap();
if let Some(resource) = resource {
let export_name = resource.to_upper_camel_case();
let binding_name = generate_binding_name_import(
&export_name,
&item.iface_name,
&item.binding_name,
);
if item.iface {
specifier_list.push(format!("{export_name}: import_{binding_name}"));
} else {
specifier_list.push(format!("default: import_{binding_name}"));
}
} else {
for BindingItem {
iface,
name,
binding_name,
..
} in items
{
let export_name = name.to_lower_camel_case();
if *iface {
specifier_list.push(format!("{export_name}: import_{binding_name}"));
} else {
specifier_list.push(format!("default: import_{binding_name}"));
}
}
}
}
let joined_bindings = specifier_list.join(",\n\t");
import_wrappers.push((
specifier.to_string(),
format!("defineBuiltinModule('{specifier}', {{\n\t{joined_bindings}\n}});"),
));
}
let mut resource_bindings = Vec::new();
let mut resource_imports = Vec::new();
let mut finalization_registries = Vec::new();
for (key, export) in &resolve.worlds[wid].exports {
let key_name = resolve.name_world_key(key);
if let WorldItem::Interface {
id: iface_id,
stability: _,
} = export
{
let iface = &resolve.interfaces[*iface_id];
for ty_id in iface.types.values() {
let ty = &resolve.types[*ty_id];
if let TypeDefKind::Resource = &ty.kind {
let iface_prefix = interface_name(resolve, *iface_id)
.map(|s| format!("{s}$"))
.unwrap_or_default();
let resource_name_camel = ty.name.as_ref().unwrap().to_lower_camel_case();
let resource_name_kebab = ty.name.as_ref().unwrap().to_kebab_case();
let module_name = format!("[export]{key_name}");
resource_bindings.push(format!("{iface_prefix}new${resource_name_camel}"));
resource_imports.push((
module_name.clone(),
format!("[resource-new]{resource_name_kebab}"),
1,
));
resource_bindings.push(format!("{iface_prefix}rep${resource_name_camel}"));
resource_imports.push((
module_name.clone(),
format!("[resource-rep]{resource_name_kebab}"),
1,
));
resource_bindings
.push(format!("export${iface_prefix}drop${resource_name_camel}"));
resource_imports.push((
module_name.clone(),
format!("[resource-drop]{resource_name_kebab}"),
0,
));
finalization_registries.push(format!(
"const finalizationRegistry_export${iface_prefix}{resource_name_camel} = \
new FinalizationRegistry((handle) => {{
$resource_export${iface_prefix}drop${resource_name_camel}(handle);
}});
"
));
}
}
}
}
let mut imported_resource_modules = HashMap::new();
for (key, import) in &resolve.worlds[wid].imports {
let key_name = resolve.name_world_key(key);
match import {
WorldItem::Interface {
id: iface_id,
stability: _,
} => {
let iface = &resolve.interfaces[*iface_id];
for ty_id in iface.types.values() {
let ty = &resolve.types[*ty_id];
if let TypeDefKind::Resource = &ty.kind {
imported_resource_modules.insert(*ty_id, key_name.clone());
}
}
}
WorldItem::Function(_) => {}
WorldItem::Type(id) => {
let ty = &resolve.types[*id];
if ty.kind == TypeDefKind::Resource {
imported_resource_modules.insert(*id, key_name.clone());
}
}
}
}
for &id in &bindgen.imported_resources {
let ty = &resolve.types[id];
let mut impt = imported_resource_modules.get(&id).unwrap().clone();
let prefix = match &ty.owner {
TypeOwner::World(w) => {
impt = "$root".into();
let world = &resolve.worlds[*w];
if *w == wid {
None
} else {
Some(format!("$world${}$", world.name.to_lower_camel_case()))
}
}
TypeOwner::Interface(id) => interface_name(resolve, *id).map(|s| format!("{s}$")),
TypeOwner::None => unreachable!(),
};
let resource_name = ty.name.as_deref().unwrap();
let prefix = prefix.as_deref().unwrap_or("");
let resource_name_camel = resource_name.to_lower_camel_case();
let resource_name_kebab = resource_name.to_kebab_case();
finalization_registries.push(format!(
"const finalizationRegistry_import${prefix}{resource_name_camel} = \
new FinalizationRegistry((handle) => {{
$resource_import${prefix}drop${resource_name_camel}(handle);
}});
"
));
resource_bindings.push(format!("import${prefix}drop${resource_name_camel}"));
resource_imports.push((impt, format!("[resource-drop]{resource_name_kebab}"), 0));
}
let finalization_registries = finalization_registries.concat();
let mut output = Source::default();
uwrite!(
output,
"let {{ TextEncoder, TextDecoder }} = contentGlobal;
let repCnt = 1;
let repTable = new Map();
let [$memory, $realloc{}] = $bindings;
delete globalThis.$bindings;
{finalization_registries}
",
import_bindings
.iter()
.map(|impt| format!(", $import_{impt}"))
.chain(
resource_bindings
.iter()
.map(|name| format!(", $resource_{name}"))
)
.collect::<Vec<_>>()
.concat(),
);
let js_intrinsics = render_intrinsics(&mut bindgen.all_intrinsics, false, true);
output.push_str(&js_intrinsics);
output.push_str(&bindgen.src);
import_wrappers
.iter()
.for_each(|(_, src)| output.push_str(&format!("\n\n{src}")));
bindgen
.esm_bindgen
.render_export_imports(&mut output, "$source_mod", &mut bindgen.local_names);
Ok(Componentization {
js_bindings: output.to_string(),
exports: bindgen.exports,
imports: bindgen.imports,
resource_imports,
})
}
impl JsBindgen<'_> {
fn intrinsic(&mut self, intrinsic: Intrinsic) -> String {
self.all_intrinsics.insert(intrinsic);
intrinsic.name().to_string()
}
fn exports_bindgen(&mut self) -> Result<()> {
for (key, export) in &self.resolve.worlds[self.world].exports {
let name = self.resolve.name_world_key(key);
// Skip bindings generation for wasi:http/incoming-handler if the fetch-event
// feature was enabled. We expect that the built-in engine implementation will be used
if name.starts_with("wasi:http/incoming-handler@0.2.")
&& self.features.contains(&Feature::FetchEvent)
{
continue;
}
match export {
WorldItem::Function(func) => {
let local_name = self.local_names.create_once(&func.name).to_string();
self.export_bindgen(name, false, None, &local_name, StringEncoding::UTF8, func);
self.esm_bindgen.add_export_func(
None,
local_name.to_string(),
func.name.to_lower_camel_case(),
);
}
WorldItem::Interface { id, stability: _ } => {
let iface = &self.resolve.interfaces[*id];
for id in iface.types.values() {
if let TypeDefKind::Resource = &self.resolve.types[*id].kind {
self.resource_directions
.insert(*id, AbiVariant::GuestExport);
}
}
for (func_name, func) in &iface.functions {
let local_name = self
.local_names
.create_once(&format!("{name}-{func_name}"))
.to_string();
match &func.kind {
FunctionKind::Freestanding => {
let name = &name;
self.export_bindgen(
name.to_string(),
true,
interface_name(self.resolve, *id),
&local_name,
StringEncoding::UTF8,
func,
);
self.esm_bindgen.add_export_func(
Some(name),
local_name,
func.name.to_lower_camel_case(),
);
}
FunctionKind::Method(ty)
| FunctionKind::Static(ty)
| FunctionKind::Constructor(ty) => {
let name = &name;
let ty = &self.resolve.types[*ty];
let resource_name = ty.name.as_ref().unwrap().to_upper_camel_case();
let local_name = self
.local_names
.get_or_create(
format!("resource:{resource_name}"),
&resource_name,
)
.0
.to_upper_camel_case();
self.export_bindgen(
name.to_string(),
true,
interface_name(self.resolve, *id),
&local_name,
StringEncoding::UTF8,
func,
);
self.esm_bindgen.ensure_exported_resource(
Some(name),
local_name,
resource_name,
);
}
FunctionKind::AsyncFreestanding => todo!(),
FunctionKind::AsyncMethod(_id) => todo!(),
FunctionKind::AsyncStatic(_id) => todo!(),
};
}
}
// ignore type exports for now
WorldItem::Type(_) => {}
}
}
Ok(())
}
fn resource_bindgen(
&mut self,
resource: TypeId,
import_name: &str,
iface_name: &Option<String>,
functions: Vec<(&str, &Function)>,
) {
let name = binding_name(
&self.resolve.types[resource]
.name
.as_ref()
.unwrap()
.to_upper_camel_case(),
iface_name,
);
uwriteln!(self.src, "\nclass import_{name} {{");
// TODO: Imports tree-shaking for resources is disabled since it is not functioning correctly.
// To make this work properly, we need to trace recursively through the type graph
// to include all resources across argument types.
for (_, func) in functions {
self.import_bindgen(import_name.to_string(), func, true, iface_name.clone());
}
let lower_camel = &self.resolve.types[resource]
.name
.as_ref()
.unwrap()
.to_lower_camel_case();
let prefix = iface_name
.as_deref()
.map(|s| format!("{s}$"))
.unwrap_or_default();
let resource_symbol = self.intrinsic(Intrinsic::SymbolResourceHandle);
let dispose_symbol = self.intrinsic(Intrinsic::SymbolDispose);
uwriteln!(
self.src,
"
[{dispose_symbol}]() {{
finalizationRegistry_import${prefix}{lower_camel}.unregister(this);
$resource_import${prefix}drop${lower_camel}(this[{resource_symbol}]);
this[{resource_symbol}] = undefined;
}}
}}
"
);
}
fn imports_bindgen(&mut self) {
for (key, impt) in &self.resolve.worlds[self.world].imports {
let import_name = self.resolve.name_world_key(key);
match &impt {
WorldItem::Function(f) => {
if !matches!(f.kind, FunctionKind::Freestanding) {
continue;
}
self.import_bindgen(import_name, f, false, None);
}
WorldItem::Interface {
id: i,
stability: _,
} => {
let iface = &self.resolve.interfaces[*i];
for id in iface.types.values() {
if let TypeDefKind::Resource = &self.resolve.types[*id].kind {
self.resource_directions
.insert(*id, AbiVariant::GuestImport);
}
}
let by_resource = iface.functions.iter().fold(
BTreeMap::<_, Vec<_>>::new(),
|mut map, (name, func)| {
map.entry(match &func.kind {
FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
None
}
FunctionKind::Method(ty)
| FunctionKind::Static(ty)
| FunctionKind::Constructor(ty)
| FunctionKind::AsyncMethod(ty)
| FunctionKind::AsyncStatic(ty) => Some(*ty),
})
.or_default()
.push((name.as_str(), func));
map
},
);
let iface_name = interface_name(self.resolve, *i);
for (resource, functions) in by_resource {
if let Some(ty) = resource {
self.resource_bindgen(ty, &import_name, &iface_name, functions);
} else {
for (_, func) in functions {
self.import_bindgen(
import_name.clone(),
func,
true,
iface_name.clone(),
);
}
}
}
}
WorldItem::Type(id) => {
let ty = &self.resolve.types[*id];
if ty.kind == TypeDefKind::Resource {
self.resource_directions
.insert(*id, AbiVariant::GuestImport);
let resource_name = ty.name.as_ref().unwrap();
let mut resource_fns = Vec::new();
for (_, impt) in &self.resolve.worlds[self.world].imports {
if let WorldItem::Function(function) = impt {
let stripped = if let Some(stripped) =
function.name.strip_prefix("[constructor]")
{
stripped
} else if let Some(stripped) =
function.name.strip_prefix("[method]")
{
stripped
} else if let Some(stripped) =
function.name.strip_prefix("[static]")
{
stripped
} else {
continue;
};
if stripped.starts_with(resource_name) {
resource_fns.push((function.name.as_str(), function));
}
}
}
self.resource_bindgen(*id, "$root", &None, resource_fns);
}
}
};
}
}
fn import_bindgen(
&mut self,
import_name: String,
func: &Function,
iface: bool,
iface_name: Option<String>,
) {
let fn_name = func.item_name();
let fn_camel_name = fn_name.to_lower_camel_case();
use generate_binding_name_import as binding_name_fn;
let (binding_name, resource) = match &func.kind {
FunctionKind::Freestanding => {
let binding_name =
generate_binding_name_import(&fn_camel_name, &iface_name, &import_name);
uwrite!(self.src, "\nfunction import_{binding_name}");
(binding_name, Resource::None)
}
FunctionKind::Method(ty) => {
let args = (0..(func.params.len() - 1))
.map(|n| format!("arg{n}"))
.collect::<Vec<_>>()
.join(", ");
uwrite!(self.src, "{fn_camel_name}({args}) {{\nfunction helper");
(
"<<INVALID>>".to_string(),
Resource::Method(self.resolve.types[*ty].name.clone().unwrap()),
)
}
FunctionKind::Static(ty) => {
uwrite!(self.src, "static {fn_camel_name}");
(
"<<INVALID>>".to_string(),
Resource::Static(self.resolve.types[*ty].name.clone().unwrap()),
)
}
FunctionKind::Constructor(ty) => {
uwrite!(self.src, "constructor");
(
"<<INVALID>>".to_string(),
Resource::Constructor(self.resolve.types[*ty].name.clone().unwrap()),
)
}
FunctionKind::AsyncFreestanding => todo!(),
FunctionKind::AsyncMethod(_id) => todo!(),
FunctionKind::AsyncStatic(_id) => todo!(),
};
// imports are canonicalized as exports because
// the function bindgen as currently written still makes this assumption
self.bindgen(
func.params.len(),
&format!(
"$import_{}",
binding_name_fn(
&resource.func_name(fn_name),
&iface_name,
import_name.as_str()
)
),
StringEncoding::UTF8,
func,
AbiVariant::GuestExport,
);
self.src.push_str("\n");
if let FunctionKind::Method(_) = &func.kind {
let args = (0..(func.params.len() - 1))
.map(|n| format!(", arg{n}"))
.collect::<Vec<_>>()
.concat();
uwriteln!(self.src, "return helper(this{args});\n}}");
}
let sig = self.resolve.wasm_signature(AbiVariant::GuestImport, func);
let component_item = if let Some(iface_name) = iface_name {
BindingItem {
iface,
binding_name,
iface_name: Some(iface_name),
resource,
name: fn_name.to_string(),
func: self.core_fn(func, &sig),
}
} else {
BindingItem {
iface,
binding_name,
iface_name: None,
resource,
name: fn_name.to_string(),
func: self.core_fn(func, &sig),
}
};
self.imports.push((import_name, component_item));
}
fn create_resource_map(&self, func: &Function) -> ResourceMap {
let mut resource_map = BTreeMap::new();
for (_, ty) in func.params.iter() {
self.iter_resources(ty, &mut resource_map);
}
if let Some(ty) = func.result {
self.iter_resources(&ty, &mut resource_map);
}
resource_map
}
fn iter_resources(&self, ty: &Type, map: &mut ResourceMap) {
let Type::Id(id) = ty else { return };
match &self.resolve.types[*id].kind {
TypeDefKind::Flags(_) | TypeDefKind::Enum(_) => {}
TypeDefKind::Record(ty) => {
for field in ty.fields.iter() {
self.iter_resources(&field.ty, map);
}
}
TypeDefKind::Handle(Handle::Own(t) | Handle::Borrow(t)) => {
let resource = js_component_bindgen::dealias(self.resolve, *t);
let abi = self.resource_directions[&resource];
let ty = &self.resolve.types[resource];
let prefix = match &ty.owner {
TypeOwner::World(w) => {
let world = &self.resolve.worlds[*w];
if *w == self.world {
None
} else {
Some(format!("$world${}$", world.name.to_lower_camel_case()))
}
}
TypeOwner::Interface(id) => {
interface_name(self.resolve, *id).map(|s| format!("{s}$"))
}
TypeOwner::None => unreachable!(),
};
map.insert(
resource,
ResourceTable {
imported: abi == AbiVariant::GuestImport,
data: ResourceData::Guest {
resource_name: ty.name.clone().unwrap(),
prefix,
},
},
);
}
TypeDefKind::Tuple(t) => {
for ty in t.types.iter() {
self.iter_resources(ty, map);
}
}
TypeDefKind::Variant(t) => {
for case in t.cases.iter() {
if let Some(ty) = &case.ty {
self.iter_resources(ty, map);
}
}
}
TypeDefKind::Option(ty) => {
self.iter_resources(ty, map);
}
TypeDefKind::Result(ty) => {
if let Some(ty) = &ty.ok {
self.iter_resources(ty, map);
}
if let Some(ty) = &ty.err {
self.iter_resources(ty, map);
}
}
TypeDefKind::List(ty) => {
self.iter_resources(ty, map);
}
TypeDefKind::Type(ty) => {
self.iter_resources(ty, map);
}
_ => unreachable!(),
}
}
fn bindgen(
&mut self,
nparams: usize,
callee: &str,
string_encoding: StringEncoding,
func: &Function,
abi: AbiVariant,
) {
self.src.push_str("(");
let mut params = Vec::new();
for i in 0..nparams {
if i > 0 {
self.src.push_str(", ");
}
let param = format!("arg{i}");
self.src.push_str(¶m);
params.push(param);
}
uwriteln!(self.src, ") {{");
let resource_map = self.create_resource_map(func);
for (id, table) in &resource_map {
if table.imported {
self.imported_resources.insert(*id);
}
}
let err = if get_result_types(self.resolve, func.result).is_some() {
match abi {
AbiVariant::GuestExport => ErrHandling::ThrowResultErr,
AbiVariant::GuestImport => ErrHandling::ResultCatchHandler,
AbiVariant::GuestImportAsync => todo!(),
AbiVariant::GuestExportAsync => todo!(),
AbiVariant::GuestExportAsyncStackful => todo!(),
}
} else {
ErrHandling::None
};
let mut f = FunctionBindgen {
is_async: false,
tracing_prefix: None,
intrinsics: &mut self.all_intrinsics,
valid_lifting_optimization: true,
sizes: &self.sizes,
err,
block_storage: Vec::new(),
blocks: Vec::new(),
callee,
memory: Some(&self.memory),
realloc: Some(&self.realloc),
tmp: 0,
params,
post_return: None,
encoding: match string_encoding {
StringEncoding::UTF8 => StringEncoding::UTF8,
StringEncoding::UTF16 => todo!("UTF16 encoding"),
StringEncoding::CompactUTF16 => todo!("Compact UTF16 encoding"),
},
src: Source::default(),
resource_map: &resource_map,
cur_resource_borrows: false,
resolve: self.resolve,
callee_resource_dynamic: false,
};
abi::call(
self.resolve,
abi,
match abi {
AbiVariant::GuestImport => LiftLower::LiftArgsLowerResults,
AbiVariant::GuestExport => LiftLower::LowerArgsLiftResults,
AbiVariant::GuestImportAsync => todo!(),
AbiVariant::GuestExportAsync => todo!(),
AbiVariant::GuestExportAsyncStackful => todo!(),
},
func,
&mut f,
false,
);
self.src.push_str(&f.src);
self.src.push_str("}");
}
fn export_bindgen(
&mut self,
name: String,
iface: bool,
iface_name: Option<String>,
callee: &str,
string_encoding: StringEncoding,
func: &Function,
) {
let fn_name = func.item_name();
let fn_camel_name = fn_name.to_lower_camel_case();
let (resource, callee) = match &func.kind {
FunctionKind::Freestanding => (Resource::None, callee.to_string()),
FunctionKind::Method(ty) => (
Resource::Method(self.resolve.types[*ty].name.clone().unwrap()),
format!("{callee}.prototype.{fn_camel_name}.call"),
),
FunctionKind::Static(ty) => (
Resource::Static(self.resolve.types[*ty].name.clone().unwrap()),
format!("{callee}.{fn_camel_name}"),
),
FunctionKind::Constructor(ty) => (
Resource::Constructor(self.resolve.types[*ty].name.clone().unwrap()),
format!("new {callee}"),
),
FunctionKind::AsyncFreestanding => todo!(),
FunctionKind::AsyncMethod(_id) => todo!(),
FunctionKind::AsyncStatic(_id) => todo!(),
};
let binding_name = format!(
"export_{}",
binding_name(&resource.func_name(fn_name), &iface_name)
);
// all exports are supported as async functions
uwrite!(self.src, "\nasync function {binding_name}");
// exports are canonicalized as imports because
// the function bindgen as currently written still makes this assumption
let sig = self.resolve.wasm_signature(AbiVariant::GuestImport, func);
self.bindgen(
sig.params.len(),
&format!("await {callee}"),
string_encoding,
func,
AbiVariant::GuestImport,
);
self.src.push_str("\n");
// populate core function return info for splicer
self.exports.push((
name,
BindingItem {
iface,
binding_name,
iface_name,
name: fn_name.to_string(),
resource,
func: self.core_fn(
func,
&self.resolve.wasm_signature(AbiVariant::GuestExport, func),
),
},
));
}
fn core_fn(&self, func: &Function, sig: &WasmSignature) -> CoreFn {
CoreFn {
retsize: if sig.retptr {
let mut retsize: u32 = 0;
if let Some(ret_ty) = func.result {
retsize += self.sizes.size(&ret_ty).size_wasm32() as u32;
}