Skip to content
Myr

debug_handler.rs

This file

Path

axum-macros/src/debug_handler.rs

891 lines · 25.7 KiB · Rust

Last changed by

Update tungstenite version to 0.30.0 (#3935)xd009642before adoptiondcfd5e3

History of this file

Take it

1use std::{collections::HashSet, fmt};23use crate::{4    attr_parsing::{parse_assignment_attribute, second},5    with_position::{Position, WithPosition},6};7use proc_macro2::{Ident, Span, TokenStream};8use quote::{format_ident, quote, quote_spanned};9use syn::{parse::Parse, spanned::Spanned, FnArg, ItemFn, ReturnType, Token, Type};1011pub(crate) fn expand(attr: Attrs, item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {12    let Attrs { state_ty } = attr;1314    let mut state_ty = state_ty.map(second);1516    let check_extractor_count = check_extractor_count(item_fn, kind);17    let check_path_extractor = check_path_extractor(item_fn, kind);18    let check_output_tuples = check_output_tuples(item_fn);19    let check_output_impls_into_response = if check_output_tuples.is_empty() {20        check_output_impls_into_response(item_fn)21    } else {22        check_output_tuples23    };2425    // If the function is generic, we can't reliably check its inputs or whether the future it26    // returns is `Send`. Skip those checks to avoid unhelpful additional compiler errors.27    let check_inputs_and_future_send = if item_fn.sig.generics.params.is_empty() {28        let mut err = None;2930        if state_ty.is_none() {31            let state_types_from_args = state_types_from_args(item_fn);3233            #[allow(clippy::comparison_chain)]34            if state_types_from_args.len() == 1 {35                state_ty = state_types_from_args.into_iter().next();36            } else if state_types_from_args.len() > 1 {37                err = Some(38                    syn::Error::new(39                        Span::call_site(),40                        format!(41                            "can't infer state type, please add set it explicitly, as in \42                            `#[axum_macros::debug_{kind}(state = MyStateType)]`"43                        ),44                    )45                    .into_compile_error(),46                );47            }48        }4950        err.unwrap_or_else(|| {51            let state_ty = state_ty.unwrap_or_else(|| syn::parse_quote!(()));5253            let check_future_send = check_future_send(item_fn, kind);5455            if let Some(check_input_order) = check_input_order(item_fn, kind) {56                quote! {57                    #check_input_order58                    #check_future_send59                }60            } else {61                let check_inputs_impls_from_request =62                    check_inputs_impls_from_request(item_fn, &state_ty, kind);6364                quote! {65                    #check_inputs_impls_from_request66                    #check_future_send67                }68            }69        })70    } else {71        syn::Error::new_spanned(72            &item_fn.sig.generics,73            format!("`#[axum_macros::debug_{kind}]` doesn't support generic functions"),74        )75        .into_compile_error()76    };7778    let middleware_takes_next_as_last_arg =79        matches!(kind, FunctionKind::Middleware).then(|| next_is_last_input(item_fn));8081    quote! {82        #item_fn83        #check_extractor_count84        #check_path_extractor85        #check_output_impls_into_response86        #check_inputs_and_future_send87        #middleware_takes_next_as_last_arg88    }89}9091#[derive(Clone, Copy)]92pub(crate) enum FunctionKind {93    Handler,94    Middleware,95}9697impl fmt::Display for FunctionKind {98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {99        match self {100            Self::Handler => f.write_str("handler"),101            Self::Middleware => f.write_str("middleware"),102        }103    }104}105106impl FunctionKind {107    fn name_uppercase_plural(self) -> &'static str {108        match self {109            Self::Handler => "Handlers",110            Self::Middleware => "Middleware",111        }112    }113}114115mod kw {116    syn::custom_keyword!(body);117    syn::custom_keyword!(state);118}119120pub(crate) struct Attrs {121    state_ty: Option<(kw::state, Type)>,122}123124impl Parse for Attrs {125    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {126        let mut state_ty = None;127128        while !input.is_empty() {129            let lh = input.lookahead1();130            if lh.peek(kw::state) {131                parse_assignment_attribute(input, &mut state_ty)?;132            } else {133                return Err(lh.error());134            }135136            let _ = input.parse::<Token![,]>();137        }138139        Ok(Self { state_ty })140    }141}142143fn check_extractor_count(item_fn: &ItemFn, kind: FunctionKind) -> Option<TokenStream> {144    let max_extractors = 16;145    let inputs = item_fn146        .sig147        .inputs148        .iter()149        .filter(|arg| skip_next_arg(arg, kind))150        .count();151    if inputs <= max_extractors {152        None153    } else {154        let error_message = format!(155            "{} cannot take more than {max_extractors} arguments. \156            Use `(a, b): (ExtractorA, ExtractorA)` to further nest extractors",157            kind.name_uppercase_plural(),158        );159        let error = syn::Error::new_spanned(&item_fn.sig.inputs, error_message).to_compile_error();160        Some(error)161    }162}163164fn extractor_idents(165    item_fn: &ItemFn,166    kind: FunctionKind,167) -> impl Iterator<Item = (usize, &syn::FnArg, &syn::Ident)> {168    item_fn169        .sig170        .inputs171        .iter()172        .filter(move |arg| skip_next_arg(arg, kind))173        .enumerate()174        .filter_map(|(idx, fn_arg)| match fn_arg {175            FnArg::Receiver(_) => None,176            FnArg::Typed(pat_type) => {177                if let Type::Path(type_path) = &*pat_type.ty {178                    type_path179                        .path180                        .segments181                        .last()182                        .map(|segment| (idx, fn_arg, &segment.ident))183                } else {184                    None185                }186            }187        })188}189190fn check_path_extractor(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {191    let path_extractors = extractor_idents(item_fn, kind)192        .filter(|(_, _, ident)| *ident == "Path")193        .collect::<Vec<_>>();194195    if path_extractors.len() > 1 {196        path_extractors197            .into_iter()198            .map(|(_, arg, _)| {199                syn::Error::new_spanned(200                    arg,201                    "Multiple parameters must be extracted with a tuple \202                    `Path<(_, _)>` or a struct `Path<YourParams>`, not by applying \203                    multiple `Path<_>` extractors",204                )205                .to_compile_error()206            })207            .collect()208    } else {209        quote! {}210    }211}212213fn is_self_pat_type(typed: &syn::PatType) -> bool {214    let ident = if let syn::Pat::Ident(ident) = &*typed.pat {215        &ident.ident216    } else {217        return false;218    };219220    ident == "self"221}222223fn check_inputs_impls_from_request(224    item_fn: &ItemFn,225    state_ty: &Type,226    kind: FunctionKind,227) -> TokenStream {228    let takes_self = item_fn.sig.inputs.first().is_some_and(|arg| match arg {229        FnArg::Receiver(_) => true,230        FnArg::Typed(typed) => is_self_pat_type(typed),231    });232233    WithPosition::new(234        item_fn235            .sig236            .inputs237            .iter()238            .filter(|arg| skip_next_arg(arg, kind)),239    )240    .enumerate()241    .map(|(idx, arg)| {242        let must_impl_from_request_parts = match &arg {243            Position::First(_) | Position::Middle(_) => true,244            Position::Last(_) | Position::Only(_) => false,245        };246247        let arg = arg.into_inner();248249        let (span, ty) = match arg {250            FnArg::Receiver(receiver) => {251                if receiver.reference.is_some() {252                    return syn::Error::new_spanned(253                        receiver,254                        "Handlers must only take owned values",255                    )256                    .into_compile_error();257                }258259                let span = receiver.span();260                (span, syn::parse_quote!(Self))261            }262            FnArg::Typed(typed) => {263                let ty = &typed.ty;264                let span = ty.span();265266                if is_self_pat_type(typed) {267                    (span, syn::parse_quote!(Self))268                } else {269                    (span, ty.clone())270                }271            }272        };273274        let consumes_request = request_consuming_type_name(&ty).is_some();275276        let check_fn = format_ident!(277            "__axum_macros_check_{}_{}_from_request_check",278            item_fn.sig.ident,279            idx,280            span = span,281        );282283        let call_check_fn = format_ident!(284            "__axum_macros_check_{}_{}_from_request_call_check",285            item_fn.sig.ident,286            idx,287            span = span,288        );289290        let call_check_fn_body = if takes_self {291            quote_spanned! {span=>292                Self::#check_fn();293            }294        } else {295            quote_spanned! {span=>296                #check_fn();297            }298        };299300        let check_fn_generics = if must_impl_from_request_parts || consumes_request {301            quote! {}302        } else {303            quote! { <M> }304        };305306        let from_request_bound = if must_impl_from_request_parts {307            quote_spanned! {span=>308                #ty: ::axum::extract::FromRequestParts<#state_ty> + Send309            }310        } else if consumes_request {311            quote_spanned! {span=>312                #ty: ::axum::extract::FromRequest<#state_ty> + Send313            }314        } else {315            quote_spanned! {span=>316                #ty: ::axum::extract::FromRequest<#state_ty, M> + Send317            }318        };319320        quote_spanned! {span=>321            #[allow(warnings)]322            #[doc(hidden)]323            fn #check_fn #check_fn_generics()324            where325                #from_request_bound,326            {}327328            // we have to call the function to actually trigger a compile error329            // since the function is generic, just defining it is not enough330            #[allow(warnings)]331            #[doc(hidden)]332            fn #call_check_fn()333            {334                #call_check_fn_body335            }336        }337    })338    .collect::<TokenStream>()339}340341fn check_output_tuples(item_fn: &ItemFn) -> TokenStream {342    let elems = match &item_fn.sig.output {343        ReturnType::Type(_, ty) => match &**ty {344            Type::Tuple(tuple) => &tuple.elems,345            _ => return quote! {},346        },347        ReturnType::Default => return quote! {},348    };349350    let handler_ident = &item_fn.sig.ident;351352    match elems.len() {353        0 => quote! {},354        n if n > 17 => syn::Error::new_spanned(355            &item_fn.sig.output,356            "Cannot return tuples with more than 17 elements",357        )358        .to_compile_error(),359        _ => WithPosition::new(elems)360            .enumerate()361            .map(|(idx, arg)| match arg {362                Position::First(ty) => match extract_clean_typename(ty).as_deref() {363                    Some("StatusCode" | "Response") => quote! {},364                    Some("Parts") => check_is_response_parts(ty, handler_ident, idx),365                    Some(_) | None => {366                        if let Some(tn) = well_known_last_response_type(ty) {367                            syn::Error::new_spanned(368                                ty,369                                format!(370                                    "`{tn}` must be the last element \371                                    in a response tuple"372                                ),373                            )374                            .to_compile_error()375                        } else {376                            check_into_response_parts(ty, handler_ident, idx)377                        }378                    }379                },380                Position::Middle(ty) => {381                    if let Some(tn) = well_known_last_response_type(ty) {382                        syn::Error::new_spanned(383                            ty,384                            format!("`{tn}` must be the last element in a response tuple"),385                        )386                        .to_compile_error()387                    } else {388                        check_into_response_parts(ty, handler_ident, idx)389                    }390                }391                Position::Last(ty) | Position::Only(ty) => check_into_response(handler_ident, ty),392            })393            .collect::<TokenStream>(),394    }395}396397fn check_into_response(handler: &Ident, ty: &Type) -> TokenStream {398    let (span, ty) = (ty.span(), ty.clone());399400    let check_fn = format_ident!(401        "__axum_macros_check_{handler}_into_response_check",402        span = span,403    );404405    let call_check_fn = format_ident!(406        "__axum_macros_check_{handler}_into_response_call_check",407        span = span,408    );409410    let call_check_fn_body = quote_spanned! {span=>411        #check_fn();412    };413414    let from_request_bound = quote_spanned! {span=>415        #ty: ::axum::response::IntoResponse416    };417    quote_spanned! {span=>418        #[allow(warnings)]419        #[allow(unreachable_code)]420        #[doc(hidden)]421        fn #check_fn()422        where423            #from_request_bound,424        {}425426        // we have to call the function to actually trigger a compile error427        // since the function is generic, just defining it is not enough428        #[allow(warnings)]429        #[allow(unreachable_code)]430        #[doc(hidden)]431        fn #call_check_fn() {432            #call_check_fn_body433        }434    }435}436437fn check_is_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {438    let (span, ty) = (ty.span(), ty.clone());439440    let check_fn = format_ident!(441        "__axum_macros_check_{}_is_response_parts_{index}_check",442        ident,443        span = span,444    );445446    quote_spanned! {span=>447        #[allow(warnings)]448        #[allow(unreachable_code)]449        #[doc(hidden)]450        fn #check_fn(parts: #ty) -> ::axum::http::response::Parts {451            parts452        }453    }454}455456fn check_into_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {457    let (span, ty) = (ty.span(), ty.clone());458459    let check_fn = format_ident!(460        "__axum_macros_check_{}_into_response_parts_{index}_check",461        ident,462        span = span,463    );464465    let call_check_fn = format_ident!(466        "__axum_macros_check_{}_into_response_parts_{index}_call_check",467        ident,468        span = span,469    );470471    let call_check_fn_body = quote_spanned! {span=>472        #check_fn();473    };474475    let from_request_bound = quote_spanned! {span=>476        #ty: ::axum::response::IntoResponseParts477    };478    quote_spanned! {span=>479        #[allow(warnings)]480        #[allow(unreachable_code)]481        #[doc(hidden)]482        fn #check_fn()483        where484            #from_request_bound,485        {}486487        // we have to call the function to actually trigger a compile error488        // since the function is generic, just defining it is not enough489        #[allow(warnings)]490        #[allow(unreachable_code)]491        #[doc(hidden)]492        fn #call_check_fn() {493            #call_check_fn_body494        }495    }496}497498fn check_input_order(item_fn: &ItemFn, kind: FunctionKind) -> Option<TokenStream> {499    let number_of_inputs = item_fn500        .sig501        .inputs502        .iter()503        .filter(|arg| skip_next_arg(arg, kind))504        .count();505506    let types_that_consume_the_request = item_fn507        .sig508        .inputs509        .iter()510        .filter(|arg| skip_next_arg(arg, kind))511        .enumerate()512        .filter_map(|(idx, arg)| {513            let ty = match arg {514                FnArg::Typed(pat_type) => &*pat_type.ty,515                FnArg::Receiver(_) => return None,516            };517            let type_name = request_consuming_type_name(ty)?;518519            Some((idx, type_name, ty.span()))520        })521        .collect::<Vec<_>>();522523    if types_that_consume_the_request.is_empty() {524        return None;525    };526527    // exactly one type that consumes the request528    if types_that_consume_the_request.len() == 1 {529        // and that is not the last530        if types_that_consume_the_request[0].0 != number_of_inputs - 1 {531            let (_idx, type_name, span) = &types_that_consume_the_request[0];532            let error = format!(533                "`{type_name}` consumes the request body and thus must be \534                the last argument to the handler function"535            );536            return Some(quote_spanned! {*span=>537                compile_error!(#error);538            });539        } else {540            return None;541        }542    }543544    if types_that_consume_the_request.len() == 2 {545        let (_, first, _) = &types_that_consume_the_request[0];546        let (_, second, _) = &types_that_consume_the_request[1];547        let error = format!(548            "Can't have two extractors that consume the request body. \549            `{first}` and `{second}` both do that.",550        );551        let span = item_fn.sig.inputs.span();552        Some(quote_spanned! {span=>553            compile_error!(#error);554        })555    } else {556        let types = WithPosition::new(types_that_consume_the_request)557            .map(|pos| match pos {558                Position::First((_, type_name, _)) | Position::Middle((_, type_name, _)) => {559                    format!("`{type_name}`, ")560                }561                Position::Last((_, type_name, _)) => format!("and `{type_name}`"),562                Position::Only(_) => unreachable!(),563            })564            .collect::<String>();565566        let error = format!(567            "Can't have more than one extractor that consume the request body. \568            {types} all do that.",569        );570        let span = item_fn.sig.inputs.span();571        Some(quote_spanned! {span=>572            compile_error!(#error);573        })574    }575}576577fn extract_clean_typename(ty: &Type) -> Option<String> {578    let path = match ty {579        Type::Path(type_path) => &type_path.path,580        _ => return None,581    };582    path.segments.last().map(|p| p.ident.to_string())583}584585fn request_consuming_type_name(ty: &Type) -> Option<&'static str> {586    let typename = extract_clean_typename(ty)?;587588    let type_name = match &*typename {589        "Json" => "Json<_>",590        "RawBody" => "RawBody<_>",591        "RawForm" => "RawForm",592        "Multipart" => "Multipart",593        "Protobuf" => "Protobuf",594        "JsonLines" => "JsonLines<_>",595        "Form" => "Form<_>",596        "Request" => "Request<_>",597        "Bytes" => "Bytes",598        "String" => "String",599        "Parts" => "Parts",600        _ => return None,601    };602603    Some(type_name)604}605606fn well_known_last_response_type(ty: &Type) -> Option<&'static str> {607    let typename = extract_clean_typename(ty)?;608609    let type_name = match &*typename {610        "Json" => "Json<_>",611        "Protobuf" => "Protobuf",612        "JsonLines" => "JsonLines<_>",613        "Form" => "Form<_>",614        "Bytes" => "Bytes",615        "String" => "String",616        _ => return None,617    };618619    Some(type_name)620}621622fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {623    let ty = match &item_fn.sig.output {624        syn::ReturnType::Default => return quote! {},625        syn::ReturnType::Type(_, ty) => ty,626    };627    let span = ty.span();628629    let declare_inputs = item_fn630        .sig631        .inputs632        .iter()633        .filter_map(|arg| match arg {634            FnArg::Receiver(_) => None,635            FnArg::Typed(pat_ty) => {636                let pat = &pat_ty.pat;637                let ty = &pat_ty.ty;638                Some(quote! {639                    let #pat: #ty = panic!();640                })641            }642        })643        .collect::<TokenStream>();644645    let block = &item_fn.block;646647    let make_value_name = format_ident!(648        "__axum_macros_check_{}_into_response_make_value",649        item_fn.sig.ident650    );651652    let make = if item_fn.sig.asyncness.is_some() {653        quote_spanned! {span=>654            #[allow(warnings)]655            #[allow(unreachable_code)]656            #[doc(hidden)]657            async fn #make_value_name() -> #ty {658                #declare_inputs659                #block660            }661        }662    } else {663        quote_spanned! {span=>664            #[allow(warnings)]665            #[allow(unreachable_code)]666            #[doc(hidden)]667            fn #make_value_name() -> #ty {668                #declare_inputs669                #block670            }671        }672    };673674    let name = format_ident!("__axum_macros_check_{}_into_response", item_fn.sig.ident);675676    if let Some(receiver) = self_receiver(item_fn) {677        quote_spanned! {span=>678            #make679680            #[allow(warnings)]681            #[allow(unreachable_code)]682            #[doc(hidden)]683            async fn #name() {684                fn check<T>(_: T)685                    where T: ::axum::response::IntoResponse686                {}687                let value = #receiver #make_value_name().await;688                check(value);689            }690        }691    } else {692        quote_spanned! {span=>693            #[allow(warnings)]694            #[allow(unreachable_code)]695            #[doc(hidden)]696            async fn #name() {697                #make698699                fn check<T>(_: T)700                where T: ::axum::response::IntoResponse701                {}702703                let value = #make_value_name().await;704705                check(value);706            }707        }708    }709}710711fn check_future_send(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {712    if item_fn.sig.asyncness.is_none() {713        match &item_fn.sig.output {714            syn::ReturnType::Default => {715                return syn::Error::new_spanned(716                    item_fn.sig.fn_token,717                    format!("{} must be `async fn`s", kind.name_uppercase_plural()),718                )719                .into_compile_error();720            }721            syn::ReturnType::Type(_, ty) => ty,722        };723    }724725    let span = item_fn.sig.ident.span();726727    let handler_name = &item_fn.sig.ident;728729    let args = item_fn.sig.inputs.iter().map(|_| {730        quote_spanned! {span=> panic!() }731    });732733    let name = format_ident!("__axum_macros_check_{}_future", item_fn.sig.ident);734735    let define_check = quote! {736        fn check<T>(_: T)737            where T: ::std::future::Future + Send738        {}739    };740741    let do_check = quote! {742        check(future);743    };744745    if let Some(receiver) = self_receiver(item_fn) {746        quote! {747            #[allow(warnings)]748            #[allow(unreachable_code)]749            #[doc(hidden)]750            fn #name() {751                #define_check752                let future = #receiver #handler_name(#(#args),*);753                #do_check754            }755        }756    } else {757        quote! {758            #[allow(warnings)]759            #[allow(unreachable_code)]760            #[doc(hidden)]761            fn #name() {762                #item_fn763                #define_check764                let future = #handler_name(#(#args),*);765                #do_check766            }767        }768    }769}770771fn self_receiver(item_fn: &ItemFn) -> Option<TokenStream> {772    let takes_self = item_fn.sig.inputs.iter().any(|arg| match arg {773        FnArg::Receiver(_) => true,774        FnArg::Typed(typed) => is_self_pat_type(typed),775    });776777    if takes_self {778        return Some(quote! { Self:: });779    }780781    if let syn::ReturnType::Type(_, ty) = &item_fn.sig.output {782        if let syn::Type::Path(path) = &**ty {783            let segments = &path.path.segments;784            if segments.len() == 1 {785                if let Some(last) = segments.last() {786                    match &last.arguments {787                        syn::PathArguments::None if last.ident == "Self" => {788                            return Some(quote! { Self:: });789                        }790                        _ => {}791                    }792                }793            }794        }795    }796797    None798}799800/// Given a signature like801///802/// ```skip803/// #[debug_handler]804/// async fn handler(805///     _: axum::extract::State<AppState>,806///     _: State<AppState>,807/// ) {}808/// ```809///810/// This will extract `AppState`.811///812/// Returns `None` if there are no `State` args or multiple of different types.813fn state_types_from_args(item_fn: &ItemFn) -> HashSet<Type> {814    let types = item_fn815        .sig816        .inputs817        .iter()818        .filter_map(|input| match input {819            FnArg::Receiver(_) => None,820            FnArg::Typed(pat_type) => Some(pat_type),821        })822        .map(|pat_type| &*pat_type.ty);823    crate::infer_state_types(types).collect()824}825826fn next_is_last_input(item_fn: &ItemFn) -> TokenStream {827    let next_args = item_fn828        .sig829        .inputs830        .iter()831        .enumerate()832        .filter(|(_, arg)| !skip_next_arg(arg, FunctionKind::Middleware))833        .collect::<Vec<_>>();834835    if next_args.is_empty() {836        return quote! {837            compile_error!(838                "Middleware functions must take `axum::middleware::Next` as the last argument",839            );840        };841    }842843    if next_args.len() == 1 {844        let (idx, arg) = &next_args[0];845        if *idx != item_fn.sig.inputs.len() - 1 {846            return quote_spanned! {arg.span()=>847                compile_error!("`axum::middleware::Next` must be the last argument");848            };849        }850    }851852    if next_args.len() >= 2 {853        return quote! {854            compile_error!(855                "Middleware functions can only take one argument of type `axum::middleware::Next`",856            );857        };858    }859860    quote! {}861}862863fn skip_next_arg(arg: &FnArg, kind: FunctionKind) -> bool {864    match kind {865        FunctionKind::Handler => true,866        FunctionKind::Middleware => match arg {867            FnArg::Receiver(_) => true,868            FnArg::Typed(pat_type) => {869                if let Type::Path(type_path) = &*pat_type.ty {870                    type_path871                        .path872                        .segments873                        .last()874                        .is_none_or(|path_segment| path_segment.ident != "Next")875                } else {876                    true877                }878            }879        },880    }881}882883#[test]884fn ui_debug_handler() {885    crate::run_ui_tests("debug_handler");886}887888#[test]889fn ui_debug_middleware() {890    crate::run_ui_tests("debug_middleware");891}