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
//! Valor plugin

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Error, ItemFn, ItemStruct};

/// vlugin
#[proc_macro_attribute]
pub fn vlugin(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let ts2: proc_macro2::TokenStream = item.into();

    if let Ok(rslt) = syn::parse2::<ItemFn>(ts2.clone()) {
        return handle_item_fn(rslt).into();
    }

    if let Ok(rslt) = syn::parse2::<ItemStruct>(ts2) {
        return handle_item_struct(rslt).into();
    }

    Error::new(
        proc_macro2::Span::mixed_site(),
        "Only functions and structures that implement `RequestHandler` are currently supported",
    )
    .to_compile_error()
    .into()
}

fn handle_item_fn(item: ItemFn) -> TokenStream2 {
    let name = item.sig.ident.clone();

    let plugin_def = quote! {
        #[cfg(target_arch = "wasm32")]
        use valor::web::{web_sys, wasm_bindgen, wasm_bindgen_futures, into_request, into_js_response};
        #[cfg(target_arch = "wasm32")]
        use wasm_bindgen::prelude::*;

        /// Handler
        #[cfg(target_arch = "wasm32")]
        #[wasm_bindgen]
        pub async fn handler(req: web_sys::Request) -> web_sys::Response {
            let res = crate::#name(into_request(req).await).await;
            into_js_response(res).await
        }

        /// Handler
        #[cfg(not(target_arch = "wasm32"))]
        #[no_mangle]
        pub extern "Rust" fn get_request_handler() -> Box<dyn valor::RequestHandler> {
            Box::new(|req| #name(req))
        }

        #item
    };

    plugin_def
}

fn handle_item_struct(item: ItemStruct) -> TokenStream2 {
    let name = &item.ident;

    let plugin_def = quote! {
        /// Handler
        #[no_mangle]
        pub extern "Rust" fn get_request_handler() -> Box<dyn valor::RequestHandler> {
            Box::new(#name::default())
        }

        #item
    };

    plugin_def
}