logo
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
//! The macros lib of Savlo web server framework. Read more: <https://salvo.rs>
#![doc(html_favicon_url = "https://salvo.rs/images/favicon-32x32.png")]
#![doc(html_logo_url = "https://salvo.rs/images/logo.svg")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(private_in_public, unreachable_pub, unused_crate_dependencies)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro_crate::{crate_name, FoundCrate};
use proc_quote::quote;
use syn::punctuated::Punctuated;
use syn::{parse_macro_input, AttributeArgs, FnArg, Ident, ItemFn, Meta, NestedMeta, ReturnType};

enum InputType {
    Request,
    Depot,
    Response,
    FlowCtrl,
    UnKnow,
    NoReferenceArg,
}

/// `fn_handler` is a pro macro to help create `Handler` from function easily.
///
/// `Handler` is a trait, `fn_handler` will convert you `fn` to a struct, and then implement `Handler`.
///
/// ```ignore
/// #[async_trait]
/// pub trait Handler: Send + Sync + 'static {
///     async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl);
/// }
/// ```
///
/// After use `fn_handler`, you don't need to care arguments' order, omit unused arguments:
///
/// ```ignore
/// #[fn_handler]
/// async fn hello_world() -> &'static str {
///     "Hello World"
/// }
/// ```
#[proc_macro_attribute]
pub fn fn_handler(args: TokenStream, input: TokenStream) -> TokenStream {
    let mut item_fn = parse_macro_input!(input as ItemFn);
    let attrs = &item_fn.attrs;
    let vis = &item_fn.vis;
    let sig = &mut item_fn.sig;
    if sig.inputs.len() > 4 {
        return syn::Error::new_spanned(sig.fn_token, "too many args in handle function")
            .to_compile_error()
            .into();
    }
    if sig.asyncness.is_none() {
        return syn::Error::new_spanned(sig.fn_token, "only async fn is supported")
            .to_compile_error()
            .into();
        // let ts: TokenStream = quote! {async}.into();
        // $sig.asyncness = Some(parse_macro_input!(ts as syn::token::Async))
    }

    let body = &item_fn.block;
    let name = &sig.ident;
    let docs = item_fn
        .attrs
        .iter()
        .filter(|attr| attr.path.is_ident("doc"))
        .cloned()
        .collect::<Vec<_>>();

    let args: AttributeArgs = parse_macro_input!(args as AttributeArgs);
    let mut internal = false;
    for arg in args {
        if matches!(arg,NestedMeta::Meta(Meta::Path(p)) if p.is_ident("internal")) {
            internal = true;
            break;
        }
    }

    let salvo = salvo_crate(internal);

    let inputs = std::mem::replace(&mut sig.inputs, Punctuated::new());
    let mut req_ts = None;
    let mut depot_ts = None;
    let mut res_ts = None;
    let mut ctrl_ts = None;
    for input in inputs {
        match parse_input_type(&input) {
            InputType::Request => {
                req_ts = Some(input);
            }
            InputType::Depot => {
                depot_ts = Some(input);
            }
            InputType::Response => {
                res_ts = Some(input);
            }
            InputType::FlowCtrl => {
                ctrl_ts = Some(input);
            }
            InputType::UnKnow => {
                return syn::Error::new_spanned(
                    &sig.inputs,
                    "the inputs parameters must be Request, Depot, Response or FlowCtrl",
                )
                .to_compile_error()
                .into()
            }
            InputType::NoReferenceArg => {
                return syn::Error::new_spanned(
                    &sig.inputs,
                    "the inputs parameters must be mutable reference Request, Depot, Response or FlowCtrl",
                )
                .to_compile_error()
                .into()
            }
        }
    }
    if let Some(ts) = req_ts {
        sig.inputs.push(ts);
    } else {
        let ts: TokenStream = quote! {_req: &mut #salvo::Request}.into();
        sig.inputs.push(parse_macro_input!(ts as FnArg));
    }
    if let Some(ts) = depot_ts {
        sig.inputs.push(ts);
    } else {
        let ts: TokenStream = quote! {_depot: &mut #salvo::Depot}.into();
        sig.inputs.push(parse_macro_input!(ts as FnArg));
    }
    if let Some(ts) = res_ts {
        sig.inputs.push(ts);
    } else {
        let ts: TokenStream = quote! {_res: &mut #salvo::Response}.into();
        sig.inputs.push(parse_macro_input!(ts as FnArg));
    }
    if let Some(ts) = ctrl_ts {
        sig.inputs.push(ts);
    } else {
        let ts: TokenStream = quote! {_ctrl: &mut #salvo::routing::FlowCtrl}.into();
        sig.inputs.push(parse_macro_input!(ts as FnArg));
    }

    let sdef = quote! {
        #(#docs)*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        #vis struct #name;
        impl #name {
            #(#attrs)*
            #sig {
                #body
            }
        }
    };

    match sig.output {
        ReturnType::Default => {
            (quote! {
                #sdef
                #[async_trait]
                impl #salvo::Handler for #name {
                    #[inline]
                    async fn handle(&self, req: &mut #salvo::Request, depot: &mut #salvo::Depot, res: &mut #salvo::Response, ctrl: &mut #salvo::routing::FlowCtrl) {
                        Self::#name(req, depot, res, ctrl).await
                    }
                }
            })
            .into()
        }
        ReturnType::Type(_, _) => (quote! {
            #sdef
            #[async_trait]
            impl #salvo::Handler for #name {
                #[inline]
                async fn handle(&self, req: &mut #salvo::Request, depot: &mut #salvo::Depot, res: &mut #salvo::Response, ctrl: &mut #salvo::routing::FlowCtrl) {
                    #salvo::Writer::write(Self::#name(req, depot, res, ctrl).await, req, depot, res).await;
                }
            }
        })
        .into(),
    }
}

// https://github.com/bkchr/proc-macro-crate/issues/14
#[inline]
fn salvo_crate(internal: bool) -> syn::Ident {
    if internal {
        return Ident::new("crate", Span::call_site());
    }
    match crate_name("salvo") {
        Ok(salvo) => match salvo {
            FoundCrate::Itself => Ident::new("salvo", Span::call_site()),
            FoundCrate::Name(name) => Ident::new(&name, Span::call_site()),
        },
        Err(_) => match crate_name("salvo_core") {
            Ok(salvo) => match salvo {
                FoundCrate::Itself => Ident::new("salvo_core", Span::call_site()),
                FoundCrate::Name(name) => Ident::new(&name, Span::call_site()),
            },
            Err(_) => Ident::new("salvo", Span::call_site()),
        },
    }
}

#[inline]
fn parse_input_type(input: &FnArg) -> InputType {
    if let FnArg::Typed(p) = input {
        if let syn::Type::Reference(ty) = &*p.ty {
            if let syn::Type::Path(nty) = &*ty.elem {
                // the last ident for path type is the real type
                // such as:
                // `::std::vec::Vec` is `Vec`
                // `Vec` is `Vec`
                let ident = &nty.path.segments.last().unwrap().ident;
                if ident == "Request" {
                    InputType::Request
                } else if ident == "Response" {
                    InputType::Response
                } else if ident == "Depot" {
                    InputType::Depot
                } else if ident == "FlowCtrl" {
                    InputType::FlowCtrl
                } else {
                    InputType::UnKnow
                }
            } else {
                InputType::UnKnow
            }
        } else {
            // like owned type or other type
            InputType::NoReferenceArg
        }
    } else {
        // like self on fn
        InputType::UnKnow
    }
}