potato_macro/
lib.rs

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
use lazy_static::lazy_static;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use rand::Rng;
use std::collections::HashSet;
use syn::{parse_macro_input, FnArg, ItemFn, LitStr};

lazy_static! {
    static ref ARG_TYPES: HashSet<&'static str> = [
        "String", "bool", "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "f32",
        "f64", "isize",
    ]
    .into_iter()
    .collect();
}

fn random_ident() -> Ident {
    let mut rng = rand::thread_rng();
    let value = format!("__potato_id_{}", rng.gen::<u64>());
    Ident::new(&value, Span::call_site())
}

// ItemFn {
//     sig: Signature {
//         ident: Ident { ident: "hello", span: #0 bytes(312..317) },
//         inputs: [FnArg::Typed(
//             PatType {
//                 pat: Pat::Ident { ident: Ident { ident: "req", span: #0 bytes(318..321) }, },
//                 ty: Type::Path { path: Path { segments: [
//                     PathSegment {
//                         ident: Ident { ident: "HttpRequest", span: #0 bytes(323..334) },
//                         arguments: PathArguments::None
//                     }
//                 ] } }
//             }
//         )],
//         output: ReturnType::Type( Type::Path { path: Path { segments: [
//             PathSegment {
//                 ident: Ident { ident: "HttpResponse", span: #0 bytes(339..351) },
//                 arguments: PathArguments::None
//             }
//         ] } } )
//     },
// }

fn http_handler_macro(attr: TokenStream, input: TokenStream, req_name: &str) -> TokenStream {
    let req_name = Ident::new(req_name, Span::call_site());
    let route_path = parse_macro_input!(attr as LitStr);
    let root_fn = parse_macro_input!(input as ItemFn);
    let fn_name = root_fn.sig.ident.clone();
    let wrap_func_name = random_ident();
    let mut args = vec![];
    for arg in root_fn.sig.inputs.iter() {
        if let FnArg::Typed(arg) = arg {
            let arg_type = arg
                .ty
                .as_ref()
                .to_token_stream()
                .to_string()
                .type_simplify();
            let arg_name_str = arg.pat.to_token_stream().to_string();
            let arg_name = Ident::new(&arg_name_str, Span::call_site());
            args.push(match &arg_type[..] {
                "HttpRequest" => quote! { req },
                "SocketAddr" => quote! { client },
                "& mut WebsocketContext" => quote! { wsctx },
                "PostFile" => quote! {
                    match req.body_files.get(#arg_name_str).cloned() {
                        Some(file) => file,
                        None => return HttpResponse::error(format!("lose file: #arg_name")),
                    }
                },
                arg_type if ARG_TYPES.contains(arg_type) => quote! {
                    match req.body_pairs.get(#arg_name_str).cloned() {
                        Some(val) => val,
                        None => match req.url_query.get(#arg_name_str).cloned() {
                            Some(val) => val,
                            None => return HttpResponse::error(format!("lose file: #arg_name")),
                        },
                    }
                },
                _ => panic!("unsupported arg type: [{}]", arg_type),
            });
        } else {
            panic!("unsupported: {}", arg.to_token_stream().to_string());
        }
    }
    let wrap_func_name2 = random_ident();
    let ret_type = root_fn
        .sig
        .output
        .to_token_stream()
        .to_string()
        .type_simplify();
    let wrap_func_body = match &ret_type[..] {
        "Result < () >" => quote! {
            match #fn_name(#(#args),*).await {
                Ok(ret) => HttpResponse::empty(),
                Err(err) => HttpResponse::error(format!("{err:?}")),
            }
        },
        "Result < HttpResponse >" => quote! {
            match #fn_name(#(#args),*).await {
                Ok(ret) => ret,
                Err(err) => HttpResponse::error(format!("{err:?}")),
            }
        },
        "()" => quote! {
            #fn_name(#(#args),*).await;
            HttpResponse::empty()
        },
        "HttpResponse" => quote! {
            #fn_name(#(#args),*).await
        },
        _ => panic!("unsupported ret type: {}", ret_type),
    };
    quote! {
        #root_fn

        #[doc(hidden)]
        async fn #wrap_func_name2(
            req: potato::HttpRequest, client: std::net::SocketAddr, wsctx: &mut potato::WebsocketContext
        ) -> potato::HttpResponse {
            #wrap_func_body
        }

        #[doc(hidden)]
        fn #wrap_func_name<'a>(
            req: potato::HttpRequest, client: std::net::SocketAddr, wsctx: &'a mut potato::WebsocketContext
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + 'a>> {
            Box::pin(#wrap_func_name2(req, client, wsctx))
        }

        potato::inventory::submit!{potato::RequestHandlerFlag::new(
            potato::HttpMethod::#req_name, #route_path, #wrap_func_name
        )}
    }.into()
}

#[proc_macro_attribute]
pub fn http_get(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "GET")
}

#[proc_macro_attribute]
pub fn http_post(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "POST")
}

#[proc_macro_attribute]
pub fn http_put(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "PUT")
}

#[proc_macro_attribute]
pub fn http_delete(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "DELETE")
}

#[proc_macro_attribute]
pub fn http_options(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "OPTIONS")
}

#[proc_macro_attribute]
pub fn http_head(attr: TokenStream, input: TokenStream) -> TokenStream {
    http_handler_macro(attr, input, "HEAD")
}

trait StringExt {
    fn type_simplify(&self) -> String;
}

impl StringExt for String {
    fn type_simplify(&self) -> String {
        self.replace("potato :: ", "")
            .replace("std :: ", "")
            .replace("net :: ", "")
            .replace("anyhow :: ", "")
            .replace("-> ", "")
    }
}