baxe_derive/
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
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
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Expr, Fields};

#[proc_macro_attribute]
pub fn error(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);

    for attr in &input.attrs {
        if attr.path().is_ident("baxe") {
            let err = syn::Error::new(
                attr.span(),
                "The #[baxe(...)] attribute is only allowed on enum variants, not on the enum itself.",
            );
            return err.to_compile_error().into();
        }
    }

    let enum_name = input.ident;
    let data = match input.data {
        Data::Enum(data) => data,
        _ => panic!("baxe::error can only be applied to enums"),
    };

    let variants_def = data
        .variants
        .iter()
        .map(|v| {
            let variant_ident = &v.ident;
            match &v.fields {
                Fields::Unit => quote! { #variant_ident },
                Fields::Unnamed(fields) => {
                    let types = fields.unnamed.iter().map(|f| &f.ty);
                    quote! { #variant_ident(#(#types),*) }
                }
                Fields::Named(fields) => {
                    let field_defs = fields.named.iter().map(|f| {
                        let name = &f.ident;
                        let ty = &f.ty;
                        quote! { #name: #ty }
                    });
                    quote! { #variant_ident { #(#field_defs),* } }
                }
            }
        })
        .collect::<Vec<_>>();

    let matches = data
        .variants
        .iter()
        .map(|variant| {
            let variant_ident = &variant.ident;
            let attrs = parse_baxe_attributes(variant);
            let (status, tag, code, message) = (attrs.status, attrs.tag, attrs.code, attrs.message);

            let pattern = match &variant.fields {
                Fields::Unit => quote! { 
                    #enum_name::#variant_ident
                },
                Fields::Unnamed(ref fields) => {
                    let field_patterns: Vec<_> = fields.unnamed.iter().enumerate().map(|(i, _)| {
                        syn::Ident::new(&format!("arg{i}"), proc_macro2::Span::call_site())
                    }).collect();
                    quote! {
                        #enum_name::#variant_ident(#(#field_patterns),*)
                    }
                }
                Fields::Named(ref fields) => {
                    let field_patterns: Vec<_> = fields.named.iter().map(|field| {
                        field.ident.clone().unwrap()
                    }).collect();
                    quote! {
                        #enum_name::#variant_ident { #(#field_patterns),* }
                    }
                }
            };

            let message = match &variant.fields {
                Fields::Unit => quote! { 
                    #enum_name::#variant_ident => { 
                        write!(f, #message) 
                    }
                },
                Fields::Unnamed(ref fields) => {
                    let field_patterns: Vec<_> = fields.unnamed.iter().enumerate().map(|(i, _)| {
                        // Generate a name for each field (e.g., `arg0`, `arg1`, ...)
                        syn::Ident::new(&format!("arg{i}"), proc_macro2::Span::call_site())
                    }).collect();
            
                    let field_names = &field_patterns; // Use the generated names for the format! arguments
                    quote! {
                        #enum_name::#variant_ident(#(#field_patterns),*) => {
                            let formatted_message = format!(#message, #(#field_names),*);
                            write!(f, "{formatted_message}")
                        }
                    }
                }
                Fields::Named(ref fields) => {
                    let field_patterns: Vec<_> = fields.named.iter().map(|field| {
                        field.ident.clone().unwrap() // Get the field name (e.g., `field_name`)
                    }).collect();
            
                    let field_names = &field_patterns; // Use the field names for the format! arguments
                    quote! {
                        #enum_name::#variant_ident { #(#field_patterns),* } => {
                            let formatted_message = format!(#message, #(#field_names),*);
                            write!(f, "{formatted_message}")
                        }
                    }
                }
            };

            (pattern, status, tag, code, message)
        })
        .collect::<Vec<_>>();

    let (patterns, statuses, tags, codes, messages): (Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>) =
        matches.into_iter().unzip_n_vec();

    let expanded = quote! {
        #[derive(Debug)]
        pub enum #enum_name {
            #(#variants_def,)*
        }

        impl std::fmt::Display for #enum_name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    #(#messages,)*
                }
            }
        }

        impl std::error::Error for #enum_name {}
        
        impl crate::traits::BackendError for #enum_name {
            fn to_status_code(&self) -> axum::http::StatusCode {
                match self {
                    #(#patterns => #statuses,)*
                }
            }

            fn to_error_tag(&self) -> &str {
                match self {
                    #(#patterns => #tags,)*
                }
            }

            fn to_error_code(&self) -> u16 {
                match self {
                    #(#patterns => #codes,)*
                }
            }
        }

        impl From<#enum_name> for crate::BaxeError {
            fn from(error: #enum_name) -> Self {
                use crate::traits::BackendError;
                let status = error.to_status_code();
                crate::BaxeError {
                    status_code: status,
                    error_tag: error.to_error_tag().to_string(),
                    code: error.to_error_code(),
                    message: error.to_string(),
                }
            }
        }

        impl IntoResponse for #enum_name {
            fn into_response(self) -> axum::response::Response {
                (self.to_status_code(), Json(crate::BaxeError::from(self))).into_response()
            }
        }
    };

    TokenStream::from(expanded)
}

struct BaxeAttributes {
    status: proc_macro2::TokenStream,
    tag: proc_macro2::TokenStream,
    code: proc_macro2::TokenStream,
    message: proc_macro2::TokenStream,
}

fn parse_baxe_attributes(variant: &syn::Variant) -> BaxeAttributes {
    let mut attrs = BaxeAttributes {
        status: quote!(None),
        tag: quote!(None),
        code: quote!(None),
        message: quote!(None),
    };

    for attr in &variant.attrs {
        if attr.path().is_ident("baxe") {
            attr.parse_nested_meta(|meta| {
                let value = meta.value()?.parse::<Expr>()?;
                if let Some(ident) = meta.path.get_ident().map(|ident| ident.to_string()) {
                    match ident.as_str() {
                        "status" => attrs.status = quote!(#value),
                        "tag" => attrs.tag = quote!(#value),
                        "code" => attrs.code = quote!(#value),
                        "message" => attrs.message = quote!(#value),
                        _ => {}
                    }
                }
                Ok(())
            })
            .unwrap();
        }
    }

    attrs
}

trait UnzipN<T1, T2, T3, T4, T5> {
    fn unzip_n_vec(self) -> (Vec<T1>, Vec<T2>, Vec<T3>, Vec<T4>, Vec<T5>);
}

impl<T1, T2, T3, T4, T5, I: Iterator<Item = (T1, T2, T3, T4, T5)>> UnzipN<T1, T2, T3, T4, T5>
    for I
{
    fn unzip_n_vec(self) -> (Vec<T1>, Vec<T2>, Vec<T3>, Vec<T4>, Vec<T5>) {
        let mut t1 = Vec::new();
        let mut t2 = Vec::new();
        let mut t3 = Vec::new();
        let mut t4 = Vec::new();
        let mut t5 = Vec::new();

        for (x1, x2, x3, x4, x5) in self {
            t1.push(x1);
            t2.push(x2);
            t3.push(x3);
            t4.push(x4);
            t5.push(x5);
        }

        (t1, t2, t3, t4, t5)
    }
}