-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathinterface.rs
More file actions
1872 lines (1661 loc) · 69.2 KB
/
interface.rs
File metadata and controls
1872 lines (1661 loc) · 69.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 crate::csharp_ident::ToCSharpIdent;
use crate::function::FunctionBindgen;
use crate::function::ResourceInfo;
use crate::world_generator::CSharp;
use heck::ToLowerCamelCase;
use heck::{ToShoutySnakeCase, ToUpperCamelCase};
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Write;
use std::mem;
use std::ops::Deref;
use wit_bindgen_core::abi::LiftLower;
use wit_bindgen_core::{
Direction, InterfaceGenerator as CoreInterfaceGenerator, abi, uwrite, uwriteln,
};
use wit_parser::Param;
use wit_parser::abi::AbiVariant;
use wit_parser::{
Docs, Enum, Flags, FlagsRepr, Function, FunctionKind, Handle, Int, InterfaceId, LiveTypes,
Record, Resolve, Result_, Tuple, Type, TypeDefKind, TypeId, TypeOwner, Variant, WorldKey,
};
pub(crate) struct InterfaceFragment {
pub(crate) csharp_src: String,
pub(crate) csharp_interop_src: String,
pub(crate) stub: String,
pub(crate) direction: Option<Direction>, // Types do not have a direction.
}
pub(crate) struct InterfaceTypeAndFragments {
pub(crate) is_export: bool,
pub(crate) interface_fragments: Vec<InterfaceFragment>,
}
impl InterfaceTypeAndFragments {
pub(crate) fn new(is_export: bool) -> Self {
InterfaceTypeAndFragments {
is_export,
interface_fragments: Vec::<InterfaceFragment>::new(),
}
}
}
pub(crate) struct FutureInfo {
pub name: String,
pub generic_type_name: String,
pub ty: Option<Type>,
}
/// InterfaceGenerator generates the C# code for wit interfaces.
/// It produces types by interface in wit and then generates the interop code
/// by calling out to FunctionGenerator
pub(crate) struct InterfaceGenerator<'a> {
pub(crate) src: String,
pub(crate) csharp_interop_src: String,
pub(crate) stub: String,
pub(crate) csharp_gen: &'a mut CSharp,
pub(crate) resolve: &'a Resolve,
pub(crate) name: &'a str,
pub(crate) direction: Direction,
pub(crate) futures: Vec<FutureInfo>,
pub(crate) streams: Vec<FutureInfo>,
pub(crate) is_world: bool,
}
impl InterfaceGenerator<'_> {
pub fn is_async(kind: &FunctionKind) -> bool {
matches!(
kind,
FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_)
| FunctionKind::AsyncMethod(_)
)
}
pub(crate) fn define_interface_types(&mut self, id: InterfaceId) {
let mut live = LiveTypes::default();
live.add_interface(self.resolve, id);
self.define_live_types(live, id);
}
//TODO: we probably need this for anonymous types outside of an interface...
// fn define_function_types(&mut self, funcs: &[(&str, &Function)]) {
// let mut live = LiveTypes::default();
// for (_, func) in funcs {
// live.add_func(self.resolve, func);
// }
// self.define_live_types(live);
// }
fn define_live_types(&mut self, live: LiveTypes, id: InterfaceId) {
let mut type_names = HashMap::new();
for ty in live.iter() {
// just create c# types for wit anonymous types
let type_def = &self.resolve.types[ty];
if type_names.contains_key(&ty) || type_def.name.is_some() {
continue;
}
let typedef_name = self.type_name(&Type::Id(ty));
let prev = type_names.insert(ty, typedef_name.clone());
assert!(prev.is_none());
// workaround for owner not set on anonymous types, maintain or own map to the owner
self.csharp_gen
.anonymous_type_owners
.insert(ty, TypeOwner::Interface(id));
self.define_anonymous_type(ty, &typedef_name)
}
}
fn define_anonymous_type(&mut self, type_id: TypeId, typedef_name: &str) {
let type_def = &self.resolve().types[type_id];
let kind = &type_def.kind;
// TODO Does c# need this exit?
// // skip `typedef handle_x handle_y` where `handle_x` is the same as `handle_y`
// if let TypeDefKind::Handle(handle) = kind {
// let resource = match handle {
// Handle::Borrow(id) | Handle::Own(id) => id,
// };
// let origin = dealias(self.resolve, *resource);
// if origin == *resource {
// return;
// }
// }
//TODO: what other TypeDefKind do we need here?
match kind {
TypeDefKind::Tuple(t) => self.type_tuple(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Option(t) => self.type_option(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Record(t) => self.type_record(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::List(t) => self.type_list(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Variant(t) => self.type_variant(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Result(t) => self.type_result(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Handle(_) => {
// Handles don't require a separate definition beyond what we already define for the corresponding
// resource types.
}
TypeDefKind::Future(t) => self.type_future(type_id, typedef_name, t, &type_def.docs),
TypeDefKind::Stream(t) => self.type_stream(type_id, typedef_name, t, &type_def.docs),
_ => unreachable!(),
}
}
pub(crate) fn qualifier(&self, when: bool, ty: &TypeId) -> String {
let type_def = &self.resolve.types[*ty];
// anonymous types dont get an owner from wit-parser, so assume they are part of an interface here.
let owner = if let Some(owner_type) = self.csharp_gen.anonymous_type_owners.get(ty) {
*owner_type
} else {
type_def.owner
};
let global_prefix = self.global_if_user_type(&Type::Id(*ty));
if let TypeOwner::Interface(id) = owner {
if let Some(name) = self.csharp_gen.interface_names.get(&id) {
if name != self.name {
return format!("{global_prefix}{name}.");
}
}
}
if when {
let mut name = self.name;
let tmp_name: String;
if self.is_world {
if CSharp::type_is_bidirectional(self.resolve(), ty) {
name = name.rsplitn(2, ".").nth(1).unwrap();
}
// World level types, except resources are always imports.
else if name.ends_with("Exports") && type_def.kind != TypeDefKind::Resource {
tmp_name = Self::replace_last(&name, "Exports", "Imports");
name = &tmp_name;
}
}
format!("{global_prefix}{name}.")
} else {
String::new()
}
}
fn replace_last(haystack: &str, needle: &str, replacement: &str) -> String {
if let Some(pos) = haystack.rfind(needle) {
let mut result =
String::with_capacity(haystack.len() - needle.len() + replacement.len());
result.push_str(&haystack[..pos]);
result.push_str(replacement);
result.push_str(&haystack[pos + needle.len()..]);
result
} else {
haystack.to_string()
}
}
pub(crate) fn add_interface_fragment(self, is_export: bool) {
self.csharp_gen
.interface_fragments
.entry(self.name.to_string())
.or_insert_with(|| InterfaceTypeAndFragments::new(is_export))
.interface_fragments
.push(InterfaceFragment {
csharp_src: self.src,
csharp_interop_src: self.csharp_interop_src,
stub: self.stub,
direction: Some(self.direction),
});
}
pub(crate) fn add_futures_or_streams(
&mut self,
import_module_name: &str,
is_export: bool,
is_future: bool,
) {
// Anything for this future/stream list?
if (is_future && self.futures.is_empty()) || (!is_future && self.streams.is_empty()) {
return;
}
let future_stream_name = if is_future { "Future" } else { "Stream" };
let future_stream_name_lower = future_stream_name.to_lowercase();
let mut bool_non_generic_new_added = false;
let mut bool_generic_new_added = false;
let mut generated_future_types: HashSet<Option<Type>> = HashSet::new();
let (_namespace, interface_name) = &CSharp::get_class_name_from_qualified_name(self.name);
let interop_name = format!("{}Interop", interface_name.strip_prefix("I").unwrap());
let (futures_or_streams, stream_length_param) = if is_future {
(&self.futures, "")
} else {
(&self.streams, ", uint length")
};
for future in futures_or_streams {
// This code originally copied from Rust codegen generate_payload.
// See the rust codegen for the comment - essentially we canonicalize to one per type.
let canonical_payload = match future.ty {
Some(Type::Id(id)) => {
let id = self.csharp_gen.types.get_representative_type(id);
match self.resolve.types[id].kind {
TypeDefKind::Type(t) => Some(t),
_ => Some(Type::Id(id)),
}
}
other => other,
};
{
if generated_future_types.contains(&canonical_payload) {
continue;
}
}
let future_name = &future.name;
let generic_type_name = &future.generic_type_name;
let upper_camel_future_type = generic_type_name.to_upper_camel_case();
uwrite!(
self.csharp_interop_src,
r#"
internal static {future_stream_name}VTable {future_stream_name}VTable{upper_camel_future_type} = new {future_stream_name}VTable()
{{
New = {future_stream_name}New{upper_camel_future_type},
Read = {future_stream_name}Read{upper_camel_future_type},
Write = {future_stream_name}Write{upper_camel_future_type},
DropReader = {future_stream_name}DropReader{upper_camel_future_type},
DropWriter = {future_stream_name}DropWriter{upper_camel_future_type},
}};
"#
);
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[async-lower][{future_stream_name_lower}-read-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static unsafe extern uint {future_stream_name}Read{upper_camel_future_type}(int readable, IntPtr ptr{stream_length_param});
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[async-lower][{future_stream_name_lower}-write-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static unsafe extern uint {future_stream_name}Write{upper_camel_future_type}(int writeable, IntPtr buffer{stream_length_param});
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-drop-readable-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern void {future_stream_name}DropReader{upper_camel_future_type}(int readable);
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-drop-writable-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern void {future_stream_name}DropWriter{upper_camel_future_type}(int readable);
"#
);
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-new-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern ulong {future_stream_name}New{upper_camel_future_type}();
"#
);
// TODO: Move this and other type dependent functions out to another function.
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-cancel-read-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern uint {future_stream_name}CancelRead{upper_camel_future_type}(int readable);
"#
);
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-cancel-write-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern uint {future_stream_name}CancelWrite{upper_camel_future_type}(int writeable);
"#
);
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "[{future_stream_name_lower}-drop-writeable-0]{future_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
internal static extern void {future_stream_name}DropWriteable{upper_camel_future_type}(int writeable);
"#
);
match future.generic_type_name.as_str() {
"" => {
if !bool_non_generic_new_added {
self.csharp_gen
.interface_fragments
.entry(self.name.to_string())
.or_insert_with(|| InterfaceTypeAndFragments::new(is_export))
.interface_fragments
.push(InterfaceFragment {
csharp_src: format!(r#"
internal static ({future_stream_name}Reader, {future_stream_name}Writer) {future_stream_name}New()
{{
return FutureHelpers.Raw{future_stream_name}New({interop_name}.{future_stream_name}VTable);
}}
"#).to_string(),
csharp_interop_src: "".to_string(),
stub: "".to_string(),
direction: Some(self.direction),
});
bool_non_generic_new_added = true;
}
}
_ => {
self.csharp_gen
.interface_fragments
.entry(self.name.to_string())
.or_insert_with(|| InterfaceTypeAndFragments::new(is_export))
.interface_fragments
.push(InterfaceFragment {
csharp_src: format!(r#"
public static ({future_stream_name}Reader<{generic_type_name}>, {future_stream_name}Writer<{generic_type_name}>) {future_stream_name}New{upper_camel_future_type}()
{{
return FutureHelpers.Raw{future_stream_name}New<{generic_type_name}>({interop_name}.{future_stream_name}VTable{upper_camel_future_type});
}}
"#).to_string(),
csharp_interop_src: "".to_string(),
stub: "".to_string(),
direction: Some(self.direction),
});
if !bool_generic_new_added {
self.csharp_gen
.interface_fragments
.entry(self.name.to_string())
.or_insert_with(|| InterfaceTypeAndFragments::new(is_export))
.interface_fragments
.push(InterfaceFragment {
csharp_src: format!(r#"
public static ({future_stream_name}Reader<T>, {future_stream_name}Writer<T>) {future_stream_name}New<T>({future_stream_name}VTable vtable)
{{
return FutureHelpers.Raw{future_stream_name}New<T>(vtable);
}}
"#).to_string(),
csharp_interop_src: "".to_string(),
stub: "".to_string(),
direction: Some(self.direction),
});
bool_generic_new_added = true;
}
}
}
generated_future_types.insert(canonical_payload);
}
self.csharp_gen.needs_async_support = true;
self.csharp_gen
.generated_future_types
.extend(generated_future_types.iter());
}
pub(crate) fn add_world_fragment(self, direction: Option<Direction>) {
self.csharp_gen.world_fragments.push(InterfaceFragment {
csharp_src: self.src,
csharp_interop_src: self.csharp_interop_src,
stub: self.stub,
direction,
});
}
pub(crate) fn import(&mut self, import_module_name: &str, func: &Function) {
let camel_name = match &func.kind {
FunctionKind::Freestanding
| FunctionKind::Static(_)
| FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_) => func.item_name().to_upper_camel_case(),
FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => {
func.item_name().to_upper_camel_case()
}
FunctionKind::Constructor(id) => {
self.csharp_gen.all_resources[id].name.to_upper_camel_case()
}
};
let access = self.csharp_gen.access_modifier();
let modifiers = modifiers(func, &camel_name, Direction::Import);
let interop_camel_name = func.item_name().to_upper_camel_case();
let sig = self.resolve.wasm_signature(AbiVariant::GuestImport, func);
let is_async = matches!(
func.kind,
FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_)
| FunctionKind::AsyncMethod(_)
);
let mut wasm_result_type = match &sig.results[..] {
[] => {
if is_async {
"uint"
} else {
"void"
}
}
[result] => crate::world_generator::wasm_type(*result),
_ => unreachable!(),
};
let (result_type, results) = self.func_payload_and_return_type(func);
let is_async = InterfaceGenerator::is_async(&func.kind);
let requires_async_return_buffer_param = is_async && !sig.results.is_empty();
let sig_unsafe = if requires_async_return_buffer_param {
"unsafe "
} else {
""
};
let wasm_params: String = {
let param_list = sig
.params
.iter()
.enumerate()
.map(|(i, param)| {
let ty = crate::world_generator::wasm_type(*param);
format!("{ty} p{i}")
})
.collect::<Vec<_>>()
.join(", ");
if requires_async_return_buffer_param {
if param_list.is_empty() {
"void *taskResultBuffer".to_string()
} else {
format!("{param_list}, void *taskResultBuffer")
}
} else {
param_list
}
};
let mut funcs: Vec<(String, String)> = Vec::new();
funcs.push(self.gen_import_src(func, &results, ParameterType::ABI));
let include_additional_functions = func
.params
.iter()
.skip(if let FunctionKind::Method(_) = &func.kind {
1
} else {
0
})
.any(|param| self.is_primative_list(¶m.ty));
if include_additional_functions {
funcs.push(self.gen_import_src(func, &results, ParameterType::Span));
funcs.push(self.gen_import_src(func, &results, ParameterType::Memory));
}
let import_name = if is_async {
wasm_result_type = "uint";
format!("[async-lower]{}", func.name)
} else {
func.name.to_string()
};
uwrite!(
self.csharp_interop_src,
r#"
public static class {interop_camel_name}WasmInterop
{{
[global::System.Runtime.InteropServices.DllImportAttribute("{import_module_name}", EntryPoint = "{import_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
public static extern {sig_unsafe}{wasm_result_type} wasmImport{interop_camel_name}({wasm_params});
}}
"#
);
for (src, params) in funcs {
uwrite!(
self.src,
r#"
{access} {modifiers} unsafe {result_type} {camel_name}({params})
{{
{src}
}}
"#
);
}
}
fn func_payload_and_return_type(&mut self, func: &Function) -> (String, Vec<TypeId>) {
let return_type = self.func_return_type(func, true);
let results = if let FunctionKind::Constructor(_) = &func.kind {
Vec::new()
} else {
let payload = match func.result {
None => Vec::new(),
Some(ty) => {
let (_payload, results) = payload_and_results(
self.resolve,
ty,
self.csharp_gen.opts.with_wit_results,
);
results
}
};
payload
};
(return_type, results)
}
fn func_return_type(&mut self, func: &Function, qualifier: bool) -> String {
let result_type = if let FunctionKind::Constructor(_) = &func.kind {
String::new()
} else {
let base_type = match func.result {
None => "void".to_string(),
Some(_ty) => {
let result_type = match func.result {
None => "void".to_string(),
Some(ty) => {
let (payload, _results) = payload_and_results(
self.resolve,
ty,
self.csharp_gen.opts.with_wit_results,
);
if let Some(ty) = payload {
self.csharp_gen.needs_result = true;
self.type_name_with_qualifier(&ty, qualifier)
} else {
"void".to_string()
}
}
};
result_type
}
};
let asyncified_type = match &func.kind {
FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_)
| FunctionKind::AsyncMethod(_) => match func.result {
None => "Task".to_string(),
Some(_ty) => format!("Task<{base_type}>"),
},
_ => base_type,
};
asyncified_type
};
result_type
}
fn gen_import_src(
&mut self,
func: &Function,
results: &Vec<TypeId>,
parameter_type: ParameterType,
) -> (String, String) {
let mut bindgen = FunctionBindgen::new(
self,
&func.item_name(),
&func.kind,
func.params
.iter()
.enumerate()
.map(|(i, Param { name, .. })| {
if i == 0 && matches!(&func.kind, FunctionKind::Method(_)) {
"this".to_owned()
} else {
name.to_csharp_ident()
}
})
.collect(),
results.clone(),
parameter_type,
func.result,
);
let async_ = InterfaceGenerator::is_async(&func.kind);
let mut src: String;
if async_ {
// TODO: Use lower_to_memory as per Go ?
let sig = bindgen
.interface_gen
.resolve
.wasm_signature(AbiVariant::GuestImportAsync, func);
// TODO: the result is a tmp so could be result/1/2/.. Maybe this will fallout if we use lower_to_memory.
let async_status_var = "result"; // String::new();
let requires_async_return_buffer_param = func.result.is_some();
let async_return_buffer = if requires_async_return_buffer_param {
let buffer = bindgen.emit_allocation_for_type(&sig.results);
uwriteln!(
bindgen.src,
"//TODO: store somewhere with the TaskCompletionSource, possibly in the state, using Task.AsyncState to retrieve it later."
);
Some(buffer)
} else {
None
};
let csharp_param_names = func
.params
.iter()
.map(|param| param.name.to_lower_camel_case())
.collect::<Vec<_>>();
let (lower, wasm_params) = if sig.indirect_params {
todo!("indirect params not supported for async imports yet");
} else {
let wasm_params: Vec<String> = csharp_param_names
.iter()
.zip(&func.params)
.flat_map(|(name, param)| {
abi::lower_flat(
bindgen.interface_gen.resolve,
&mut bindgen,
name.clone(),
¶m.ty,
)
})
.collect();
(mem::take(&mut bindgen.src), wasm_params)
};
let name = func.name.to_upper_camel_case();
let raw_name = format!("IImportsInterop.{name}WasmInterop.wasmImport{name}");
let wasm_params = wasm_params
.iter()
.map(|v| v.as_str())
.chain(func.result.map(|_| "address"))
.collect::<Vec<_>>()
.join(", ");
// TODO: lift expr
let code = format!(
"{lower}
var {async_status_var} = {raw_name}({wasm_params});
"
);
src = format!("{code}{}", bindgen.src);
if let Some(buffer) = async_return_buffer {
let ty = bindgen.result_type.expect("expected a result type");
let lift_expr = abi::lift_from_memory(
bindgen.interface_gen.resolve,
&mut bindgen,
buffer.clone(),
&ty,
);
let return_type = self.type_name_with_qualifier(&ty, true);
let lift_func = format!("() => {lift_expr}");
uwriteln!(
src,
"
Console.WriteLine(\"calling TaskFromStatus from func {}\");
var task = AsyncSupport.TaskFromStatus<{return_type}>({async_status_var}, {});",
func.name,
lift_func
);
uwriteln!(
src,
"global::System.Runtime.InteropServices.NativeMemory.Free({});",
buffer
);
uwriteln!(src, "return task;");
} else {
uwriteln!(
src,
"
Console.WriteLine(\"calling TaskFromStatus from func {}\");
return AsyncSupport.TaskFromStatus({async_status_var});",
func.name
);
}
} else {
abi::call(
bindgen.interface_gen.resolve,
AbiVariant::GuestImport,
LiftLower::LowerArgsLiftResults,
func,
&mut bindgen,
false,
);
src = bindgen.src;
}
let params = func
.params
.iter()
.skip(if let FunctionKind::Method(_) = &func.kind {
1
} else {
0
})
.map(|param| {
let ty = self.name_with_qualifier(¶m.ty, true, parameter_type);
let param_name = ¶m.name;
let param_name = param_name.to_csharp_ident();
format!("{ty} {param_name}")
})
.collect::<Vec<_>>()
.join(", ");
(src, params)
}
pub(crate) fn export(&mut self, func: &Function, interface_key: Option<&WorldKey>) {
let camel_name = match &func.kind {
FunctionKind::Freestanding
| FunctionKind::Static(_)
| FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_) => func.item_name().to_upper_camel_case(),
FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => {
func.item_name().to_upper_camel_case()
}
FunctionKind::Constructor(id) => {
self.csharp_gen.all_resources[id].name.to_upper_camel_case()
}
};
let modifiers = modifiers(func, &camel_name, Direction::Export);
let sig = self.resolve.wasm_signature(AbiVariant::GuestExport, func);
let (result_type, results) = self.func_payload_and_return_type(func);
let mut bindgen = FunctionBindgen::new(
self,
&func.item_name(),
&func.kind,
(0..sig.params.len()).map(|i| format!("p{i}")).collect(),
results,
ParameterType::ABI,
func.result,
);
let async_ = matches!(
func.kind,
FunctionKind::AsyncFreestanding
| FunctionKind::AsyncStatic(_)
| FunctionKind::AsyncMethod(_)
);
abi::call(
bindgen.interface_gen.resolve,
AbiVariant::GuestExport,
LiftLower::LiftArgsLowerResults,
func,
&mut bindgen,
async_,
);
let src = bindgen.src;
let resource_type_name = bindgen.resource_type_name;
let vars = bindgen
.resource_drops
.iter()
.map(|(t, v)| format!("{t}? {v} = null;"))
.collect::<Vec<_>>()
.join(";\n");
let wasm_result_type = if async_ {
"uint"
} else {
match &sig.results[..] {
[] => "void",
[result] => crate::world_generator::wasm_type(*result),
_ => unreachable!(),
}
};
let wasm_params = sig
.params
.iter()
.enumerate()
.map(|(i, param)| {
let ty = crate::world_generator::wasm_type(*param);
format!("{ty} p{i}")
})
.collect::<Vec<_>>()
.join(", ");
let (_namespace, _interface_name) = &CSharp::get_class_name_from_qualified_name(self.name);
let params = func
.params
.iter()
.skip(if let FunctionKind::Method(_) = &func.kind {
1
} else {
0
})
.map(|Param { name, ty, .. }| {
let ty = self.type_name_with_qualifier(ty, true);
let name = name.to_csharp_ident();
format!("{ty} {name}")
})
.collect::<Vec<String>>()
.join(", ");
let wasm_func_name = func.name.clone();
let interop_name = format!("wasmExport{}", wasm_func_name.to_upper_camel_case());
let core_module_name = interface_key.map(|s| self.resolve.name_world_key(s));
let export_name = func.legacy_core_export_name(core_module_name.as_deref());
let export_name = if async_ {
format!("[async-lift]{export_name}")
} else {
export_name.to_string()
};
let access = self.csharp_gen.access_modifier();
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute(EntryPoint = "{export_name}")]
{access} static unsafe {wasm_result_type} {interop_name}({wasm_params}) {{
{vars}
{src}
}}
"#
);
if async_ {
uwriteln!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute(EntryPoint = "[callback]{export_name}")]
public static unsafe uint {camel_name}Callback(int eventRaw, uint waitable, uint code)
{{
Console.WriteLine($"Callback with code {{code}}");
EventWaitable e = new EventWaitable((EventCode)eventRaw, waitable, code);
"#
);
// TODO: Get the results from a static dictionary?
if sig.results.len() > 0 {
uwriteln!(
self.csharp_interop_src,
r#"
throw new NotImplementedException("callbacks with parameters are not yet implemented.");
}}
"#
);
} else {
uwriteln!(
self.csharp_interop_src,
r#"
return (uint)AsyncSupport.Callback(e, (ContextTask *)IntPtr.Zero, () => {camel_name}TaskReturn());
}}
"#
);
}
}
if abi::guest_export_needs_post_return(self.resolve, func) {
let params = sig
.results
.iter()
.enumerate()
.map(|(i, param)| {
let ty = crate::world_generator::wasm_type(*param);
format!("{ty} p{i}")
})
.collect::<Vec<_>>()
.join(", ");
let mut bindgen = FunctionBindgen::new(
self,
"INVALID",
&func.kind,
(0..sig.results.len()).map(|i| format!("p{i}")).collect(),
Vec::new(),
ParameterType::ABI,
func.result,
);
abi::post_return(bindgen.interface_gen.resolve, func, &mut bindgen);
let src = bindgen.src;
uwrite!(
self.csharp_interop_src,
r#"
[global::System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute(EntryPoint = "cabi_post_{export_name}")]
{access} static unsafe void cabi_post_{interop_name}({params}) {{
{src}
}}
"#
);
}
if async_ {
let (_namespace, interface_name) =
&CSharp::get_class_name_from_qualified_name(self.name);
let impl_name = if resource_type_name.is_some() {
resource_type_name.unwrap()
} else {
format!("{}Impl", interface_name.strip_prefix("I").unwrap())
};
let (_import_module_prefix, import_module) = match interface_key {
Some(world_key) => {
let interface_world = self.resolve.name_world_key(world_key);
(format!("{interface_world}#"), interface_world)
}
None => (String::new(), "$root".to_string()),
};
let mut interop_class_name = impl_name.replace("Impl", "Interop");
if self.is_world {
interop_class_name = interop_class_name.replace("ExportsInterop", "Interop");
interop_class_name = format!("Exports.{interop_class_name}");
}
// TODO: The task return function can take up to 16 core parameters.
let (task_return_param_sig, task_return_param) = match &sig.results[..] {
[] => (String::new(), String::new()),
[_result] => (format!("{wasm_result_type} result"), "result".to_string()),
_ => unreachable!(),
};
uwriteln!(
self.src,
r#"
public static void {camel_name}TaskReturn({task_return_param_sig} )
{{
{interop_class_name}.{camel_name}TaskReturn({task_return_param});
}}
"#
);
uwriteln!(
self.csharp_interop_src,
r#"
// TODO: The task return function can take up to 16 core parameters.
[global::System.Runtime.InteropServices.DllImportAttribute("[export]{import_module}", EntryPoint = "[task-return]{wasm_func_name}"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
public static extern void {camel_name}TaskReturn({task_return_param_sig});
"#
);
}
if !matches!(&func.kind, FunctionKind::Constructor(_)) {
uwrite!(
self.src,
r#"{modifiers} {result_type} {camel_name}({params});
"#
);
}