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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Procedural macros for [`axum-debug`] crate.
//!
//! [`axum-debug`]: https://crates.io/crates/axum-debug

#![warn(
    clippy::all,
    clippy::dbg_macro,
    clippy::todo,
    clippy::mem_forget,
    rust_2018_idioms,
    future_incompatible,
    nonstandard_style,
    missing_debug_implementations,
    missing_docs
)]
#![deny(unreachable_pub, private_in_public)]
#![forbid(unsafe_code)]

use proc_macro::TokenStream;

/// Generates better error messages when applied to a handler function.
///
/// # Examples
///
/// Function is not async:
///
/// ```rust,ignore
/// #[debug_handler]
/// fn handler() -> &'static str {
///     "Hello, world"
/// }
/// ```
///
/// ```text
/// error: handlers must be async functions
///   --> main.rs:xx:1
///    |
/// xx | fn handler() -> &'static str {
///    | ^^
/// ```
///
/// Wrong return type:
///
/// ```rust,ignore
/// #[debug_handler]
/// async fn handler() -> bool {
///     false
/// }
/// ```
///
/// ```text
/// error[E0277]: the trait bound `bool: IntoResponse` is not satisfied
///   --> main.rs:xx:23
///    |
/// xx | async fn handler() -> bool {
///    |                       ^^^^
///    |                       |
///    |                       the trait `IntoResponse` is not implemented for `bool`
/// ```
///
/// Wrong extractor:
///
/// ```rust,ignore
/// #[debug_handler]
/// async fn handler(a: bool) -> String {
///     format!("Can I extract a bool? {}", a)
/// }
/// ```
///
/// ```text
/// error[E0277]: the trait bound `bool: FromRequest` is not satisfied
///   --> main.rs:xx:21
///    |
/// xx | async fn handler(a: bool) -> String {
///    |                     ^^^^
///    |                     |
///    |                     the trait `FromRequest` is not implemented for `bool`
/// ```
///
/// Too many extractors:
///
/// ```rust,ignore
/// #[debug_handler]
/// async fn handler(
///     a: String,
///     b: String,
///     c: String,
///     d: String,
///     e: String,
///     f: String,
///     g: String,
///     h: String,
///     i: String,
///     j: String,
///     k: String,
///     l: String,
///     m: String,
///     n: String,
///     o: String,
///     p: String,
///     q: String,
/// ) {}
/// ```
///
/// ```text
/// error: too many extractors. 16 extractors are allowed
/// note: you can nest extractors like "a: (Extractor, Extractor), b: (Extractor, Extractor)"
///   --> main.rs:xx:5
///    |
/// xx | /     a: String,
/// xx | |     b: String,
/// xx | |     c: String,
/// xx | |     d: String,
/// ...  |
/// xx | |     p: String,
/// xx | |     q: String,
///    | |______________^
/// ```
///
/// Future is not [`Send`]:
///
/// ```rust,ignore
/// #[debug_handler]
/// async fn handler() {
///     let not_send = std::rc::Rc::new(());
///
///     async{}.await;
/// }
/// ```
///
/// ```text
/// error: future cannot be sent between threads safely
///   --> main.rs:xx:10
///    |
/// xx | async fn handler() {
///    |          ^^^^^^^
///    |          |
///    |          future returned by `handler` is not `Send`
/// ```
///
/// [`Send`]: Send
#[proc_macro_attribute]
pub fn debug_handler(_attr: TokenStream, input: TokenStream) -> TokenStream {
    #[cfg(not(debug_assertions))]
    return input;

    #[cfg(debug_assertions)]
    return debug::apply_debug_handler(input);
}

/// Shortens error message when applied to a [`Router`].
///
/// # Example
///
/// ```rust,ignore
/// use axum::{handler::get, Router};
/// use axum_debug::{debug_handler, debug_router};
///
/// #[tokio::main]
/// async fn main() {
///     let app = Router::new().route("/", get(handler));
///
///     debug_router!(app);
///
///     axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
///         .serve(app.into_make_service())
///         .await
///         .unwrap();
/// }
///
/// #[debug_handler]
/// async fn handler() -> bool {
///     false
/// }
/// ```
///
/// [`Router`]: axum::routing::Router
#[proc_macro]
pub fn debug_router(_input: TokenStream) -> TokenStream {
    #[cfg(not(debug_assertions))]
    return TokenStream::new();

    #[cfg(debug_assertions)]
    return debug::apply_debug_router(_input);
}

#[cfg(debug_assertions)]
mod debug {
    use proc_macro::TokenStream;
    use proc_macro2::Span;
    use quote::{quote, quote_spanned};
    use syn::{parse_macro_input, FnArg, Ident, ItemFn, ReturnType, Signature};

    pub(crate) fn apply_debug_handler(input: TokenStream) -> TokenStream {
        let function = parse_macro_input!(input as ItemFn);

        let vis = &function.vis;
        let sig = &function.sig;
        let ident = &sig.ident;
        let span = ident.span();
        let len = sig.inputs.len();
        let generics = create_generics(len);
        let params = sig.inputs.iter().map(|fn_arg| {
            if let FnArg::Typed(pat_type) = fn_arg {
                &pat_type.pat
            } else {
                panic!("not a handler function");
            }
        });
        let block = &function.block;

        if let Err(error) = async_check(&sig) {
            return error;
        }

        if let Err(error) = param_limit_check(&sig) {
            return error;
        }

        let check_trait = check_trait_code(&sig, &generics);
        let check_return = check_return_code(&sig, &generics);
        let check_params = check_params_code(&sig, &generics);

        let expanded = quote_spanned! {span=>
            #vis #sig {
                #check_trait
                #check_return
                #(#check_params)*

                #sig #block

                #ident(#(#params),*).await
            }
        };

        expanded.into()
    }

    pub(crate) fn apply_debug_router(input: TokenStream) -> TokenStream {
        let ident = parse_macro_input!(input as Ident);

        let expanded = quote! {
            let #ident = axum::Router::boxed(#ident);
        };

        expanded.into()
    }

    fn create_generics(len: usize) -> Vec<Ident> {
        let mut vec = Vec::new();
        for i in 1..=len {
            vec.push(Ident::new(&format!("T{}", i), Span::call_site()));
        }
        vec
    }

    fn async_check(sig: &Signature) -> Result<(), TokenStream> {
        if sig.asyncness.is_none() {
            let error = syn::Error::new_spanned(sig.fn_token, "handlers must be async functions")
                .to_compile_error()
                .into();

            return Err(error);
        }

        Ok(())
    }

    fn param_limit_check(sig: &Signature) -> Result<(), TokenStream> {
        if sig.inputs.len() > 16 {
            let msg = "too many extractors. 16 extractors are allowed\n\
                       note: you can nest extractors like \"a: (Extractor, Extractor), b: (Extractor, Extractor)\"";

            let error = syn::Error::new_spanned(&sig.inputs, msg)
                .to_compile_error()
                .into();

            return Err(error);
        }

        Ok(())
    }

    fn check_trait_code(sig: &Signature, generics: &Vec<Ident>) -> proc_macro2::TokenStream {
        let ident = &sig.ident;
        let span = ident.span();

        quote_spanned! {span=>
            {
                debug_handler(#ident);

                fn debug_handler<F, Fut, #(#generics),*>(_f: F)
                where
                    F: FnOnce(#(#generics),*) -> Fut + Clone + Send + Sync + 'static,
                    Fut: std::future::Future + Send,
                {}
            }
        }
    }

    fn check_return_code(sig: &Signature, generics: &Vec<Ident>) -> proc_macro2::TokenStream {
        let span = match &sig.output {
            ReturnType::Default => syn::Error::new_spanned(&sig.output, "").span(),
            ReturnType::Type(_, t) => syn::Error::new_spanned(t, "").span(),
        };
        let ident = &sig.ident;

        quote_spanned! {span=>
            {
                debug_handler(#ident);

                fn debug_handler<F, Fut, Res, #(#generics),*>(_f: F)
                where
                    F: FnOnce(#(#generics),*) -> Fut,
                    Fut: std::future::Future<Output = Res>,
                    Res: axum::response::IntoResponse,
                {}
            }
        }
    }

    fn check_params_code(sig: &Signature, generics: &Vec<Ident>) -> Vec<proc_macro2::TokenStream> {
        let mut vec = Vec::new();

        let ident = &sig.ident;

        for (i, generic) in generics.iter().enumerate() {
            let span = match &sig.inputs[i] {
                FnArg::Typed(pat_type) => syn::Error::new_spanned(&pat_type.ty, "").span(),
                _ => panic!("not a handler"),
            };

            let token_stream = quote_spanned! {span=>
                {
                    debug_handler(#ident);

                    fn debug_handler<F, Fut, #(#generics),*>(_f: F)
                    where
                        F: FnOnce(#(#generics),*) -> Fut,
                        Fut: std::future::Future,
                        #generic: axum::extract::FromRequest + Send,
                    {}
                }
            };

            vec.push(token_stream);
        }

        vec
    }
}