error-tree 0.6.0

This crate let's us use the `error_tree!` proc macro for ergonomic error hierarchy definition
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
crate::ix!();

#[derive(Clone,Debug,PartialEq)]
pub struct ErrorEnum {
    pub attrs:      Vec<Attribute>,
    pub visibility: syn::Visibility,
    pub ident:      Ident, // Enum name
    pub variants:   Vec<ErrorVariant>, // Variants
}

impl ToTokens for ErrorEnum {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let ErrorEnum {
            attrs,
            visibility,
            ident,
            variants: _,
        } = &self;

        // Process attributes
        let mut other_attrs = Vec::new();
        let mut derives = Vec::new();
        let mut has_partial_eq = false;

        for attr in &self.attrs {
            if attr.path().is_ident("derive") {
                let paths: syn::punctuated::Punctuated<syn::Path, syn::token::Comma> =
                    attr.parse_args_with(syn::punctuated::Punctuated::parse_terminated)
                        .unwrap_or_default();
                for path in paths.iter() {
                    if path.is_ident("PartialEq") {
                        has_partial_eq = true;
                    } else {
                        derives.push(path.clone());
                    }
                }
            } else {
                other_attrs.push(attr.clone());
            }
        }

        // Ensure `Debug` is included
        if !derives.iter().any(|path| path.is_ident("Debug")) {
            derives.push(parse_quote!(Debug));
        }

        // Generate enum definition
        let variant_defs = self.variant_defs();
        tokens.extend(quote! {
            #(#other_attrs)*
            #[derive(#(#derives),*)]
            #visibility enum #ident {
                #(#variant_defs),*
            }
        });

        // Generate impl Display
        let display_impl = self.generate_display_impl();
        tokens.extend(display_impl);

        // Conditionally generate PartialEq implementation
        if has_partial_eq {
            if let Some(partial_eq_impl) = self.generate_partial_eq_impl() {
                tokens.extend(partial_eq_impl);
            }
        }
    }
}


impl ErrorEnum {

    fn has_derive_partial_eq(&self) -> bool {
        for attr in &self.attrs {
            if attr.path().is_ident("derive") {
                let mut found = false;
                attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("PartialEq") {
                        found = true;
                    }
                    Ok(())
                }).expect("Failed to parse nested meta");
                if found {
                    return true;
                }
            }
        }
        false
    }

    pub fn variant_defs(&self) -> Vec<TokenStream2> {
        self.variants.iter().map(|variant| {
            let attrs = variant.attrs();

            match variant {
                // Basic variants remain unchanged
                ErrorVariant::Basic { ident, .. } => quote! {
                    #(#attrs)*
                    #ident
                },
                // Wrapped variants generate tuple variants
                ErrorVariant::Wrapped { ident, ty, .. } => quote! {
                    #(#attrs)*
                    #ident(#ty)
                },
                // Struct variants remain unchanged
                ErrorVariant::Struct { ident, fields, .. } => {
                    let field_defs: Vec<_> = fields.iter().map(|field| {
                        let ErrorField { ident, ty } = field;
                        quote! { #ident: #ty }
                    }).collect();
                    quote! {
                        #(#attrs)*
                        #ident { #(#field_defs),* }
                    }
                },
            }
        }).collect()
    }

    pub fn find_variant_name_wrapping_type(&self, ty: &Type) -> Option<Ident> {

        self.variants.iter().find_map(|variant| {
            match variant {
                ErrorVariant::Wrapped { attrs: _, ident, ty: wrapped_ty, .. }
                    if **wrapped_ty == *ty => Some(ident.clone()),
                _ => None,
            }
        })
    }

    fn generate_display_impl(&self) -> TokenStream2 {
        let ident = &self.ident;

        let arms: Vec<TokenStream2> = self.variants.iter().map(|variant| {
            let variant_ident = variant.ident();
            let display_format = variant.display_format();

            match variant {
                // Basic variants
                ErrorVariant::Basic { .. } => {
                    if let Some(format_str) = display_format {
                        quote! {
                            #ident::#variant_ident => write!(f, #format_str),
                        }
                    } else {
                        quote! {
                            #ident::#variant_ident => write!(f, stringify!(#variant_ident)),
                        }
                    }
                },
                // Wrapped variants now match tuple variants
                ErrorVariant::Wrapped { .. } => {
                    if let Some(format_str) = display_format {
                        quote! {
                            #ident::#variant_ident(inner) => write!(f, #format_str, inner = inner),
                        }
                    } else {
                        quote! {
                            #ident::#variant_ident(inner) => write!(f, "{}: {:?}", stringify!(#variant_ident), inner),
                        }
                    }
                },
                // Struct variants
                ErrorVariant::Struct { fields, .. } => {
                    let field_idents: Vec<_> = fields.iter().map(|field| &field.ident).collect();
                    let pattern = quote! { #ident::#variant_ident { #(#field_idents),* } };

                    if let Some(format_str) = display_format {
                        let format_args = field_idents.iter().map(|ident| quote! { #ident = #ident });
                        quote! {
                            #pattern => write!(f, #format_str, #(#format_args),*),
                        }
                    } else {
                        quote! {
                            #pattern => write!(f, stringify!(#variant_ident)),
                        }
                    }
                },
            }
        }).collect();

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

    fn generate_partial_eq_impl(&self) -> Option<TokenStream2> {
        let ident = &self.ident;

        // Generate match arms for each variant
        let arms: Vec<TokenStream2> = self.variants.iter().map(|variant| {
            let variant_ident = variant.ident();
            let cmp_neq = variant.cmp_neq();

            match variant {
                ErrorVariant::Basic { .. } => {
                    if cmp_neq {
                        quote! {
                            (#ident::#variant_ident, #ident::#variant_ident) => false,
                        }
                    } else {
                        quote! {
                            (#ident::#variant_ident, #ident::#variant_ident) => true,
                        }
                    }
                },
                ErrorVariant::Wrapped { .. } => {
                    if cmp_neq {
                        quote! {
                            (#ident::#variant_ident(_), #ident::#variant_ident(_)) => false,
                        }
                    } else {
                        quote! {
                            (#ident::#variant_ident(a), #ident::#variant_ident(b)) => a == b,
                        }
                    }
                },
                ErrorVariant::Struct { fields, .. } => {
                    if cmp_neq {
                        quote! {
                            (#ident::#variant_ident { .. }, #ident::#variant_ident { .. }) => false,
                        }
                    } else {
                        // Compare each field
                        let field_idents: Vec<_> = fields.iter().map(|f| &f.ident).collect();
                        let a_fields: Vec<_> = field_idents.iter()
                            .map(|ident| format_ident!("a_{}", ident))
                            .collect();
                        let b_fields: Vec<_> = field_idents.iter()
                            .map(|ident| format_ident!("b_{}", ident))
                            .collect();

                        let pattern_a = quote! { #ident::#variant_ident { #(#field_idents: #a_fields),* } };
                        let pattern_b = quote! { #ident::#variant_ident { #(#field_idents: #b_fields),* } };

                        let comparisons = a_fields.iter().zip(b_fields.iter())
                            .map(|(a, b)| quote! { #a == #b });

                        quote! {
                            (#pattern_a, #pattern_b) => {
                                #(#comparisons)&&*
                            },
                        }
                    }
                },
            }
        }).collect();

        // Fallback arm for variants that don't match
        let fallback_arm = quote! {
            _ => false,
        };

        Some(quote! {
            impl PartialEq for #ident {
                fn eq(&self, other: &Self) -> bool {
                    match (self, other) {
                        #(#arms)*
                        #fallback_arm
                    }
                }
            }
        })
    }
}

impl Parse for ErrorEnum {

    fn parse(input: ParseStream) -> SynResult<Self> {
        // Parse attributes
        let attrs: Vec<Attribute> = input.call(Attribute::parse_outer)?;

        // Parse visibility specifier (like `pub`)
        let visibility: syn::Visibility = input.parse()?;

        // Parse the `enum` keyword
        let _enum_token: Token![enum] = input.parse()?;

        // Parse the identifier (name of the enum)
        let ident: Ident = input.parse()?;

        // Parse the curly braces and the content within them
        let content;
        let _ = braced!(content in input);

        let mut variants: Vec<ErrorVariant> = Vec::new();
        while !content.is_empty() {
            let variant = content.parse()?;
            variants.push(variant);
            // Check for a trailing comma
            let _ = content.parse::<Option<Token![,]>>();
        }

        Ok(ErrorEnum {
            attrs,
            visibility,
            ident,
            variants,
        })
    }
}

impl Validate for ErrorEnum {
    fn validate(&self) -> bool {
        for variant in &self.variants {
            match variant {
                ErrorVariant::Basic { .. } => {},
                ErrorVariant::Wrapped { ty, .. } => {
                    if !ty.validate() {
                        return false;
                    }
                },
                ErrorVariant::Struct { fields, .. } => {
                    for field in fields {
                        if !field.ty.validate() {
                            return false;
                        }
                    }
                },
            }
        }
        true
    }
}

#[cfg(test)]
mod test_error_enum {

    use super::*;
    use syn::{parse_str, Ident, parse_quote};
    use proc_macro2::Span;

    #[test]
    fn test_parse() {
        let input_str = r#"
            #[derive(Clone)]
            pub enum FirstError {
                FormatError,
                IOError(std::io::Error),
                DeviceNotAvailable { device_name: String }
            }
            #[derive(PartialEq)]
            pub enum SecondError {
                AnotherError
            }
        "#;

        let parse_result: Result<ErrorTree, syn::Error> = syn::parse_str(input_str);

        match parse_result {
            Ok(parsed_tree) => println!("Parsed successfully: {:#?}", parsed_tree),
            Err(e) => panic!("Failed to parse: {}", e),
        }
    }

    fn test_error_enum(input_str: &str, vis: syn::Visibility, ident: Ident, variants: Vec<ErrorVariant>) {
        match parse_str::<ErrorEnum>(input_str) {
            Ok(parsed_enum) => {
                assert_eq!(parsed_enum.visibility, vis);
                assert_eq!(parsed_enum.ident, ident);
                assert_eq!(parsed_enum.variants, variants);
            }
            Err(e) => panic!("Failed to parse: {:?}", e),
        }
    }

    #[test]
    fn test_error_enum_parse_pub() {
        let input_str = "pub enum MyErrorEnum {
            FormatError,
            IOError(std::io::Error),
            DeviceNotAvailable { device_name: String }
        }";

        test_error_enum(input_str, parse_quote!(pub), Ident::new("MyErrorEnum", Span::call_site()), common_variants());
    }

    #[test]
    fn test_error_enum_parse_pub_super() {
        let input_str = "pub(super) enum MyErrorEnum {
            FormatError,
            IOError(std::io::Error),
            DeviceNotAvailable { device_name: String }
        }";

        test_error_enum(input_str, parse_quote!(pub(super)), Ident::new("MyErrorEnum", Span::call_site()), common_variants());
    }

    #[test]
    fn test_error_enum_parse_pub_crate() {
        let input_str = "pub(crate) enum MyErrorEnum {
            FormatError,
            IOError(std::io::Error),
            DeviceNotAvailable { device_name: String }
        }";

        test_error_enum(input_str, parse_quote!(pub(crate)), Ident::new("MyErrorEnum", Span::call_site()), common_variants());
    }

    #[test]
    fn test_error_enum_parse_no_vis() {
        let input_str = "enum MyErrorEnum {
            FormatError,
            IOError(std::io::Error),
            DeviceNotAvailable { device_name: String }
        }";

        test_error_enum(input_str, parse_quote!(), Ident::new("MyErrorEnum", Span::call_site()), common_variants());
    }

    fn common_variants() -> Vec<ErrorVariant> {
        vec![
            ErrorVariant::Basic{
                attrs: vec![],
                ident: Ident::new("FormatError", Span::call_site()),
                cmp_neq: false,
                display_format: None,
            },
            ErrorVariant::Wrapped{
                attrs: vec![],
                ident: Ident::new("IOError", Span::call_site()), 
                ty:    Box::new(parse_quote!(std::io::Error)),
                cmp_neq: false,
                display_format: None,
            },
            ErrorVariant::Struct{
                attrs:  vec![],
                ident:  Ident::new("DeviceNotAvailable", Span::call_site()), 
                fields: vec![
                    ErrorField {
                        ident: Ident::new("device_name", Span::call_site()),
                        ty: parse_quote!(String)
                    }
                ],
                cmp_neq: false,
                display_format: None,
            }
        ]
    }
}