stackerror_impl/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, DeriveInput};
4
5#[proc_macro_attribute]
6pub fn derive_stack_error(_attr: TokenStream, item: TokenStream) -> TokenStream {
7    let input = parse_macro_input!(item as DeriveInput);
8    let name = &input.ident;
9    let first_field_type = if let syn::Data::Struct(data) = &input.data {
10        if let Some(field) = data.fields.iter().next() {
11            &field.ty
12        } else {
13            panic!("Expected at least one field");
14        }
15    } else {
16        panic!("Expected a struct");
17    };
18
19    let expanded = quote! {
20        #input
21
22        impl #name {
23            pub fn new(error: impl std::fmt::Display + Send + Sync + 'static) -> Self {
24                Self(#first_field_type::new(error))
25            }
26        }
27
28        impl ErrorStacks<ErrorCode> for #name {
29            fn err_code(&self) -> Option<&ErrorCode> {
30                self.0.err_code()
31            }
32
33            fn with_err_code(self, code: Option<ErrorCode>) -> Self {
34                Self(self.0.with_err_code(code))
35            }
36
37            fn err_uri(&self) -> Option<&str> {
38                self.0.err_uri()
39            }
40
41            fn with_err_uri(self, uri: Option<String>) -> Self {
42                Self(self.0.with_err_uri(uri))
43            }
44
45            fn stack_err(self, error: impl std::fmt::Display + Send + Sync + 'static) -> Self {
46                Self(self.0.stack_err(error))
47            }
48        }
49
50        impl std::fmt::Display for #name {
51            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52                self.0.fmt(f)
53            }
54        }
55
56        impl std::fmt::Debug for #name {
57            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58                self.0.fmt(f)
59            }
60        }
61
62        impl std::error::Error for #name {
63            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
64                self.0.source()
65            }
66        }
67    };
68
69    TokenStream::from(expanded)
70}