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
#![doc(html_root_url = "https://docs.rs/wasm_plugin_guest_derive/0.1.2")]
#![deny(missing_docs)]
use proc_macro::TokenStream;
extern crate proc_macro;
use quote::{format_ident, quote};
use syn;
#[proc_macro_attribute]
pub fn export_function(_args: TokenStream, input: TokenStream) -> TokenStream {
let ast = syn::parse_macro_input!(input as syn::ItemFn);
impl_function_export(&ast)
}
fn impl_function_export(ast: &syn::ItemFn) -> TokenStream {
let name = &ast.sig.ident;
let remote_name = format_ident!("wasm_plugin_exported__{}", name);
let gen = if ast.sig.inputs.is_empty() {
quote! {
#[no_mangle]
pub extern "C" fn #remote_name() -> i32 {
wasm_plugin_guest::write_message(&#name())
}
}
} else {
let mut argument_types = quote!();
let mut call = quote!();
for (i, arg) in ast.sig.inputs.iter().enumerate() {
let i = syn::Index::from(i);
call = quote!(#call message.#i,);
if let syn::FnArg::Typed(t) = arg {
let ty = &t.ty;
argument_types = quote!(#argument_types #ty,);
} else {
panic!();
}
}
quote! {
#[no_mangle]
pub extern "C" fn #remote_name() -> i32 {
let message:(#argument_types) = wasm_plugin_guest::read_message();
wasm_plugin_guest::write_message(&#name(#call))
}
}
};
quote!(#gen #ast).into()
}