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() -> Self {
24 Self(#first_field_type::new())
25 }
26
27 pub fn from_msg(error: impl std::fmt::Display + Send + Sync + 'static) -> Self {
28 Self(#first_field_type::from_msg(error))
29 }
30 }
31
32 impl ErrorStacks<ErrorCode> for #name {
33 fn err_code(&self) -> Option<&ErrorCode> {
34 self.0.err_code()
35 }
36
37 fn with_err_code(self, code: ErrorCode) -> Self {
38 Self(self.0.with_err_code(code))
39 }
40
41 fn with_no_err_code(self) -> Self {
42 Self(self.0.with_no_err_code())
43 }
44
45 fn err_uri(&self) -> Option<&str> {
46 self.0.err_uri()
47 }
48
49 fn with_err_uri(self, uri: String) -> Self {
50 Self(self.0.with_err_uri(uri))
51 }
52
53 fn with_no_err_uri(self) -> Self {
54 Self(self.0.with_no_err_uri())
55 }
56
57 fn with_err_msg(self, error: impl std::fmt::Display + Send + Sync + 'static) -> Self {
58 Self(self.0.with_err_msg(error))
59 }
60
61 fn with_no_err_msg(self) -> Self {
62 Self(self.0.with_no_err_msg())
63 }
64
65 fn stack_err(self) -> Self {
66 Self(self.0.stack_err())
67 }
68
69 fn stack_err_msg(self, error: impl std::fmt::Display + Send + Sync + 'static) -> Self {
70 Self(self.0.stack_err_msg(error))
71 }
72 }
73
74 impl std::fmt::Display for #name {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 std::fmt::Display::fmt(&self.0, f)
77 }
78 }
79
80 impl std::fmt::Debug for #name {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 std::fmt::Debug::fmt(&self.0, f)
83 }
84 }
85
86 impl std::error::Error for #name {
87 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
88 self.0.source()
89 }
90 }
91
92 impl<E> From<E> for #name
93 where
94 StackError: From<E>,
95 {
96 fn from(err: E) -> Self {
97 Self(StackError::from(err))
98 }
99 }
100 };
101
102 TokenStream::from(expanded)
103}