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
//! The heart of this crate is [`ErrorStack`],
//! its a derive macro to make generating enums and structs compatible
//! with [error_stack](https://docs.rs/error-stack/latest/error_stack/).
//! Even though the sole purpose is provind a better DX with `error_stack`
//! this derive macro can actually be used with any other error system
//! since the crate itself doesn't depend on `error_stack` all it does
//! is makes [`std::error::Error`] and [`std::fmt::Display`] implementations
//! easy.
//!
//! ## Usage with and without `error_stack`
//!
//! ### With
//!
//! > Note:
//! > As of right-now `no-std` is not supported
//!
//! With `error_stack` you get the `Report` and their fancy attachments,
//! context, frames, etc. features, which to say the least are
//! pretty cool and helpful for error handling & debugging.
//!
//! ```
//! use error_stack::{IntoReport, Result, ResultExt};
//! use error_stack_derive::ErrorStack;
//!
//! #[derive(ErrorStack, Debug)]
//! #[error_message("An exception occured in foo")]
//! struct FooError;
//!
//! fn main() -> Result<(), FooError> {
//! let contents = std::fs::read_to_string("foo.txt")
//! .report()
//! .change_context(FooError)
//! .attach_printable("Unable to read foo.txt file")?;
//!
//! println!("{contents}");
//!
//! Ok(())
//! }
//! ```
//!
//! ### Without
//!
//! Ofcourse this crate doesn't enforce the usage of `error_stack`
//! infact you can use it with any other error handling crate,
//! just like this
//!
//! ```
//! use error_stack_derive::ErrorStack;
//!
//! #[derive(ErrorStack, Debug)]
//! #[error_message(&format!("An exception occured with foo: {}", self.0))]
//!
//! struct FooError(String);
//! fn main() -> Result<(), FooError> {
//! let contents = std::fs::read_to_string("foo.txt").map_err(|e| FooError(e.to_string()))?;
//!
//! println!("{contents}");
//!
//! Ok(())
//! }
//! ```
//!
//! ## Looking into the expansion
//!
//! This crate, specifically the derive macro, does 2 things, <br />
//! one, implements [`std::error::Error`] <br />
//! two, implements [`std::fmt::Display`] <br />
//! you can derive a struct or an enum, the trait impl are pretty
//! simple
//!
//! For a struct:
//!
//! ```
//! // #[derive(error_stack_derive::ErrorStack, Debug)]
//! // #[error_message("An exception occured in foo")]
//! // struct FooError;
//!
//! #[derive(Debug)]
//! struct FooError;
//!
//! impl std::fmt::Display for FooError {
//! fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//! fmt.write_str("An exception occured in foo")
//! }
//! }
//!
//! impl std::error::Error for FooError {}
//! ```
//!
//! For an enum:
//!
//! ```
//! // #[derive(error_stack_derive::ErrorStack, Debug)]
//! // enum FooErrors {
//! // #[error_message("An exception in bar")]
//! // BarError,
//! // #[error_message(&format!("Error in baz ({unnamed0})"))]
//! // BazError(String),
//! // #[error_message(&format!("Error in qux ({start}, {end})"))]
//! // QuxError {
//! // start: u64,
//! // end: u64,
//! // }
//! // };
//!
//! #[derive(Debug)]
//! enum FooErrors {
//! BarError,
//! BazError(String),
//! QuxError {
//! start: u64,
//! end: u64,
//! }
//! };
//!
//! impl std::fmt::Display for FooErrors {
//! fn fmt(&self, _____fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//! match self {
//! Self::BarError => _____fmt.write_str(&format!("[{name}] An error occured; {:?}", name = "FooErrors", self)),
//! Self::BazError(unnamed0) => _____fmt.write_str(&format!("Error in baz ({unnamed0})")),
//! Self::QuxError { start, end } => _____fmt.write_str(&format!("Error in qux ({start}, {end})")),
//! }
//! }
//! }
//!
//! impl std::error::Error for FooErrors {}
//! ```
//!
//! As you can see its a pretty simple macro but definitely helps when
//! you have a large code base and error handling definitely becomes dreadful.
//! Read up the doc comments of [`ErrorStack`] for more information.
//!
use TokenStream;
use ;
use ;
/// A derive-macro to easily create enums and structs compatible with
/// error_stack. You can use a struct or an enum with it
///
///
/// ## Panic
///
/// - When input cannot be passed as [`syn::DeriveInput`]
/// - When the derive data is not one of [`syn::Data::Enum`] or
/// [`syn::Data::Struct`]
///
///
/// ## Usage
///
/// ```
/// use error_stack_derive::ErrorStack;
///
/// #[derive(ErrorStack, Debug)]
/// // error_message tokens can be any token stream as long as it evaluates
/// // to a &str
/// #[error_message("An error occured in Foo")]
/// struct FooError;
///
/// #[derive(ErrorStack, Debug)]
/// // The tokens are passed to the [`std::fmt::Formatter::write_str`]
/// // method of the [`std::fmt::Formatter`] in the automatically
/// // implemented Display impl. Passing an error message is mandatory
/// // for structs while its not for enums
/// // So you can do this too!
/// #[error_message(&format!("An internal error occured: {}", self.0))]
/// struct InternalError<A>(pub A)
/// where
/// A: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static;
///
///
/// // And ofcourse enums are supported too
/// #[derive(ErrorStack, Debug)]
/// // This is the default error message, this is used when a variant
/// // doesn't have a dedicated error message
/// // When a default error message is not specified and an enum doesn't
/// // have a dedicated message,
/// // `&format!("[{name}] An error occured; {:?}", name = #struct_name, self)` is passed to
/// // [`std::fmt::Formatter::write_str`]
/// #[error_message("Default error message")]
/// enum EncoderError {
/// // For struct variants the name of the fields are left unchanged
/// // but for tuple variants they are named `unnamed{pos}`
/// #[error_message(&format!("Couldn't serialize data: {:?}", unnamed0))]
/// SerializeError(String),
/// DeserializeError,
/// }
/// ```