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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// define-errors - copyright 2017 The define-errors authors.
// See the AUTHORS file for further copyright information.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A macro for defining error types.
//!
//! # Introduction
//!
//! The `define_errors` macro defines new error types. The error types
//! are enums that can hold other error values and/or error
//! descriptions. The macro is designed to allow the adding of
//! multiple levels of *context* to errors by sucessively wrapping
//! them, without losing any of the structured information contained
//! in the wrapped errors. It tries to be as simple as possible while
//! still achieving that goal.
//!
//! # Plain and wrapped errors
//!
//! To illustrate the syntax we will use examples. Firstly, the
//! following code will define a new error type called `MyError`, and
//! a macro `myerr_new` that can be used to create new values of type
//! `MyError`:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! use std::error::Error; // required use statement
//!
//! define_errors! {
//!     MyError myerr_new {}
//! }
//! # fn main() {}
//! ```
//!
//! Note that the `use` statement is *required*. However, you can use
//! another name binding if you need to. For example, this will also
//! work:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! use std::error::Error as StdError;
//!
//! define_errors! {
//!     MyError myerr_new {}
//! }
//! # fn main() {}
//! ```
//!
//! If the type being defined needs to be declared public you can add
//! the `pub` keyword before the name. Also, you can define multiple
//! error types at once (although in most cases one is all that is required):
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! define_errors! {
//!     pub MyError myerr_new {}
//!     MyError2 myerr2_new {}
//!     MyError3 myerr3_new {}
//! }
//! # fn main() {}
//! ```
//!
//! The `MyError` definition inserted by the macro above looks like
//! this:
//!
//! ```
//! pub enum MyError {
//!     Plain {
//!         description: String,
//!     },
//!     Wrapped {
//!         err: Box<MyError>,
//!         description: String,
//!     },
//! }
//! ```
//!
//! Since `MyError` is an enum, `MyError` values can be different
//! *variants*. In this case: `Plain` and `Wrapped`. `Plain` holds a
//! simple description string, but `Wrapped` holds a description and a
//! "wrapped" error, also of type `MyError`. The two variants can be
//! created in a simple way using the automatically defined
//! `myerr_new` macro, as shown in the next code example. The
//! description passed to `myerr_new` can be either a `&str` or a
//! `String`:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {}
//! # }
//! # fn main() {
//! let e_plain = myerr_new!(Plain, "a plain error");
//! let e_wrapped = myerr_new!(Wrapped, e_plain, "a wrapped error");
//! # }
//! ```
//!
//! When `e_wrapped` is converted to a string it will show the
//! description given to the `myerr_new` call, as well as the
//! description contained inside the wrapped error:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {}
//! # }
//! # fn main() {
//! # let e_plain = myerr_new!(Plain, "a plain error");
//! # let e_wrapped = myerr_new!(Wrapped, e_plain, "a wrapped error");
//! assert_eq!(format!("{}", e_wrapped), "a wrapped error: a plain error");
//! # }
//! ```
//!
//! In other words, `e_wrapped` has taken `e_plain` and added context
//! to it. It should also be noted that `e_wrapped` takes ownership of
//! `e_plain`.
//!
//! # Formatted descriptions
//!
//! There is a shortcut for creating formatted descriptions for
//! `Plain` and `Wrapped`. Instead of
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {}
//! # }
//! # fn main() {
//! let e_plain2 = myerr_new!(Plain, format!("{}: {}", "str1", "str2"));
//! # }
//! ```
//!
//! you can instead use
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {}
//! # }
//! # fn main() {
//! # let e_plain2 = myerr_new!(Plain, format!("{}: {}", "str1", "str2"));
//! let e_plain3 = myerr_new!(Plain, "{}: {}", "str1", "str2");
//! # assert_eq!(e_plain2.description(), e_plain3.description());
//! # }
//! ```
//!
//! This works for up to six `format` arguments, and for `Plain` and
//! `Wrapped` variants of `MyError`.
//!
//! # Existing error types
//!
//! `define_errors` can also define error types that holds existing
//! error types (such as `std::io::Error`) in corresponding
//! variants. For example:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! define_errors! {
//!     MyError myerr_new {
//!         Io: std::io::Error,
//!         Utf8: std::str::Utf8Error,
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! This defines an enum that looks like:
//!
//! ```
//! enum MyError {
//!     Plain {
//!         description: String,
//!     },
//!     Wrapped {
//!         err: Box<MyError>,
//!         description: String,
//!     },
//!     Io {
//!         err: std::io::Error,
//!     },
//!     Utf8 {
//!         err: std::str::Utf8Error,
//!     },
//! }
//! ```
//!
//! `Plain` and `Wrapped` variants are still present, but we now also
//! have `Io` and `Utf8`. These new variants of `MyError` can be
//! created in a similar fashion to before, again using
//! `myerr_new`. As when creating `Wrapped` variants, `myerr_new`
//! takes ownership of the errors being passed to it:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # use std::io::ErrorKind;
//! # define_errors! {
//! #     MyError myerr_new {
//! #         Io: std::io::Error,
//! #         Utf8: std::str::Utf8Error,
//! #     }
//! # }
//! # fn main() {
//! # let io_err = std::io::Error::new(ErrorKind::Other, "oh no!");
//! # let utf8_err = std::str::from_utf8(&[255]).unwrap_err();
//! // io_err: value of type std::io::Error
//! let e_io = myerr_new!(Io, io_err);
//!
//! // utf8_err: value of type std::str::Utf8Error
//! let e_utf8 = myerr_new!(Utf8, utf8_err);
//! # }
//! ```
//!
//! A nice thing is that the `From` traits for existing error types
//! are implemented as standard by `define_errors`. In this case:
//!
//! ```ignore
//! From<std::io::Error> for MyError
//! From<std::str::Utf8Error> for MyError
//! ```
//!
//! This means that when using the question mark operator or `try`
//! macro, existing error types get converted to our `MyError` type
//! automatically:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {
//! #         Io: std::io::Error,
//! #         Utf8: std::str::Utf8Error,
//! #     }
//! # }
//! type MyResult<T> = Result<T, MyError>;
//!
//! fn decode_some_utf8() -> MyResult<()> {
//!     // std::str::Utf8Error errors here are converted to MyError
//!     std::str::from_utf8(&[255])?;
//!     // this line is never reached - &[255] is bad utf8
//!     unreachable!();
//! }
//!
//! fn main() {
//!     match decode_some_utf8() {
//!         Ok(_) => unreachable!(),
//!         Err(ref e) => {
//!             assert_eq!(e.description(),
//!                        "invalid utf-8: corrupt contents");
//!         }
//!     }
//! }
//! ```
//!
//! Lastly, `MyError` also implements the `std::error::Error` trait,
//! so you can create trait objects if you wish:
//!
//! ```
//! # #[macro_use] extern crate define_errors;
//! # use std::error::Error;
//! # define_errors! {
//! #     MyError myerr_new {
//! #     }
//! # }
//!
//! fn use_trait_object(err: &std::error::Error)  {
//!     // do stuff with err
//!     let _ = err.description();
//!     let _ = err.cause();
//! }
//!
//! fn main() {
//!     let e = myerr_new!(Plain, "a plain old error");
//!     use_trait_object(&e);
//! }
//! ```
//!
//! That is all there is to `define_errors`.
//!
//! # A complete example
//!
//! Here is a complete example illustrating most of the above:
//!
//! ```
//! #[macro_use]
//! extern crate define_errors;
//!
//! use std::error::Error;
//! use std::fs::File;
//! use std::io::Read;
//! use std::path::Path;
//!
//! define_errors! {
//!     MyError myerr_new {
//!         Io: std::io::Error,
//!     }
//! }
//!
//! type MyResult<T> = Result<T, MyError>;
//!
//! fn load_file(path: &Path) -> MyResult<Vec<u8>> {
//!     // std::io::Error values here are automatically converted to MyError
//!     let mut f = File::open(path)?;
//!     let mut buffer = Vec::new();
//!     let _ = f.read_to_end(&mut buffer)?;
//!     Ok(buffer)
//! }
//!
//! fn load_file_add_context(path: &Path) -> MyResult<Vec<u8>> {
//!     if path.starts_with("/forbidden_area") {
//!         return Err(myerr_new!(Plain,
//!                               "{}: no access",
//!                               path.to_string_lossy()));
//!     }
//!     load_file(path).map_err(|e| {
//!         // add path context to errors returned from load_file
//!         myerr_new!(Wrapped, e, path.to_string_lossy())
//!     })
//! }
//!
//! fn main() {
//!     let result = load_file_add_context(Path::new("/path/to/invalid/file"));
//!     match result {
//!         Ok(_) => unreachable!(),
//!         Err(ref e) => {
//!             assert_eq!(format!("{}", e),
//!                        "/path/to/invalid/file: entity not found");
//!             assert_eq!(e.description(),
//!                        "/path/to/invalid/file: entity not found");
//!         }
//!     }
//! }
//! ```

/// A macro for defining error types.
///
/// See the crate documentation for details.
#[macro_export]
macro_rules! define_errors {
    (@implementations $name:ident $mcname:ident ($($vrnt:ident $err:path)*)) =>
    {
        $(
            impl From<$err> for $name {
                fn from(e: $err) -> $name {
                    $name::$vrnt { err: e }
                }
            }
        )*
        impl ::std::fmt::Display for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) ->
                ::std::fmt::Result {
                match *self {
                    $name::Plain { description: ref s } => write!(f, "{}", s),
                    $name::Wrapped { err: _, description: ref s } => {
                        write!(f, "{}", s)
                    }
                    $(
                        $name::$vrnt { err: ref e } => {
                            write!(f, "{}", e.description())
                        }
                    )*
                }
            }
        }
        impl ::std::error::Error for $name {
            fn description(&self) -> &str {
                match *self {
                    $name::Plain { description: ref s } => &*s,
                    $name::Wrapped { err: _, description: ref s } => &*s,
                    $(
                        $name::$vrnt { err: ref e } => e.description(),
                    )*
                }
            }
            fn cause(&self) -> Option<&::std::error::Error> {
                match *self {
                    $name::Plain { description: _ } => None,
                    $name::Wrapped { err: ref e, description: _ } => Some(e),
                    $(
                        $name::$vrnt { err: ref e } => Some(e),
                    )*
                }
            }
        }
        macro_rules! $mcname {
            (Plain, $a1:expr) => {
                $name::Plain{description: format!("{}", $a1)}
            };
            (Plain, $a1:expr, $a2:expr) => {
                $name::Plain{description: format!($a1, $a2)}
            };
            (Plain, $a1:expr, $a2:expr, $a3:expr) => {
                $name::Plain{description: format!($a1, $a2, $a3)}
            };
            (Plain, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => {
                $name::Plain{description: format!($a1, $a2, $a3, $a4)}
            };
            (Plain, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => {
                $name::Plain{description: format!($a1, $a2, $a3, $a4, $a5)}
            };
            (Plain, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => {
                $name::Plain{description: format!($a1, $a2, $a3, $a4, $a5, $a6)}
            };
            (Wrapped, $wrapped_err:expr, $a1:expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!("{}", $a1),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            (Wrapped, $wrapped_err:expr, $a1:expr, $a2:expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!($a1, $a2),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            (Wrapped, $wrapped_err:expr, $a1:expr, $a2:expr, $a3:expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!($a1, $a2, $a3),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            (Wrapped, $wrapped_err:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!($a1, $a2, $a3, $a4),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            (Wrapped, $wrapped_err:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!($a1, $a2, $a3, $a4, $a5),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            (Wrapped, $wrapped_err:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6: expr) => {
                $name::Wrapped{
                    description: format!("{}: {}",
                                         format!($a1, $a2, $a3, $a4, $a5, $a6),
                                         $wrapped_err.description()),
                    err: Box::new($wrapped_err)
                }
            };
            $(
                ($vrnt, $err_val:expr) => {
                    $name::$vrnt{err: $err_val}
                };
            )*
        }
    };
    (pub $name:ident $mcname:ident {$($vrnt:ident: $err:path,)*} $($tt:tt)*)
        => {
        #[derive(Debug)]
        #[allow(dead_code)]
        pub enum $name {
            /// A plain error with a description.
            Plain { description: String },
            /// A wrapped error with a description.
            Wrapped {
                err: Box<$name>,
                description: String,
            },
            $(
                /// A specific error of the given type
                $vrnt {
                    err: $err,
                },
            )*
        }
        define_errors!(@implementations $name $mcname ($($vrnt $err)*));
        define_errors!($($tt)*);
    };
    ($name:ident $mcname:ident {$($vrnt:ident: $err:path,)*} $($tt:tt)*)
        => {
        #[derive(Debug)]
        #[allow(dead_code)]
        enum $name {
            /// A plain error with a description.
            Plain { description: String },
            /// A wrapped error with a description.
            Wrapped {
                err: Box<$name>,
                description: String,
            },
            $(
                /// A specific error of the given type
                $vrnt {
                    err: $err,
                },
            )*
        }
        define_errors!(@implementations $name $mcname ($($vrnt $err)*));
        define_errors!($($tt)*);
    };
    () => {};
}