-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathinterface.rs
More file actions
3286 lines (3042 loc) · 117 KB
/
interface.rs
File metadata and controls
3286 lines (3042 loc) · 117 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 crate::bindgen::{FunctionBindgen, POINTER_SIZE_EXPRESSION};
use crate::{
ConstructorReturnType, FnSig, Identifier, InterfaceName, Ownership, RuntimeItem, RustFlagsRepr,
RustWasm, TypeGeneration, classify_constructor_return_type, full_wit_type_name, int_repr,
to_rust_ident, to_upper_camel_case, wasm_type,
};
use anyhow::Result;
use heck::*;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::mem;
use wit_bindgen_core::abi::{self, AbiVariant, LiftLower};
use wit_bindgen_core::{
AnonymousTypeGenerator, Source, TypeInfo, dealias, uwrite, uwriteln, wit_parser::*,
};
pub struct InterfaceGenerator<'a> {
pub src: Source,
pub(super) identifier: Identifier<'a>,
pub in_import: bool,
pub sizes: SizeAlign,
pub(super) r#gen: &'a mut RustWasm,
pub wasm_import_module: &'a str,
pub resolve: &'a Resolve,
pub return_pointer_area_size: ArchitectureSize,
pub return_pointer_area_align: Alignment,
pub(super) needs_runtime_module: bool,
pub(super) needs_wit_map: bool,
}
/// A description of the "mode" in which a type is printed.
///
/// Rust types can either be "borrowed" or "owned". This primarily has to do
/// with lists and imports where arguments to imports can be borrowed lists in
/// theory as ownership is not taken from the caller. This structure is used to
/// help with this fact in addition to the various codegen options of this
/// generator. Namely types in WIT can be reflected into Rust as two separate
/// types, one "owned" and one "borrowed" (aka one with `Vec` and one with
/// `&[T]`).
///
/// This structure is used in conjunction with `modes_of` and `type_mode_for*`
/// primarily. That enables creating a programmatic description of what a type
/// is rendered as along with various options.
///
/// Note that a `TypeMode` is a description of a single "level" of a type. This
/// means that there's one mode for `Vec<T>` and one mode for `T` internally.
/// This is mostly used for things like records where some fields have lifetime
/// parameters, for example, and others don't.
///
/// This type is intended to simplify generation of types and encapsulate all
/// the knowledge about whether lifetime parameters are used and how lists are
/// rendered.
///
/// There are currently two users of lifetime parameters:
///
/// * Lists - when borrowed these are rendered as either `&[T]` or `&str`.
/// * Borrowed resources - for resources owned by the current module they're
/// represented as `&T` and for borrows of imported resources they're
/// represented, more-or-less, as `&Resource<T>`.
///
/// Lists have a choice of being rendered as borrowed or not but resources are
/// required to be borrowed.
#[derive(Debug, Copy, Clone, PartialEq)]
struct TypeMode {
/// The lifetime parameter, if any, for this type. If present this type is
/// required to have a lifetime parameter.
lifetime: Option<&'static str>,
/// Whether or not lists are borrowed in this type.
///
/// If this field is `true` then lists are rendered as `&[T]` and `&str`
/// rather than their owned equivalent. If this field is `false` than the
/// owned equivalents are used instead.
lists_borrowed: bool,
/// The "style" of ownership that this mode was created with.
///
/// This information is used to determine what mode the next layer deep int
/// he type tree is rendered with. For example if this layer is owned so is
/// the next layer. This is primarily used for the "OnlyTopBorrowed"
/// ownership style where all further layers beneath that are `Owned`.
style: TypeOwnershipStyle,
}
/// The style of ownership of a type, used to initially create a `TypeMode` and
/// stored internally within it as well.
#[derive(Debug, Copy, Clone, PartialEq)]
enum TypeOwnershipStyle {
/// This style means owned things are printed such as `Vec<T>` and `String`.
///
/// Note that this primarily applies to lists.
Owned,
/// This style means that lists/strings are `&[T]` and `&str`.
///
/// Note that this primarily applies to lists.
Borrowed,
/// This style means that the top-level of a type is borrowed but all other
/// layers are `Owned`.
///
/// This is used for parameters in the "owning" mode of generation to
/// imports. It's easy enough to create a `&T` at the root layer but it's
/// more difficult to create `&T` stored within a `U`, for example.
OnlyTopBorrowed,
}
impl TypeMode {
/// Returns a mode where everything is indicated that it's supposed to be
/// rendered as an "owned" type.
fn owned() -> TypeMode {
TypeMode {
lifetime: None,
lists_borrowed: false,
style: TypeOwnershipStyle::Owned,
}
}
}
impl TypeOwnershipStyle {
/// Preserves this mode except for `OnlyTopBorrowed` where it switches it to
/// `Owned`.
fn next(&self) -> TypeOwnershipStyle {
match self {
TypeOwnershipStyle::Owned => TypeOwnershipStyle::Owned,
TypeOwnershipStyle::Borrowed => TypeOwnershipStyle::Borrowed,
TypeOwnershipStyle::OnlyTopBorrowed => TypeOwnershipStyle::Owned,
}
}
}
enum PayloadFor {
Future,
Stream,
}
impl<'i> InterfaceGenerator<'i> {
pub(super) fn generate_exports<'a>(
&mut self,
interface: Option<(InterfaceId, &WorldKey)>,
funcs: impl Iterator<Item = &'a Function> + Clone,
) -> Result<String> {
let mut traits = BTreeMap::new();
let mut funcs_to_export = Vec::new();
let mut resources_to_drop = Vec::new();
traits.insert(None, ("Guest".to_string(), Vec::new()));
if let Some((id, _)) = interface {
for (name, id) in self.resolve.interfaces[id].types.iter() {
match self.resolve.types[*id].kind {
TypeDefKind::Resource => {}
_ => continue,
}
resources_to_drop.push(name);
let camel = name.to_upper_camel_case();
traits.insert(Some(*id), (format!("Guest{camel}"), Vec::new()));
}
}
for func in funcs {
if self.r#gen.skip.contains(&func.name) {
continue;
}
let async_ = self
.r#gen
.is_async(self.resolve, interface.map(|p| p.1), func, false);
let resource = func.kind.resource();
funcs_to_export.push((func, resource, async_));
let (trait_name, methods) = traits.get_mut(&resource).unwrap();
self.generate_guest_export(func, interface.map(|(_, k)| k), &trait_name, async_);
let prev = mem::take(&mut self.src);
let mut sig = FnSig {
async_,
use_item_name: true,
private: true,
..Default::default()
};
sig.update_for_func(&func);
self.print_signature(func, true, &sig);
self.src.push_str(";\n");
let trait_method = mem::replace(&mut self.src, prev);
methods.push(trait_method);
}
let (name, methods) = traits.remove(&None).unwrap();
if !methods.is_empty() || !traits.is_empty() {
self.generate_interface_trait(
&name,
&methods,
traits
.iter()
.map(|(resource, (trait_name, ..))| (resource.unwrap(), trait_name.as_str())),
)
}
for (resource, (trait_name, methods)) in traits.iter() {
uwriteln!(self.src, "pub trait {trait_name}: 'static {{");
let resource = resource.unwrap();
let resource_name = self.resolve.types[resource].name.as_ref().unwrap();
let (_, interface_name) = interface.unwrap();
let module = self.resolve.name_world_key(interface_name);
let wasm_import_module = format!("[export]{module}");
let import_new = crate::declare_import(
&wasm_import_module,
&format!("[resource-new]{resource_name}"),
"new",
&[abi::WasmType::Pointer],
&[abi::WasmType::I32],
);
let import_rep = crate::declare_import(
&wasm_import_module,
&format!("[resource-rep]{resource_name}"),
"rep",
&[abi::WasmType::I32],
&[abi::WasmType::Pointer],
);
uwriteln!(
self.src,
r#"
#[doc(hidden)]
unsafe fn _resource_new(val: *mut u8) -> u32
where Self: Sized
{{
{import_new}
unsafe {{ new(val) as u32 }}
}}
#[doc(hidden)]
fn _resource_rep(handle: u32) -> *mut u8
where Self: Sized
{{
{import_rep}
unsafe {{ rep(handle as i32) }}
}}
"#
);
for method in methods {
self.src.push_str(method);
}
uwriteln!(self.src, "}}");
}
let macro_name = match interface {
None => {
let world = match self.identifier {
Identifier::World(w) => w,
Identifier::Interface(..) | Identifier::StreamOrFuturePayload => unreachable!(),
};
let world = self.resolve.worlds[world].name.to_snake_case();
format!("__export_world_{world}_cabi")
}
Some((_, name)) => {
format!(
"__export_{}_cabi",
self.resolve
.name_world_key(name)
.to_snake_case()
.chars()
.map(|c| if !c.is_alphanumeric() { '_' } else { c })
.collect::<String>()
)
}
};
let (macro_export, use_vis) = if self.r#gen.opts.pub_export_macro {
("#[macro_export]", "pub")
} else {
("", "pub(crate)")
};
uwriteln!(
self.src,
"\
#[doc(hidden)]
{macro_export}
macro_rules! {macro_name} {{
($ty:ident with_types_in $($path_to_types:tt)*) => (const _: () = {{
"
);
for (func, resource, async_) in funcs_to_export {
let ty = match resource {
None => "$ty".to_string(),
Some(id) => {
let name = self.resolve.types[id]
.name
.as_ref()
.unwrap()
.to_upper_camel_case();
format!("<$ty as $($path_to_types)*::Guest>::{name}")
}
};
self.generate_raw_cabi_export(func, &ty, "$($path_to_types)*", async_);
}
let export_prefix = self.r#gen.opts.export_prefix.as_deref().unwrap_or("");
for name in resources_to_drop {
let module = match self.identifier {
Identifier::Interface(_, key) => self.resolve.name_world_key(key),
Identifier::World(_) | Identifier::StreamOrFuturePayload => {
unreachable!()
}
};
let camel = name.to_upper_camel_case();
uwriteln!(
self.src,
r#"
const _: () = {{
#[doc(hidden)]
#[unsafe(export_name = "{export_prefix}{module}#[dtor]{name}")]
#[allow(non_snake_case)]
unsafe extern "C" fn dtor(rep: *mut u8) {{
unsafe {{
$($path_to_types)*::{camel}::dtor::<
<$ty as $($path_to_types)*::Guest>::{camel}
>(rep)
}}
}}
}};
"#
);
}
uwriteln!(self.src, "}};);");
uwriteln!(self.src, "}}");
uwriteln!(self.src, "#[doc(hidden)]");
uwriteln!(self.src, "{use_vis} use {macro_name};");
Ok(macro_name)
}
fn generate_interface_trait<'a>(
&mut self,
trait_name: &str,
methods: &[Source],
resource_traits: impl Iterator<Item = (TypeId, &'a str)>,
) {
uwriteln!(self.src, "pub trait {trait_name} {{");
for (id, trait_name) in resource_traits {
let name = self.resolve.types[id]
.name
.as_ref()
.unwrap()
.to_upper_camel_case();
uwriteln!(self.src, "type {name}: {trait_name};");
}
for method in methods {
self.src.push_str(method);
}
uwriteln!(self.src, "}}");
}
pub fn generate_imports<'a>(
&mut self,
funcs: impl Iterator<Item = &'a Function>,
interface: Option<&WorldKey>,
) {
for func in funcs {
self.generate_guest_import(func, interface);
}
}
pub fn align_area(&mut self, alignment: Alignment) {
match alignment {
Alignment::Pointer => uwriteln!(
self.src,
"#[cfg_attr(target_pointer_width=\"64\", repr(align(8)))]
#[cfg_attr(target_pointer_width=\"32\", repr(align(4)))]"
),
Alignment::Bytes(bytes) => {
uwriteln!(self.src, "#[repr(align({align}))]", align = bytes.get())
}
}
}
pub fn finish(&mut self) -> String {
if !self.return_pointer_area_size.is_empty() {
uwriteln!(self.src,);
self.align_area(self.return_pointer_area_align);
uwrite!(
self.src,
"struct _RetArea([::core::mem::MaybeUninit::<u8>; {size}]);
static mut _RET_AREA: _RetArea = _RetArea([::core::mem::MaybeUninit::uninit(); {size}]);
",
size = self.return_pointer_area_size.format_term(POINTER_SIZE_EXPRESSION, true),
);
}
let src = mem::take(&mut self.src).into();
if self.needs_runtime_module {
let root = self.path_to_root();
if !root.is_empty() {
let wit_map_use = if self.needs_wit_map {
format!("use {root}_rt::WitMap;\n")
} else {
String::new()
};
return format!("use {root}_rt;\n{wit_map_use}{src}");
}
}
src
}
pub(crate) fn path_to_root(&self) -> String {
let mut path_to_root = String::new();
match self.identifier {
Identifier::Interface(_, key) => {
// Escape the submodule for this interface
path_to_root.push_str("super::");
// Escape the `exports` top-level submodule
if !self.in_import {
path_to_root.push_str("super::");
}
// Escape the namespace/package submodules for interface-based ids
match key {
WorldKey::Name(_) => {}
WorldKey::Interface(_) => {
path_to_root.push_str("super::super::");
}
}
}
Identifier::StreamOrFuturePayload => path_to_root.push_str("super::super::"),
_ => {}
}
path_to_root
}
pub fn start_append_submodule(&mut self, name: &WorldKey) -> (String, Vec<String>) {
let snake = match name {
WorldKey::Name(name) => to_rust_ident(name),
WorldKey::Interface(id) => {
to_rust_ident(self.resolve.interfaces[*id].name.as_ref().unwrap())
}
};
let module_path = crate::compute_module_path(name, &self.resolve, !self.in_import);
(snake, module_path)
}
pub fn finish_append_submodule(mut self, snake: &str, module_path: Vec<String>, docs: &Docs) {
let module = self.finish();
self.rustdoc(docs);
let docs = mem::take(&mut self.src).to_string();
let docs = docs.trim_end();
let path_to_root = self.path_to_root();
let used_static = if self.r#gen.opts.disable_custom_section_link_helpers {
String::new()
} else {
format!(
"\
#[used]
#[doc(hidden)]
static __FORCE_SECTION_REF: fn() =
{path_to_root}__link_custom_section_describing_imports;
"
)
};
let module = format!(
"\
{docs}
#[allow(dead_code, async_fn_in_trait, unused_imports, clippy::all)]
pub mod {snake} {{
{used_static}
{module}
}}
",
);
let map = if self.in_import {
&mut self.r#gen.import_modules
} else {
&mut self.r#gen.export_modules
};
map.push((module, module_path))
}
fn generate_payloads(&mut self, prefix: &str, func: &Function, interface: Option<&WorldKey>) {
let old_identifier = mem::replace(&mut self.identifier, Identifier::StreamOrFuturePayload);
for (index, ty) in func
.find_futures_and_streams(self.resolve)
.into_iter()
.enumerate()
{
let module = format!(
"{prefix}{}",
interface
.map(|name| self.resolve.name_world_key(name))
.unwrap_or_else(|| "$root".into())
);
let func_name = &func.name;
match &self.resolve.types[ty].kind {
TypeDefKind::Future(payload_type) => {
self.generate_payload(
PayloadFor::Future,
&module,
index,
func_name,
payload_type.as_ref(),
);
}
TypeDefKind::Stream(payload_type) => {
self.generate_payload(
PayloadFor::Stream,
&module,
index,
func_name,
payload_type.as_ref(),
);
}
_ => unreachable!(),
}
}
self.identifier = old_identifier;
}
fn generate_payload(
&mut self,
payload_for: PayloadFor,
module: &str,
index: usize,
func_name: &str,
payload_type: Option<&Type>,
) {
// Rust requires one-impl-per-type, so any `id` here is transformed
// into its canonical representation using
// `get_representative_type`. This ensures that type aliases, uses,
// etc, all get canonicalized to the exact same ID regardless of
// type structure. This canonical key is used for deduplication only.
//
// Note that `get_representative_type` maps ids-to-ids which is 95%
// of what we want, but this additionally goes one layer further to
// see if the final id is actually itself a typedef, which would
// always be to a primitive, and then uses the primitive type
// instead of the typedef to canonicalize with other streams/futures
// using the primitive type.
let canonical_payload = match payload_type {
Some(Type::Id(id)) => {
let id = self.r#gen.types.get_representative_type(*id);
match self.resolve.types[id].kind {
TypeDefKind::Type(t) => Some(t),
_ => Some(Type::Id(id)),
}
}
other => other.copied(),
};
{
let map = match payload_for {
PayloadFor::Future => &self.r#gen.future_payloads,
PayloadFor::Stream => &self.r#gen.stream_payloads,
};
if map.contains_key(&canonical_payload) {
return;
}
}
// Use the original (non-canonicalized) type for generating the
// type name and code. Since structurally equal types
// resolve to the same Rust type, it doesn't matter which alias
// path we use in the generated `impl`.
let payload_type = match payload_type {
Some(Type::Id(id)) => match self.resolve.types[*id].kind {
TypeDefKind::Type(t) => Some(t),
_ => Some(Type::Id(*id)),
},
other => other.copied(),
};
let payload_type = payload_type.as_ref();
let name = match payload_type {
Some(payload_type) => self.type_name_owned(payload_type),
None => "()".into(),
};
let ordinal = match payload_for {
PayloadFor::Future => self.r#gen.future_payloads.len(),
PayloadFor::Stream => self.r#gen.stream_payloads.len(),
};
let async_support = self.r#gen.async_support_path();
let (size, align) = if let Some(payload_type) = payload_type {
(
self.sizes.size(payload_type),
self.sizes.align(payload_type),
)
} else {
(
ArchitectureSize {
bytes: 0,
pointers: 0,
},
Alignment::default(),
)
};
let size = size.size_wasm32();
let align = align.align_wasm32();
let lift;
let lower;
let dealloc_lists;
if let Some(payload_type) = payload_type {
lift = self.lift_from_memory("ptr", &payload_type, &module);
dealloc_lists = self.deallocate_lists(
std::slice::from_ref(payload_type),
&["ptr".to_string()],
true,
&module,
);
lower = self.lower_to_memory("ptr", "value", &payload_type, &module);
} else {
lift = format!("let _ = ptr;");
lower = format!("let _ = (ptr, value);");
dealloc_lists = format!("let _ = ptr;");
}
let import_prefix = match payload_for {
PayloadFor::Future => "future",
PayloadFor::Stream => "stream",
};
let camel = match payload_for {
PayloadFor::Future => "Future",
PayloadFor::Stream => "Stream",
};
let start_extra = match payload_for {
PayloadFor::Future => "",
PayloadFor::Stream => ", _: usize",
};
let mut lift_fn = format!("unsafe fn lift(ptr: *mut u8) -> {name} {{ {lift} }}");
let mut lower_fn = format!("unsafe fn lower(value: {name}, ptr: *mut u8) {{ {lower} }}");
let mut dealloc_lists_fn =
format!("unsafe fn dealloc_lists(ptr: *mut u8) {{ {dealloc_lists} }}");
let mut lift_arg = "lift";
let mut lower_arg = "lower";
let mut dealloc_lists_arg = "dealloc_lists";
if let PayloadFor::Stream = payload_for {
lift_arg = "lift: Some(lift)";
lower_arg = "lower: Some(lower)";
dealloc_lists_arg = "dealloc_lists: Some(dealloc_lists)";
let is_list_canonical = match payload_type {
Some(ty) => self.is_list_canonical(ty),
None => true,
};
if is_list_canonical {
lift_arg = "lift: None";
lower_arg = "lower: None";
dealloc_lists_arg = "dealloc_lists: None";
lift_fn = String::new();
lower_fn = String::new();
dealloc_lists_fn = String::new();
}
}
// `use` statements to bring every named type reachable from the
// payload into scope of the generated `vtable{ordinal}` module.
//
// Without these, a type like `future<result<R, string>>` where
// `R` is brought in via `use t.{r}` at world level emits
// `-> Result<R, super::super::_rt::String>` inside `vtable1`,
// with `R` unresolved: the composite type is anonymous so no
// owner-qualified path is inserted, and the world-level alias
// `pub type R = ...;` lives two modules up. Importing it here
// makes the bare identifier resolve regardless of how deeply
// nested the payload type is.
let mut type_imports = BTreeSet::new();
if let Some(ty) = payload_type {
collect_named_type_ids(self.resolve, ty, &mut type_imports);
}
let type_imports: String = type_imports
.into_iter()
.map(|id| {
let path = self.type_path(id, /*owned=*/ true);
// `type_path` emits the full `super::super::...::Name`
// when the type is owned by an interface, but falls
// back to a bare name when the owner is a world (the
// `use interface.{T}` alias case). Bare names need the
// `super::super::` prefix to reach the world-level
// `pub type T = ...;` alias at macro root.
let path = if path.starts_with("super::") {
path
} else {
format!("super::super::{path}")
};
format!(" use {path};\n")
})
.collect();
let code = format!(
r#"
#[doc(hidden)]
#[allow(unused_unsafe, unused_imports)]
pub mod vtable{ordinal} {{
{type_imports}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn cancel_write(_: u32) -> u32 {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn cancel_read(_: u32) -> u32 {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn drop_writable(_: u32) {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn drop_readable(_: u32) {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn new() -> u64 {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn start_read(_: u32, _: *mut u8{start_extra}) -> u32 {{ unreachable!() }}
#[cfg(not(target_arch = "wasm32"))]
unsafe extern "C" fn start_write(_: u32, _: *const u8{start_extra}) -> u32 {{ unreachable!() }}
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "{module}")]
unsafe extern "C" {{
#[link_name = "[{import_prefix}-new-{index}]{func_name}"]
fn new() -> u64;
#[link_name = "[{import_prefix}-cancel-write-{index}]{func_name}"]
fn cancel_write(_: u32) -> u32;
#[link_name = "[{import_prefix}-cancel-read-{index}]{func_name}"]
fn cancel_read(_: u32) -> u32;
#[link_name = "[{import_prefix}-drop-writable-{index}]{func_name}"]
fn drop_writable(_: u32);
#[link_name = "[{import_prefix}-drop-readable-{index}]{func_name}"]
fn drop_readable(_: u32);
#[link_name = "[async-lower][{import_prefix}-read-{index}]{func_name}"]
fn start_read(_: u32, _: *mut u8{start_extra}) -> u32;
#[link_name = "[async-lower][{import_prefix}-write-{index}]{func_name}"]
fn start_write(_: u32, _: *const u8{start_extra}) -> u32;
}}
{lift_fn}
{lower_fn}
{dealloc_lists_fn}
pub static VTABLE: {async_support}::{camel}Vtable<{name}> = {async_support}::{camel}Vtable::<{name}> {{
cancel_write,
cancel_read,
drop_writable,
drop_readable,
{dealloc_lists_arg},
layout: unsafe {{
::core::alloc::Layout::from_size_align_unchecked({size}, {align})
}},
{lift_arg},
{lower_arg},
new,
start_read,
start_write,
}};
impl super::{camel}Payload for {name} {{
const VTABLE: &'static {async_support}::{camel}Vtable<Self> = &VTABLE;
}}
}}
"#,
);
let map = match payload_for {
PayloadFor::Future => &mut self.r#gen.future_payloads,
PayloadFor::Stream => &mut self.r#gen.stream_payloads,
};
map.insert(canonical_payload, code);
}
fn generate_guest_import(&mut self, func: &Function, interface: Option<&WorldKey>) {
if self.r#gen.skip.contains(&func.name) {
return;
}
self.generate_payloads("", func, interface);
let async_ = self.r#gen.is_async(self.resolve, interface, func, true);
let mut sig = FnSig {
async_,
..Default::default()
};
if let Some(id) = func.kind.resource() {
let name = self.resolve.types[id].name.as_ref().unwrap();
let name = to_upper_camel_case(name);
uwriteln!(self.src, "impl {name} {{");
sig.use_item_name = true;
sig.update_for_func(&func);
}
self.src.push_str("#[allow(unused_unsafe, clippy::all)]\n");
let params = self.print_signature(func, async_, &sig);
self.src.push_str("{\n");
self.src.push_str("unsafe {\n");
if async_ {
self.generate_guest_import_body_async(&self.wasm_import_module, func, params);
} else {
self.generate_guest_import_body_sync(&self.wasm_import_module, func, params);
}
self.src.push_str("}\n");
self.src.push_str("}\n");
if func.kind.resource().is_some() {
self.src.push_str("}\n");
}
}
fn lower_to_memory(&mut self, address: &str, value: &str, ty: &Type, module: &str) -> String {
let mut f = FunctionBindgen::new(self, Vec::new(), module, true, false);
abi::lower_to_memory(f.r#gen.resolve, &mut f, address.into(), value.into(), ty);
format!("unsafe {{ {} }}", String::from(f.src))
}
fn deallocate_lists(
&mut self,
types: &[Type],
operands: &[String],
indirect: bool,
module: &str,
) -> String {
let mut f = FunctionBindgen::new(self, Vec::new(), module, true, false);
abi::deallocate_lists_in_types(f.r#gen.resolve, types, operands, indirect, &mut f);
format!("unsafe {{ {} }}", String::from(f.src))
}
fn deallocate_lists_and_own(
&mut self,
types: &[Type],
operands: &[String],
indirect: bool,
module: &str,
) -> String {
let mut f = FunctionBindgen::new(self, Vec::new(), module, true, false);
abi::deallocate_lists_and_own_in_types(f.r#gen.resolve, types, operands, indirect, &mut f);
format!("unsafe {{ {} }}", String::from(f.src))
}
fn lift_from_memory(&mut self, address: &str, ty: &Type, module: &str) -> String {
let mut f = FunctionBindgen::new(self, Vec::new(), module, true, false);
let result = abi::lift_from_memory(f.r#gen.resolve, &mut f, address.into(), ty);
format!("unsafe {{ {}\n{result} }}", String::from(f.src))
}
fn generate_guest_import_body_sync(
&mut self,
module: &str,
func: &Function,
params: Vec<String>,
) {
let mut f = FunctionBindgen::new(
self,
params,
module,
false,
self.r#gen.should_return_self(func),
);
abi::call(
f.r#gen.resolve,
AbiVariant::GuestImport,
LiftLower::LowerArgsLiftResults,
func,
&mut f,
false,
);
let FunctionBindgen {
needs_cleanup_list,
src,
import_return_pointer_area_size,
import_return_pointer_area_align,
handle_decls,
..
} = f;
if needs_cleanup_list {
let vec = self.path_to_vec();
uwriteln!(self.src, "let mut cleanup_list = {vec}::new();");
}
assert!(handle_decls.is_empty());
if !import_return_pointer_area_size.is_empty() {
uwriteln!(self.src,);
self.align_area(import_return_pointer_area_align);
uwrite!(
self.src,
"struct RetArea([::core::mem::MaybeUninit::<u8>; {import_return_pointer_area_size}]);
let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); {import_return_pointer_area_size}]);
", import_return_pointer_area_size = import_return_pointer_area_size.format_term(POINTER_SIZE_EXPRESSION, true)
);
}
self.src.push_str(&String::from(src));
}
fn generate_guest_import_body_async(
&mut self,
module: &str,
func: &Function,
mut params: Vec<String>,
) {
let param_tys = func
.params
.iter()
.map(|Param { ty, .. }| *ty)
.collect::<Vec<_>>();
let async_support = self.r#gen.async_support_path();
let sig = self
.resolve
.wasm_signature(AbiVariant::GuestImportAsync, func);
// Generate `type ParamsLower`
//
uwrite!(
self.src,
"
#[derive(Copy, Clone)]
struct ParamsLower(
"
);
let mut params_lower = sig.params.as_slice();
if sig.retptr {
params_lower = ¶ms_lower[..params_lower.len() - 1];
}
for ty in params_lower {
self.src.push_str(wasm_type(*ty));
self.src.push_str(", ");
}
uwriteln!(
self.src,
"
);
unsafe impl Send for ParamsLower {{}}
"
);
uwriteln!(
self.src,
"
use {async_support}::Subtask as _Subtask;
struct _MySubtask<'a> {{ _unused: core::marker::PhantomData<&'a ()> }}
#[allow(unused_parens)]
unsafe impl<'a> _Subtask for _MySubtask<'a> {{
"
);
// Generate `type Params`
uwrite!(self.src, "type Params = (");
for Param { ty, .. } in func.params.iter() {
let mode = self.type_mode_for(ty, TypeOwnershipStyle::Owned, "'a");
self.print_ty(ty, mode);
self.src.push_str(", ");
}
uwriteln!(self.src, ");");
// Generate `type Results`
match func.result {
Some(ty) => {
uwrite!(self.src, "type Results = ");
self.print_ty(&ty, TypeMode::owned());
uwriteln!(self.src, ";");
}
None => {
uwriteln!(self.src, "type Results = ();");
}
}
// Generate `type ParamsLower`
uwrite!(self.src, "type ParamsLower = ParamsLower;");
// Generate `const ABI_LAYOUT`
let mut heap_types = Vec::new();
if sig.indirect_params {
heap_types.extend(param_tys.iter().cloned());
}
heap_types.extend(func.result);
let layout = self.sizes.record(&heap_types);
uwriteln!(
self.src,
r#"
fn abi_layout(&mut self) -> ::core::alloc::Layout {{
unsafe {{
::core::alloc::Layout::from_size_align_unchecked({}, {})
}}
}}
"#,
layout.size.format(POINTER_SIZE_EXPRESSION),
layout.align.format(POINTER_SIZE_EXPRESSION),
);
// Generate `const RESULTS_OFFSET`
let offset = match func.result {
Some(_) => {
let offsets = self.sizes.field_offsets(&heap_types);
offsets.last().unwrap().0.format(POINTER_SIZE_EXPRESSION)
}
None => "0".to_string(),
};
uwriteln!(
self.src,
"fn results_offset(&mut self) -> usize {{ {offset} }}"
);
// Generate `fn call_import`
let import_name = &func.name;
let intrinsic = crate::declare_import(
&module,