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
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Error, ItemFn};
#[proc_macro_attribute]
pub fn vlugin(_attr: TokenStream, item: TokenStream) -> TokenStream {
let item: proc_macro2::TokenStream = item.into();
if let Ok(func) = syn::parse2::<ItemFn>(item.clone()) {
let is_pub = |f: &ItemFn| match f.vis {
syn::Visibility::Public(_) => true,
_ => false,
};
if func.sig.asyncness.is_none() || !is_pub(&func) {
return Error::new(
func.sig.fn_token.span,
"Function neeeds to be \"pub async\"",
)
.to_compile_error()
.into();
}
let name = &func.sig.ident;
match name.to_string().as_str() {
"on_create" | "on_request" => {}
_ => {
return Error::new(
name.span(),
"Function should either be named \"on_create\" or \"on_request\"",
)
.to_compile_error()
.into()
}
};
let module: TokenStream2 = quote! {
mod v {
include!(concat!(env!("OUT_DIR"), "/vlugin.rs"));
}
#[cfg(not(target_arch = "wasm32"))]
#[no_mangle]
pub extern "Rust" fn instantiate_vlugin(cfg: Option<valor::VluginConfig>) -> core::pin::Pin<Box<
dyn core::future::Future<Output = Result<Box<dyn valor::Vlugin>, valor::Error>>
>> {
Box::pin(async {
let instance = v::Vlugin::create(cfg).await?;
Ok(Box::new(instance) as Box<dyn valor::Vlugin>)
})
}
#item
};
module.into()
} else {
Error::new(
proc_macro2::Span::mixed_site(),
"Can only annotate functions",
)
.to_compile_error()
.into()
}
}