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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
//! Macros that help define communication between a wasm blob and its
//! rust host.
//!
//! All the types are being exchanged bincode-encoded. If multiple
//! parameters are to be taken, they are exchanged as a
//! bincode-encoded tuple.
//!
//! `&mut` references taken as arguments are taken as though they were
//! by value, and then returned as supplementary arguments in a tuple.
//!
//! Note: this crate's guest-side implementation is very heavily tied
//! to the `kannader_config` crate's implementation. This is on
//! purpose and the two crates should be used together. They are split
//! only for technical reasons.

// The functions are all implemented in wasm with:
//
// Parameters: (address, size) of the allocated block containing
// the serialized message. Ownership is passed to the called
// function.
//
// Return: u64 whose upper 32 bits are the size and lower 32 bits
// the address of a block containing the serialized message.
// Ownership is passed to the caller function.

// TODO: this all should be auto-generated by wasm-bindgen, wasm
// interface types, wiggle or similar

use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;

const SETUP_FN: fn() -> Function = || Function {
    ffi_name: Ident::new("setup", Span::call_site()),
    fn_name: Ident::new("setup", Span::call_site()),
    args: vec![Argument {
        name: Ident::new("path", Span::call_site()),
        is_mut: false,
        ty: quote!(std::path::PathBuf),
    }],
    ret: quote!(()),
    terminator: quote!(;),
};

#[proc_macro]
pub fn implement_guest(input: TokenStream) -> TokenStream {
    let cfg = syn::parse_macro_input!(input as Ident);
    let ffi_body = run_ffi_fn(
        &SETUP_FN(),
        quote!(std::slice::from_raw_parts(ptr as *const u8, size)),
        quote!(deallocate(ptr, size)),
        |args| {
            quote! {
                KANNADER_CFG.with(|cfg| {
                    assert!(cfg.borrow().is_none());
                    *cfg.borrow_mut() = Some(<#cfg as kannader_config::Config>::setup(#args));
                })
            }
        },
        |size| {
            quote! {{
                assert!(#size == 0, "‘setup’ tried to return a non-empty result");
                (0, (&mut []) as &mut [u8])
            }}
        },
    );
    let res = quote! {
        pub fn main() {}

        #[no_mangle]
        pub unsafe extern "C" fn allocate(size: usize) -> usize {
            // TODO: handle alloc error (ie. null return) properly (trap?)
            unsafe {
                std::alloc::alloc(std::alloc::Layout::from_size_align_unchecked(size, 8)) as usize
            }
        }

        #[no_mangle]
        pub unsafe extern "C" fn deallocate(ptr: usize, size: usize) {
            unsafe {
                std::alloc::dealloc(
                    ptr as *mut u8,
                    std::alloc::Layout::from_size_align_unchecked(size, 8),
                )
            }
        }

        std::thread_local! {
            static KANNADER_CFG: std::cell::RefCell<Option<#cfg>> =
                std::cell::RefCell::new(None);
        }

        #[no_mangle]
        pub unsafe extern "C" fn setup(ptr: usize, size: usize) -> u64 {
            #ffi_body
        }

        #[allow(unused)]
        fn DID_YOU_CALL_implement_guest_MACRO() {
            DID_YOU_CALL_client_config_implement_guest_server_MACRO();
            DID_YOU_CALL_queue_config_implement_guest_server_MACRO();
            DID_YOU_CALL_server_config_implement_guest_server_MACRO();
        }
    };
    res.into()
}

#[proc_macro]
pub fn implement_host(_input: TokenStream) -> TokenStream {
    let fn_body = call_ffi_fn(
        &SETUP_FN(),
        quote!(memory.data_ptr(&mut *ctx)),
        quote!(memory.data_size(&mut *ctx)),
        |s| quote!(allocate.call(&mut *ctx, #s)),
        |p, s| quote!(wasm_fun.call(&mut *ctx, (#p, #s))),
        |_, s| {
            quote! {{
                if #s == 0 {
                    Ok(())
                } else {
                    Err(anyhow::Error::msg("‘setup’ tried to return a non-empty result"))
                }
            }}
        },
    );
    let res = quote! {
        use std::{path::Path, rc::Rc};

        use anyhow::{anyhow, ensure, Context};

        // TODO: take struct name as argument instead of forcing the caller to put in a
        // mod (and same below)
        // TODO: factor code out with the below similar code to serialize the argument
        // TODO: make sure we deallocate the buffers in case any error happens (note
        // however that currently wasm supports only panic=abort which generates a trap,
        // so handling panics in wasm properly must be left for later when this is fixed
        // upstream)
        pub fn setup(
            path: &Path,
            ctx: &mut wasmtime::Store<WasmState>,
            linker: &wasmtime::Linker<WasmState>,
        ) -> anyhow::Result<()> {
            let allocate = ctx.data().alloc.unwrap();

            // Recover memory instance
            let memory = linker
                .get(&mut *ctx, "config", "memory")
                .context("Looking for an export for ‘memory’")?
                .into_memory()
                .ok_or_else(|| anyhow!("Export for ‘memory’ is not a memory"))?;

            // Recover setup function
            let wasm_fun: wasmtime::TypedFunc<(u32, u32), u64> = linker
                .get(&mut *ctx, "config", "setup")
                .context("Looking for an export for ‘setup’")?
                .into_func()
                .ok_or_else(|| anyhow!("Export for ‘setup’ is not a function"))?
                .typed(&mut *ctx)
                .with_context(|| format!("Checking the type of ‘setup’"))?;

            #fn_body
        }
    };
    res.into()
}

struct Communicator {
    trait_name: Ident,
    link_name: Ident,
    guest_type: Ident,
    funcs: Vec<Function>,
}

struct Function {
    ffi_name: Ident,
    fn_name: Ident,
    args: Vec<Argument>,
    ret: proc_macro2::TokenStream,
    terminator: proc_macro2::TokenStream,
}

struct Argument {
    name: Ident,
    is_mut: bool,
    ty: proc_macro2::TokenStream,
}

enum TraitType {
    OnGuest,
    OnHost,
}

fn make_trait(trait_type: TraitType, c: Communicator) -> TokenStream {
    let trait_name = c.trait_name;
    let cfg_type_def = match trait_type {
        #[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/4631
        TraitType::OnGuest => quote!(type Cfg: Config;),
        TraitType::OnHost => quote!(),
    };
    let first_param = match trait_type {
        TraitType::OnGuest => quote!(cfg: &Self::Cfg),
        TraitType::OnHost => quote!(self: Arc<Self>),
    };
    let funcs = c.funcs.into_iter().map(|f| {
        let fn_name = f.fn_name;
        let ret = f.ret;
        let terminator = f.terminator;
        let args = f.args.into_iter().map(|Argument { name, is_mut, ty }| {
            if is_mut {
                quote!(#name: &mut #ty)
            } else {
                quote!(#name: #ty)
            }
        });
        quote! {
            #[allow(unused_variables)]
            fn #fn_name(#first_param, #(#args),*) -> #ret
                #terminator
        }
    });
    let res = quote! {
        pub trait #trait_name {
            #cfg_type_def

            #(#funcs)*
        }
    };
    res.into()
}

fn make_guest_server(impl_name: Ident, c: Communicator) -> TokenStream {
    let trait_name = c.trait_name;
    let did_you_call_fn_name = quote::format_ident!(
        "DID_YOU_CALL_{}_implement_{}_MACRO",
        c.link_name,
        c.guest_type
    );
    let funcs = c.funcs.iter().map(|f| -> proc_macro2::TokenStream {
        let ffi_name = &f.ffi_name;
        let fn_name = &f.fn_name;
        let ffi_body = run_ffi_fn(
            f,
            quote!(std::slice::from_raw_parts(arg_ptr as *const u8, arg_size)),
            quote!(deallocate(arg_ptr, arg_size)),
            |args| {
                quote! {
                    KANNADER_CFG.with(|cfg| {
                        <#impl_name as kannader_config::#trait_name>::#fn_name(
                            cfg.borrow().as_ref().unwrap(),
                            #args
                        )
                    })
                }
            },
            |size| {
                quote! {{
                    let ptr: usize = allocate(#size as usize);
                    let slice = std::slice::from_raw_parts_mut(ptr as *mut u8, #size as usize);
                    (ptr, slice)
                }}
            },
        );
        quote! {
            // TODO: handle errors properly (but what does “properly”
            // exactly mean here? anyway, probably not `.unwrap()` /
            // `assert!`...) (and above in the file too)
            #[no_mangle]
            pub unsafe extern "C" fn #ffi_name(arg_ptr: usize, arg_size: usize) -> u64 {
                #ffi_body
            }
        }
    });
    let res = quote! {
        #(#funcs)*

        #[allow(unused)]
        fn #did_you_call_fn_name() {
            DID_YOU_CALL_implement_guest_MACRO();
        }
    };
    res.into()
}

fn make_host_client(struct_name: Ident, c: Communicator) -> TokenStream {
    let func_defs = c.funcs.iter().map(|f| {
        let fn_name = &f.fn_name;
        let ret = &f.ret;
        let args = f.args.iter().map(|a| {
            let ty = &a.ty;
            if a.is_mut {
                quote!(&mut #ty)
            } else {
                quote!(#ty)
            }
        });
        quote! {
            pub #fn_name: Box<dyn Fn(&mut wasmtime::Store<WasmState> #(, #args)*) -> anyhow::Result<#ret>>,
        }
    });
    let func_gets = c.funcs.iter().map(|f| {
        let fn_name = &f.fn_name;
        let ffi_name_str = format!("{}", f.ffi_name);
        let host_args = f.args.iter().map(|Argument { name, is_mut, ty }| {
            if *is_mut {
                quote!(#name: &mut #ty)
            } else {
                quote!(#name: #ty)
            }
        });
        let looking_for_export = format!("Looking for an export for ‘{}’", f.ffi_name);
        let export_is_not_function = format!("Export for ‘{}’ is not a function", f.ffi_name);
        let checking_type = format!("Checking the type of ‘{}’", f.ffi_name);
        let fn_body = call_ffi_fn(
            f,
            quote!(memory.data_ptr(&mut *ctx)),
            quote!(memory.data_size(&mut *ctx)),
            |s| quote!(allocate.call(&mut *ctx, #s)),
            |p, s| quote!(wasm_fun.call(&mut *ctx, (#p, #s))),
            |p, s| quote!(deallocate.call(&mut *ctx, (#p, #s))),
        );
        quote! {
            let #fn_name = {
                let memory = memory.clone();
                let allocate = ctx.data().alloc.unwrap();
                let deallocate = ctx.data().dealloc.unwrap();

                let wasm_fun: wasmtime::TypedFunc<(u32, u32), u64> = linker
                    .get(&mut *ctx, "config", #ffi_name_str)
                    .context(#looking_for_export)?
                    .into_func()
                    .ok_or_else(|| anyhow::Error::msg(#export_is_not_function))?
                    .typed(&mut *ctx)
                    .context(#checking_type)?;

                Box::new(move |ctx: &mut wasmtime::Store<WasmState>, #(#host_args),*| {
                    #fn_body
                })
            };
        }
    });
    let func_names = c.funcs.iter().map(|f| &f.fn_name);
    let res = quote! {
        pub struct #struct_name {
            #(#func_defs)*
        }

        impl #struct_name {
            pub fn build(
                ctx: &mut wasmtime::Store<WasmState>,
                linker: &wasmtime::Linker<WasmState>,
            ) -> anyhow::Result<Self> {
                use anyhow::{anyhow, ensure, Context};

                let memory = linker
                    .get(&mut *ctx, "config", "memory")
                    .context("Looking for an export for ‘memory’")?
                    .into_memory()
                    .ok_or_else(|| anyhow!("Export for ‘memory’ is not a memory"))?;

                #(#func_gets)*

                Ok(Self { #(#func_names),* })
            }
        }
    };
    res.into()
}

fn make_guest_client(module_name: Ident, c: Communicator) -> TokenStream {
    let link_name = format!("{}", c.link_name);
    let func_defs = c.funcs.iter().map(|f| {
        let ffi_name = &f.ffi_name;
        quote! {
            pub fn #ffi_name(ptr: u32, size: u32) -> u64;
        }
    });
    let func_impls = c.funcs.iter().map(|f| {
        let ffi_name = &f.ffi_name;
        let fn_name = &f.fn_name;
        let args = f.args.iter().map(|a| {
            let name = &a.name;
            let ty = &a.ty;
            if a.is_mut {
                quote!(#name: &mut #ty)
            } else {
                quote!(#name: #ty)
            }
        });
        let ret = &f.ret;
        let fn_body = call_ffi_fn(
            f,
            quote!(std::ptr::null_mut::<u8>()),
            quote!(usize::MAX),
            |s| quote!(Ok::<_, !>(unsafe { allocate(#s) })),
            |p, s| quote!(Ok::<_, !>(unsafe { private::#ffi_name(#p, #s) })),
            |p, s| quote!(Ok::<_, !>(unsafe { deallocate(#p, #s) })),
        );
        quote! {
            pub fn #fn_name(#(#args),*) -> anyhow::Result<#ret> {
                #fn_body
            }
        }
    });
    let res = quote! {
        pub mod #module_name {
            mod private {
                #[link(wasm_import_module = #link_name)]
                extern "C" {
                    #(#func_defs)*
                }
            }

            extern "C" {
                fn allocate(size: u32) -> u32;
                fn deallocate(ptr: u32, size: u32);
            }

            #(#func_impls)*
        }
    };
    res.into()
}

fn make_host_server(impl_name: Ident, c: Communicator) -> TokenStream {
    let link_name = format!("{}", c.link_name);
    let trait_name = c.trait_name;
    let linker_add = c.funcs.iter().map(|f| {
        let ffi_name = format!("{}", f.ffi_name);
        let fn_name = &f.fn_name;
        let unable_to_find_memory =
            format!("Unable to find ‘memory’ export in ‘{}’ callback", ffi_name);
        let input_slice_oob = format!("Input slice for ‘{}’ callback is out of bounds", ffi_name);
        // TODO: handle errors properly (ie. without panicking hopefully)
        // The below `.borrow().unwrap()` are OK, as the `RefCell`s
        // are unfilled only between adding this function to the
        // linker and actually getting out the allocate function
        let fn_body = run_ffi_fn(
            f,
            quote!(&memory.data(&mut ctx)[p as usize..(p + s) as usize]),
            quote!(ctx.data().dealloc.unwrap().call(&mut ctx, (p, s)).unwrap()),
            |args| quote!(<Self as #trait_name>::#fn_name(this.clone(), #args)),
            |size| {
                quote! {{
                    let ptr: u32 = ctx.data().alloc.unwrap().call(&mut ctx, #size).unwrap();
                    let slice = &mut memory.data_mut(&mut ctx)[ptr as usize..(ptr + #size) as usize];
                    (ptr, slice)
                }}
            },
        );
        quote! {{
            let this = self.clone();

            let the_fn = move |mut ctx: wasmtime::Caller<WasmState>, p: u32, s: u32| {
                let memory = ctx.get_export("memory")
                    .and_then(|m| m.into_memory())
                    .expect(#unable_to_find_memory);

                assert!((p as usize).saturating_add(s as usize) <= memory.data_size(&mut ctx), #input_slice_oob);

                #fn_body
            };

            l.define(#link_name, #ffi_name, wasmtime::Func::wrap(&mut *ctx, the_fn))?;
        }}
    });
    let res = quote! {
        impl #impl_name {
            pub fn add_to_linker(
                self: Arc<Self>,
                ctx: &mut wasmtime::Store<WasmState>,
                l: &mut wasmtime::Linker<WasmState>,
            ) -> anyhow::Result<()> {
                #(#linker_add)*

                Ok(())
            }
        }
    };
    res.into()
}

fn run_ffi_fn<F, Alloc>(
    f: &Function,
    make_arg_slice: proc_macro2::TokenStream,
    do_dealloc: proc_macro2::TokenStream,
    do_the_thing: F,
    do_alloc: Alloc,
) -> proc_macro2::TokenStream
where
    F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream,
    Alloc: Fn(&Ident) -> proc_macro2::TokenStream,
{
    let deserialize_pat = f.args.iter().map(|Argument { name, is_mut, .. }| {
        if *is_mut {
            quote!(mut #name)
        } else {
            quote!(#name)
        }
    });
    let arguments = f.args.iter().map(|Argument { name, is_mut, .. }| {
        if *is_mut {
            quote!(&mut #name)
        } else {
            quote!(#name)
        }
    });
    let result = f.args.iter().filter_map(|a| {
        let name = &a.name;
        if a.is_mut { Some(quote!(#name)) } else { None }
    });
    let do_the_thing = do_the_thing(quote!(#(#arguments),*));
    let do_alloc = do_alloc(&Ident::new("ret_size", Span::call_site()));
    quote! {
        // TODO: handle errors properly too (see the TODO down the file)
        // Deserialize from the argument slice
        let ( #(#deserialize_pat),* ) = bincode::deserialize(#make_arg_slice).unwrap();

        // Deallocate the argument slice
        #do_dealloc;

        // Call the callback
        let res = #do_the_thing;
        let res = (res, #(#result),*);

        // Allocate return buffer
        let ret_size: u64 = bincode::serialized_size(&res).unwrap();
        debug_assert!(
            ret_size <= u32::MAX as u64,
            "Message size above u32::MAX, something is really wrong"
        );
        let ret_size: u32 = ret_size as u32;
        let (ret_ptr, ret_slice) = #do_alloc;

        // Serialize the result to the return buffer
        bincode::serialize_into(ret_slice, &res).unwrap();

        // We know that usize is u32 thanks to the above const_assert
        ((ret_size as u64) << 32) | (ret_ptr as u64)
    }
}

fn call_ffi_fn<Alloc, F, Dealloc>(
    f: &Function,
    memory_base_ptr: proc_macro2::TokenStream,
    memory_size: proc_macro2::TokenStream,
    allocate: Alloc,
    call_the_fn: F,
    deallocate: Dealloc,
) -> proc_macro2::TokenStream
where
    Alloc: Fn(&Ident) -> proc_macro2::TokenStream,
    F: Fn(&Ident, &Ident) -> proc_macro2::TokenStream,
    Dealloc: Fn(proc_macro2::TokenStream, proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
    let arg_size_id = Ident::new("arg_size", Span::call_site());
    let arg_ptr_id = Ident::new("arg_ptr", Span::call_site());

    let encode_args = f.args.iter().map(|Argument { name, .. }| quote!(&#name));
    let figuring_out_size_to_allocate_for_arg_buf = format!(
        "Figuring out size to allocate for argument buffer for ‘{}’",
        f.ffi_name
    );
    let allocate_arg_size = allocate(&arg_size_id);
    let allocating_arg_buf = format!("Allocating argument buffer for ‘{}’", f.ffi_name);
    let serializing_arg_buf = format!("Serializing argument buffer for ‘{}’", f.ffi_name);
    let call_the_fn = call_the_fn(&arg_ptr_id, &arg_size_id);
    let running_wasm_func = format!("Running wasm function ‘{}’", f.ffi_name);
    let returned_alloc_outside_of_memory = format!(
        "Wasm function ‘{}’ returned allocation outside of its memory",
        f.ffi_name,
    );
    let deallocating_ret_buf = format!("Deallocating return buffer for function ‘{}’", f.ffi_name);
    let deserializing_ret_msg = format!("Deserializing return message of ‘{}’", f.ffi_name);
    let result_assignment = f.args.iter().filter_map(|a| {
        let name = &a.name;
        if a.is_mut { Some(quote!(*#name)) } else { None }
    });
    let deallocate_res = deallocate(quote!(res_ptr as u32), quote!(res_size as u32));
    quote! {
        use anyhow::Context;

        // Get the to-be-encoded argument
        let arg = ( #(#encode_args),* );

        // Compute the size of the argument
        let arg_size: u64 = bincode::serialized_size(&arg)
            .context(#figuring_out_size_to_allocate_for_arg_buf)?;
        debug_assert!(
            arg_size <= u32::MAX as u64,
            "Message size above u32::MAX, something is really wrong"
        );
        let arg_size = arg_size as u32;

        // Allocate argument buffer
        let arg_ptr = #allocate_arg_size.context(#allocating_arg_buf)?;
        anyhow::ensure!(
            (arg_ptr as usize).saturating_add(arg_size as usize) <= #memory_size,
            "Wasm allocator returned allocation outside of its memory"
        );

        // Serialize to argument buffer
        let arg_vec = bincode::serialize(&arg).context(#serializing_arg_buf)?;
        debug_assert_eq!(
            arg_size as usize,
            arg_vec.len(),
            "bincode-computed size is {} but actual size is {}",
            arg_size,
            arg_vec.len()
        );
        // TODO: the volatiles here are actually useless, wasm threads
        // are not a thing and will not be a thing with regular
        // memories
        unsafe {
            std::intrinsics::volatile_copy_nonoverlapping_memory(
                #memory_base_ptr.add(arg_ptr as usize),
                arg_vec.as_ptr(),
                arg_size as usize,
            );
        }

        // Call the function
        let res_u64 = #call_the_fn.context(#running_wasm_func)?;
        let res_ptr = (res_u64 & 0xFFFF_FFFF) as usize;
        let res_size = ((res_u64 >> 32) & 0xFFFF_FFFF) as usize;
        anyhow::ensure!(
            res_ptr.saturating_add(res_size) <= #memory_size,
            #returned_alloc_outside_of_memory
        );

        // Recover the return slice
        // TODO: the volatiles here are actually useless, wasm threads
        // are not a thing and will not be a thing with regular
        // memories
        let mut res_msg = vec![0; res_size];
        unsafe {
            std::intrinsics::volatile_copy_nonoverlapping_memory(
                res_msg.as_mut_ptr(),
                #memory_base_ptr.add(res_ptr),
                res_size,
            );
        }

        // Deallocate the return slice
        #deallocate_res.context(#deallocating_ret_buf)?;

        // Read the result
        let res;
        (res, #(#result_assignment),*) = bincode::deserialize(&res_msg)
            .context(#deserializing_ret_msg)?;
        Ok(res)
    }
}

macro_rules! communicator {
    (@is_mut ()) => { false };
    (@is_mut (&mut)) => { true };

    (
        #[communicator(link = $link_name:tt , guest_is = $guest_type:tt)]
        trait $trait_name:ident {
            $(
                fn $fn_name:ident(&self $(,)* $($arg:ident : $mut:tt $ty:ty),* $(,)*) -> ($ret:ty)
                    $terminator:tt
            )+
        }
    ) => {
        || Communicator {
            trait_name: Ident::new(stringify!($trait_name), Span::call_site()),
            link_name: Ident::new($link_name, Span::call_site()),
            guest_type: quote::format_ident!("guest_{}", $guest_type),
            funcs: vec![$(
                Function {
                    ffi_name: quote::format_ident!("{}_{}", $link_name, stringify!($fn_name)),
                    fn_name: Ident::new(stringify!($fn_name), Span::call_site()),
                    ret: quote!($ret),
                    args: vec![$(
                        Argument {
                            name: Ident::new(stringify!($arg), Span::call_site()),
                            is_mut: communicator!(@is_mut $mut),
                            ty: quote!($ty),
                        }
                    ),*],
                    terminator: quote!($terminator),
                }
            ),+],
        }
    };
}

static CLIENT_CONFIG: fn() -> Communicator = communicator! {
    #[communicator(link = "client_config", guest_is = "server")]
    trait ClientConfig {
        fn ehlo_hostname(&self) -> (smtp_message::Hostname) ;

        fn can_do_tls(&self) -> (bool) {
            true
        }

        fn must_do_tls(&self) -> (bool) {
            false
        }

        fn tls_handler(&self) -> (kannader_types::TlsHandler) {
            kannader_types::TlsHandler::Rustls
        }

        fn banner_read_timeout_in_millis(&self) -> (i64) {
            // 5 minutes in ms
            5 * 60 * 1000
        }

        fn command_write_timeout_in_millis(&self) -> (i64) {
            // 5 minutes in ms
            5 * 60 * 1000
        }

        fn ehlo_reply_timeout_in_millis(&self) -> (i64) {
            // 5 minutes in ms
            5 * 60 * 1000
        }

        fn starttls_reply_timeout_in_millis(&self) -> (i64) {
            // 2 minutes in ms
            2 * 60 * 1000
        }

        fn mail_reply_timeout_in_millis(&self) -> (i64) {
            // 5 minutes in ms
            5 * 60 * 1000
        }

        fn rcpt_reply_timeout_in_millis(&self) -> (i64) {
            // 5 minutes in ms
            5 * 60 * 1000
        }

        fn data_init_reply_timeout_in_millis(&self) -> (i64) {
            // 2 minutes in ms
            2 * 60 * 1000
        }

        fn data_block_write_timeout_in_millis(&self) -> (i64) {
            // 3 minutes in ms
            3 * 60 * 1000
        }

        fn data_end_reply_timeout_in_millis(&self) -> (i64) {
            // 10 minutes in ms
            10 * 60 * 1000
        }
    }
};

static QUEUE_CONFIG: fn() -> Communicator = communicator! {
    #[communicator(link = "queue_config", guest_is = "server")]
    trait QueueConfig {
        // TODO: THIS HAS THE CONFUSED DEPUTY PROBLEM! Figure out how
        // to pass the right thing here. For now it's probably not too
        // bad, as it's just configuration anyway.
        fn storage_type(&self) -> (kannader_types::QueueStorage) ;

        fn next_interval(
            &self,
            schedule: () smtp_queue_types::ScheduleInfo,
        ) -> (Option<std::time::Duration>) ;

        fn log_storage_error(
            &self,
            err: () serde_error::Error,
            id: () Option<smtp_queue_types::QueueId>,
        ) -> (()) {
            kannader_config::error!(
                { queue_id: ?id, err: ?anyhow::Error::new(err) },
                "Storage error",
            );
        }

        fn log_found_inflight(&self, inflight: () smtp_queue_types::QueueId) -> (()) {
            // TODO: replace “for a while” with the return of
            // ServerConfig::found_inflight_check_delay()
            kannader_config::warn!(
                { queue_id: ?inflight },
                "Found inflight mail, waiting for a while before sending",
            );
        }

        fn log_found_pending_cleanup(&self, pcm: () smtp_queue_types::QueueId) -> (()) {
            warn!({ queue_id: ?pcm }, "Found mail pending cleanup");
        }

        fn log_queued_mail_vanished(&self, id: () smtp_queue_types::QueueId) -> (()) {
            error!({ queue_id: ?id }, "Queued mail vanished");
        }

        fn log_inflight_mail_vanished(&self, id: () smtp_queue_types::QueueId) -> (()) {
            error!({ queue_id: ?id }, "Inflight mail vanished");
        }

        fn log_pending_cleanup_mail_vanished(&self, id: () smtp_queue_types::QueueId) -> (()) {
            error!({ queue_id: ?id }, "Mail that was pending cleanup vanished");
        }

        fn log_too_big_duration(
            &self,
            id: () smtp_queue_types::QueueId,
            too_big: () std::time::Duration,
            new: () std::time::Duration,
        ) -> (()) {
            error!(
                { queue_id: ?id, too_big: ?too_big, reset_to: ?new },
                "Ended up having too big a duration",
            );
        }

        fn found_inflight_check_delay(&self) -> (std::time::Duration) {
            std::time::Duration::from_secs(3600)
        }

        fn io_error_next_retry_delay(&self, d: () std::time::Duration) -> (std::time::Duration) {
            if d < std::time::Duration::from_secs(30) {
                std::time::Duration::from_secs(60)
            } else {
                d.mul_f64(2.0)
            }
        }
    }
};

static SERVER_CONFIG: fn() -> Communicator = communicator! {
    #[communicator(link = "server_config", guest_is = "server")]
    trait ServerConfig {
        // TODO: THIS HAS THE CONFUSED DEPUTY PROBLEM! Figure out how
        // to not have it. For now it's probably not too bad as it's
        // only calling from config anyway.
        // TODO: also support setting SNI
        fn tls_cert_file(&self) -> (std::path::PathBuf) ;
        fn tls_key_file(&self) -> (std::path::PathBuf) ;

        fn welcome_banner_reply(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply) ;

        fn filter_hello(
            &self,
            is_extended: () bool,
            hostname: () smtp_message::Hostname,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<smtp_server_types::HelloInfo>) ;

        fn can_do_tls(
            &self,
            conn_meta: () smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (bool)
        {
            !conn_meta.is_encrypted &&
                conn_meta.hello.as_ref().map(|h| h.is_extended).unwrap_or(false)
        }

        fn new_mail(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (Vec<u8>) ;

        fn filter_from(
            &self,
            from: () Option<smtp_message::Email>,
            meta: (&mut) smtp_server_types::MailMetadata<Vec<u8>>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<Option<smtp_message::Email>>) ;

        fn filter_to(
            &self,
            to: () smtp_message::Email,
            meta: (&mut) smtp_server_types::MailMetadata<Vec<u8>>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<smtp_message::Email>) ;

        fn filter_data(
            &self,
            meta: (&mut) smtp_server_types::MailMetadata<Vec<u8>>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Accept {
                reply: smtp_server_types::reply::okay_data().convert(),
                res: (),
            }
        }

        fn handle_rset(
            &self,
            meta: (&mut) Option<smtp_server_types::MailMetadata<Vec<u8>>>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Accept {
                reply: smtp_server_types::reply::okay_rset().convert(),
                res: (),
            }
        }

        fn handle_starttls(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            if Self::can_do_tls(cfg, (*conn_meta).clone()) {
                smtp_server_types::SerializableDecision::Accept {
                    reply: smtp_server_types::reply::okay_starttls().convert(),
                    res: (),
                }
            } else {
                smtp_server_types::SerializableDecision::Reject {
                    reply: smtp_server_types::reply::command_not_supported().convert(),
                }
            }
        }

        fn handle_expn(
            &self,
            name: () smtp_message::MaybeUtf8<String>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Reject {
                reply: smtp_server_types::reply::command_unimplemented().convert(),
            }
        }

        fn handle_vrfy(
            &self,
            name: () smtp_message::MaybeUtf8<String>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Accept {
                reply: smtp_server_types::reply::ignore_vrfy().convert(),
                res: (),
            }
        }

        fn handle_help(
            &self,
            subject: () smtp_message::MaybeUtf8<String>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Accept {
                reply: smtp_server_types::reply::ignore_help().convert(),
                res: (),
            }
        }

        fn handle_noop(
            &self,
            string: () smtp_message::MaybeUtf8<String>,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Accept {
                reply: smtp_server_types::reply::okay_noop().convert(),
                res: (),
            }
        }

        fn handle_quit(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_server_types::SerializableDecision<()>)
        {
            smtp_server_types::SerializableDecision::Kill {
                reply: Some(smtp_server_types::reply::okay_quit().convert()),
                res: Ok(()),
            }
        }

        fn already_did_hello(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn mail_before_hello(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn already_in_mail(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn rcpt_before_mail(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn data_before_rcpt(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn data_before_mail(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::bad_sequence().convert()
        }

        fn starttls_unsupported(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::command_not_supported().convert()
        }

        fn command_unrecognized(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::command_unrecognized().convert()
        }

        fn pipeline_forbidden_after_starttls(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::pipeline_forbidden_after_starttls().convert()
        }

        fn line_too_long(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::line_too_long().convert()
        }

        fn handle_mail_did_not_call_complete(
            &self,
            conn_meta: (&mut) smtp_server_types::ConnectionMetadata<Vec<u8>>,
        ) -> (smtp_message::Reply)
        {
            smtp_server_types::reply::handle_mail_did_not_call_complete().convert()
        }

        fn reply_write_timeout_in_millis(&self) -> (i64)
        {
            // 5 minutes in milliseconds
            5 * 60 * 1000
        }

        fn command_read_timeout_in_millis(&self) -> (i64)
        {
            // 5 minutes in milliseconds
            5 * 60 * 1000
        }
    }
};

static TRACING_CONFIG: fn() -> Communicator = communicator! {
    #[communicator(link = "tracing", guest_is = "client")]
    trait TracingConfig {
        fn trace(
            &self,
            meta: () std::collections::HashMap<String, String>,
            msg: () String,
        ) -> (());

        fn debug(
            &self,
            meta: () std::collections::HashMap<String, String>,
            msg: () String,
        ) -> (());

        fn info(
            &self,
            meta: () std::collections::HashMap<String, String>,
            msg: () String,
        ) -> (());

        fn warn(
            &self,
            meta: () std::collections::HashMap<String, String>,
            msg: () String,
        ) -> (());

        fn error(
            &self,
            meta: () std::collections::HashMap<String, String>,
            msg: () String,
        ) -> (());
    }
};

#[proc_macro]
pub fn client_config_implement_trait(_input: TokenStream) -> TokenStream {
    make_trait(TraitType::OnGuest, CLIENT_CONFIG())
}

#[proc_macro]
pub fn client_config_implement_guest_server(input: TokenStream) -> TokenStream {
    let impl_name = syn::parse_macro_input!(input as Ident);
    make_guest_server(impl_name, CLIENT_CONFIG())
}

#[proc_macro]
pub fn client_config_implement_host_client(input: TokenStream) -> TokenStream {
    let struct_name = syn::parse_macro_input!(input as Ident);
    make_host_client(struct_name, CLIENT_CONFIG())
}

#[proc_macro]
pub fn queue_config_implement_trait(_input: TokenStream) -> TokenStream {
    make_trait(TraitType::OnGuest, QUEUE_CONFIG())
}

#[proc_macro]
pub fn queue_config_implement_guest_server(input: TokenStream) -> TokenStream {
    let impl_name = syn::parse_macro_input!(input as Ident);
    make_guest_server(impl_name, QUEUE_CONFIG())
}

#[proc_macro]
pub fn queue_config_implement_host_client(input: TokenStream) -> TokenStream {
    let struct_name = syn::parse_macro_input!(input as Ident);
    make_host_client(struct_name, QUEUE_CONFIG())
}

#[proc_macro]
pub fn server_config_implement_trait(_input: TokenStream) -> TokenStream {
    make_trait(TraitType::OnGuest, SERVER_CONFIG())
}

#[proc_macro]
pub fn server_config_implement_guest_server(input: TokenStream) -> TokenStream {
    let impl_name = syn::parse_macro_input!(input as Ident);
    make_guest_server(impl_name, SERVER_CONFIG())
}

#[proc_macro]
pub fn server_config_implement_host_client(input: TokenStream) -> TokenStream {
    let struct_name = syn::parse_macro_input!(input as Ident);
    make_host_client(struct_name, SERVER_CONFIG())
}

#[proc_macro]
pub fn tracing_implement_trait(_input: TokenStream) -> TokenStream {
    make_trait(TraitType::OnHost, TRACING_CONFIG())
}

#[proc_macro]
pub fn tracing_implement_guest_client(input: TokenStream) -> TokenStream {
    let module_name = syn::parse_macro_input!(input as Ident);
    make_guest_client(module_name, TRACING_CONFIG())
}

#[proc_macro]
pub fn tracing_implement_host_server(input: TokenStream) -> TokenStream {
    let impl_name = syn::parse_macro_input!(input as Ident);
    make_host_server(impl_name, TRACING_CONFIG())
}