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
pub use paste::paste;

/**

`define_error!` is the main macro that implements a mini DSL to
define error types using `flex-error`. The DSL syntax
is as follows:

```ignore
define_error! { ErrorName;
  SubErrorWithFieldsAndErrorSource
    { field1: Type1, field2: Type2, ... }
    [ ErrorSource ]
    | e | { format_args!(
      "format error message with field1: {}, field2: {}, source: {}",
      e.field1, e.field2, e.source)
    },
  SubErrorWithFieldsOnly
    { field1: Type1, field2: Type2, ... }
    | e | { format_args!(
      "format error message with field1: {}, field2: {}",
      e.field1, e.field2)
    },
  SubErrorWithSourceOnly
    [ ErrorSource ]
    | e | { format_args!(
      "format error message with source: {}",
      e.source)
    },
  SubError
    | e | { format_args!(
      "only suberror message")
    },
}
```

Behind the scene, `define_error!` does the following:

  - Define an enum with the postfix `Detail`, e.g. an error named
    `FooError` would have the enum `FooErrorDetail` defined.

  - Define the error name as a type alias to
    [`ErrorReport<ErrorNameDetail, DefaultTracer>`](crate::ErrorReport).
    e.g. `type FooError = ErrorReport<FooErrorDetail, DefaultTracer>;`.

  - For each suberror, does the following:

      - Define a variant with the suberror name in the detail enum.
        e.g. a `Bar` suberror in `FooError` becomes a `Bar`
        variant in `FooErrorDetail`.

      - Define a struct with the `Subdetail` postfix. e.g.
        `Bar` would have a `BarSubdetail` struct.

        - The struct contains all named fields if specified.

        - If an error source is specified, a `source` field is
          also defined with the type
          [`AsErrorDetail<ErrorSource>`](crate::AsErrorDetail).
          e.g. a suberror with
          [`DisplayError<SourceError>`](crate::DisplayError)
          would have the field `source: SourceError`.
          Because of this, the field name `source` is reserved and
          should not be present in other detail fields.

      - Implement [`Display`](std::fmt::Display) for the suberror
        using the provided formatter to format the arguments.
        The argument type of the formatter is the suberror subdetail struct.

      - Define a suberror constructor function in snake case with the postfix
        `_error`. e.g. `Bar` would have the constructor function `bar_error`.

        - The function accepts arguments according to the named fields specified.

        - If an error source is specified, the constructor function also accepts
          a last argument of type [`AsErrorSource<ErrorSource>`](crate::AsErrorSource).
          e.g. a suberror with [`DisplayError<SourceError>`](crate::DisplayError)
          would have the last argument of type `SourceError` in the constructor function.

        - The function returns the main error type. e.g. `FooError`, which is alias to
          [`ErrorReport<FooErrorDetail, DefaultTrace>`](crate::ErrorReport).

We can demonstrate the macro expansion of `define_error!` with the following example:

```ignore
// An external error type implementing Display
use external_crate::ExternalError;

define_error! { FooError;
  Bar
    { code: u32 }
    [ DisplayError<ExternalError> ]
    | e | { format_args!("Bar error with code {}", e.code) },
  Baz
    { extra: String }
    | e | { format_args!("General Baz error with extra detail: {}", e.extra) }
}
```

The above code will be expanded into something like follows:

```ignore
pub type FooError = Report<FooErrorDetail, DefaultTracer>;

#[derive(Debug)]
pub enum FooErrorDetail {
    Bar(BarSubdetail),
    Baz(BazSubdetail),
}

#[derive(Debug)]
pub struct BarSubdetail {
    pub code: u32,
    pub source: ExternalError
}

#[derive(Debug)]
pub struct BazSubdetail {
    pub extra: String
}

fn bar_error(code: u32, source: ExternalError) -> FooError { ... }
fn baz_error(extra: String) -> FooError { ... }

impl Display for BarSubdetail {
  fn fmt(&self, f: &mut Formatter<'_>) -> Result {
    let e = self;
    write!(f, "{}", format_args!("Bar error with code {}", e.code))
  }
}

impl Display for BazSubdetail {
  fn fmt(&self, f: &mut Formatter<'_>) -> Result {
    let e = self;
    write!(f, "{}", format_args!("General Baz error with extra detail: {}", e.code))
  }
}

impl Display for FooErrorDetail { ... }
```

For the detailed macro expansion, you can use [cargo-expand](https://github.com/dtolnay/cargo-expand)
to expand the Rust module that uses `define_error!` to see how the error definition
gets expanded.

Because `FooError` is defined as an alias to [`ErrorReport`](crate::ErrorReport),
it automatically implements [`ErrorSource`](crate::ErrorSource) and can be used
as a source in other error definitions. For example:

```ignore
define_error! { QuuxError;
  Foo
    { action: String }
    [ FooError ]
    | e | { format_args!("error arised from Foo when performing action {}", e.action) },
  ...
}
```

Would be expanded to include the following definitions:

```ignore
pub struct FooSubdetail {
  pub action: String,
  pub source: FooErrorDetail
}

pub fn foo_error(action: String, source: FooError) { ... }
```

In the formatter for QuuxErrorDetail::Foo, we can also see that it does not
need to include the error string from `FooError`. This is because the error
tracer already takes care of the source error trace, so the full trace is
automatically tracked inside `foo_error`. The outer error only need to
add additional detail about what caused the source error to be raised.

**/
#[macro_export]
macro_rules! define_error {
  ( $($expr:tt)+ ) => {
    define_error_with_tracer![ $crate::DefaultTracer; $( $expr )* ];
  };
}

/// This macro allows error types to be defined with custom error tracer types
/// other than [`DefaultTracer`](crate::DefaultTracer). Behind the scene,
/// a macro call to `define_error!{ ... } really expands to
/// `define_error_with_tracer!{ flex_error::DefaultTracer; ... }
#[macro_export]
macro_rules! define_error_with_tracer {
  ( $tracer:ty; $name:ident; $(
      $suberror:ident
      $( { $( $arg_name:ident : $arg_type:ty ),* $(,)? } )?
      $( [ $source:ty ] )?
      | $formatter_arg:pat | $formatter:expr
    ),* $(,)?
  ) => {
    $crate::macros::paste![
      #[derive(Debug)]
      pub enum [< $name Detail >] {
        $(
          $suberror (
            [< $suberror Subdetail >]
          ),
        )*
      }

      $(
        $crate::define_suberror! {
          $tracer;
          $name;
          $suberror;
          ( $( $( $arg_name : $arg_type ),* )? )
          $( [ $source ] )?
        }

        impl core::fmt::Display for [< $suberror Subdetail >] {
          fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            let $formatter_arg = self;
            write!(f, "{}",  $formatter)
          }
        }
      )*

      pub type $name = $crate::ErrorReport< [< $name Detail >], $tracer >;

      impl core::fmt::Display for [< $name Detail >] {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
          match self {
            $(
              Self::$suberror( suberror ) => {
                write!( f, "{}",  suberror )
              }
            ),*
          }
        }
      }

      $(
        $crate::define_error_constructor! {
          $tracer;
          $name;
          $suberror;
          ( $( $( $arg_name : $arg_type ),* )? )
          $( [ $source ] )?
        }
      )*
    ];
  };
}

/// Internal macro used to define suberror structs
#[macro_export]
macro_rules! define_suberror {
  ( $tracer:ty;
    $name:ident;
    $suberror:ident;
    ( $( $arg_name:ident: $arg_type:ty ),* )
    $( [ $source:ty ] )?
  ) => {
    $crate::macros::paste! [
      #[derive(Debug)]
      pub struct [< $suberror Subdetail >] {
        $( pub $arg_name: $arg_type, )*
        $( pub source: $crate::AsErrorDetail<$source, $tracer> )?
      }
    ];
  };
}

/// Internal macro used to define suberror constructor functions
#[macro_export]
macro_rules! define_error_constructor {
  ( $tracer:ty;
    $name:ident;
    $suberror:ident;
    ( $( $arg_name:ident: $arg_type:ty ),* )
  ) => {
    $crate::macros::paste! [
      pub fn [< $suberror:snake _error >](
        $( $arg_name: $arg_type, )*
      ) -> $name
      {
        let detail = [< $name Detail >]::$suberror([< $suberror Subdetail >] {
          $( $arg_name, )*
        });

        let trace = $tracer::new_message(&detail);
        $crate::ErrorReport {
          detail,
          trace,
        }
      }
    ];
  };
  ( $tracer:ty;
    $name:ident;
    $suberror:ident;
    ( $( $arg_name:ident: $arg_type:ty ),* )
    [ $source:ty ]
  ) => {
    $crate::macros::paste! [
      pub fn [< $suberror:snake _error >](
        $( $arg_name: $arg_type, )*
        source: $crate::AsErrorSource< $source, $tracer >
      ) -> $name
      {
        $crate::ErrorReport::trace_from::<$source, _>(source,
          | source_detail | {
            [< $name Detail >]::$suberror([< $suberror Subdetail >] {
              $( $arg_name, )*
              source: source_detail,
            })
          })
      }
    ];
  };
}