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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
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")
        },
    }
  }
  ```

  ## Macro Expansion

  Behind the scene, for an error named `MyError`, `define_error!`
  does the following:

    - Define a struct in the form

      ```ignore
      pub struct MyError(pub MyErrorDetail, pub flex_error::DefaultTracer)
      ```

    - Define an enum in the form

      ```ignore
      pub enum MyError { ... }
      ```

      For each suberror named `MySubError`, does the following:

        - Define a variant in `MyError` in the form
          ```ignore
          pub enum MyError { ..., MySubError(MySubErrorSubdetail) ,... }
          ```

          - Implement [`core::fmt::Debug`] and [`core::fmt::Display`]
            for `MyError`.

          - If the `"std"` feature is enabled on the `flex-error` crate,
            it will generate an `impl` block for [`std::error::Error`].

          - Implement [`ErrorSource<DefaultTracer>`](crate::ErrorSource)
            for `MyError`, with `MyErrorDetail` being the `Detail` type,
            and `MyError` being the `Source` type.

          - Implement the following helper methods in `impl MyError {...}`:

            - `pub fn detail(&self) -> &MyErrorDetail`

            - `pub fn trace(&self) -> flex_error::DefaultTracer`

            - `pub fn add_trace<E: Display>(self, e: &E) -> MyError`

        - Define a struct in the form

          ```ignore
          pub struct MySubErrorSubdetail { ... }
          ```

          - For each field named `my_field: MyFieldType`, define a struct
            field in the form

            ```ignore
            struct MySubErrorSubdetail { ..., pub my_field: MyFieldType, ... }
            ```

          - If the sub-error has an error source `MySource` implementing
            [`ErrorSource<DefaultTracer>`](crate::ErrorSource), define a `source` field
            in the form

            ```ignore
            struct MySubErrorSubdetail { ..., pub source: MySource::Detail }
            ```

          - Implement [`core::fmt::Display`] in the form

            ```ignore
            impl Display for MySubErrorSubdetail { ... }
            ```

        - Define a snake-cased error constructor method in `MyError` in the form

          ```ignore
          impl MyError { pub fn my_sub_error(...) -> MyError { ... } }
          ```

          - For each field named `my_field: MyFieldType`, define a
            function argument in the form

            ```ignore
            fn my_sub_error(..., my_field: MyFieldType, ...)
            ```

          - If the sub-error has an error source `MySource` implementing
            [`ErrorSource`](crate::ErrorSource), define a `source` field in the form

            ```ignore
            fn my_sub_error(..., source: MySource::Detail)
            ```

  ## Formatter

  For each sub-error definition, a formatter needs to be provided using the
  closure syntax. For example, the following definition:


  ```ignore
  MyError {
    MySubError
      { code: u32 }
      [ MySource ]
      | e | { format_args!("error with code {}", e.code) },
    ...
  }
  ```

  will include the following expansion:

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

  Note that there is no need to manually display the error source, as the
  source is already automatically traced by the error tracer.

  If a sub-error do not have any field, we can write a simpler form of the
  formatter like:

  ```ignore
  MyError {
    MySubError
      | _ | { "something went wrong" },
    ...
  }
  ```

  ## Example Definition

  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 struct FooError(pub FooErrorDetail, pub flex_error::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 ::core::fmt::Display for BarSubdetail {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
      let e = self;
      write!(f, "{}", format_args!("Bar error with code {}", e.code))
    }
  }

  impl ::core::fmt::Display for BazSubdetail {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::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.

  Since `FooError` implements [`ErrorSource`](crate::ErrorSource), it can be used
  directly as a error 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.

  ## Attributes

  `define_error!` supports adding attributes to the generated error types.

  ### First `doc` Attribute

  If the first attribute is a [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html)
  attribute, it is attached to the main error struct. For example:

  ```ignore
  define_error! {
    /// Documentation for MyError
    MyError { ... }
  }
  ```

  will include the following expansion:

  ```ignore
  #[doc = "Documentation for MyError"]
  pub struct MyError(pub MyErrorDetail, pub flex_error::DefaultTracer);
  ```

  ## Common Attributes

  For all other attributes defined on the main error type,
  they are defined on the _error detail_ and _sub-errors type. For example:


  ```ignore
  define_error! {
    #[derive(Debug, Clone)]
    MyError {
      Foo
        { ... }
        | _ | { "foo error" },

      Bar
        { ... }
        | _ | { "bar error" },
    }
  }
  ```

  will include the following expansion:

  ```ignore
  pub struct MyError(pub MyErrorDetail, pub flex_error::DefaultTracer);

  #[derive(Debug, Clone)]
  pub enum MyErrorDetail { ... }

  #[derive(Debug, Clone)]
  pub struct FooSubdetail { ... }

  #[derive(Debug, Clone)]
  pub struct BarSubdetail { ... }
  ```

  Note that we do not add the `derive` attribute to the main error struct
  `MyError`. This is because the [`DefaultTracer`](crate::DefaultTracer)
  type is opaque, and auto deriving traits like `Clone` on it is
  generally not supported.

  If you need the main error type to implement certain traits,
  you can instead define your own custom `impl` definition for it.

  ## Sub Attributes

  We can also define custom attributes for only the sub-error.
  In that case, the attribute is given to the sub-detail type.
  For example:

  ```ignore
  define_error! {
    MyError {
      /// Documentation for Foo
      #[derive(Clone)]
      Foo
        { ... }
        | _ | { "foo error" },

      ...
    }
  }
  ```

  will include the following expansion:

  ```ignore
  #[doc = "Documentation for Foo"]
  #[derive(Clone)]
  pub struct FooSubdetail { ... }
  ```

  Note that if no attribute is given to the main error,
  the `#[derive(Debug)]` trait is added by default.
  So there is no need to derive it again in the
  sub-errors.

**/

#[macro_export]
macro_rules! define_error {
  ( $name:ident
    { $($suberrors:tt)* }
  ) => {
    $crate::define_error_with_tracer![
      @tracer( $crate::DefaultTracer ),
      @attr[ derive(Debug) ],
      @name( $name ),
      @suberrors{ $($suberrors)* }
    ];
  };
  ( #[doc = $doc:literal] $( #[$attr:meta] )*
    $name:ident
    { $($suberrors:tt)* }
  ) => {
    $crate::define_error_with_tracer![
      @tracer( $crate::DefaultTracer ),
      @doc( $doc ),
      @attr[ $( $attr ),* ],
      @name( $name ),
      @suberrors{ $($suberrors)* }
    ];
  };
  ( $( #[$attr:meta] )*
    $name:ident
    { $($suberrors:tt)* }
  ) => {
    $crate::define_error_with_tracer![
      @tracer( $crate::DefaultTracer ),
      @attr[ $( $attr ),* ],
      @name( $name ),
      @suberrors{ $($suberrors)* }
    ];
  };
  ( @with_tracer[ $tracer:ty ]
    $name:ident,
    { $($suberrors:tt)* }
  ) => {
    $crate::define_error_with_tracer![
      @tracer( $tracer ),
      @attr[ derive(Debug) ],
      @name( $name ),
      @suberrors{ $($suberrors)* }
    ];
  };
  ( @with_tracer[ $tracer:ty ]
    $( #[$attr:meta] )*
    $name:ident,
    @suberrors{ $($suberrors:tt)* }
  ) => {
    $crate::define_error_with_tracer![
      @tracer( $tracer ),
      @attr[ $( $attr ),* ],
      @name( $name ),
      @suberrors{ $($suberrors)* }
    ];
  };
}

/// 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]
#[doc(hidden)]
macro_rules! define_error_with_tracer {
  ( @tracer( $tracer:ty ),
    $( @doc($doc:literal), )?
    @attr[ $( $attr:meta ),* ],
    @name($name:ident),
    @suberrors{ $($suberrors:tt)* } $(,)?
  ) => {
    $crate::macros::paste![
      $crate::define_main_error!(
        @tracer( $tracer ),
        $( @doc( $doc ), )?
        @name( $name )
      );

      $crate::define_error_detail!(
        @attr[ $( $attr ),* ] ,
        @name( $name ),
        @suberrors{ $($suberrors)* });

      $crate::define_suberrors! {
        @tracer($tracer),
        @attr[ $( $attr ),* ],
        @name($name),
        { $( $suberrors )* }
      }
    ];
  };
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_main_error {
  ( @tracer( $tracer:ty ),
    $( @doc( $doc:literal ), )?
    @name( $name:ident ) $(,)?
  ) => {
    $crate::macros::paste![
      $crate::define_main_error_struct!(
        @tracer( $tracer ),
        $( @doc($doc), )?
        @name( $name )
      );

      impl $crate::ErrorSource<$tracer> for $name {
        type Source = Self;
        type Detail = [< $name Detail >];

        fn error_details($name(detail, trace): Self) -> ([< $name Detail >], Option<$tracer>) {
            (detail, Some(trace))
        }
      }

      impl ::core::fmt::Debug for $name
      where
          $tracer: ::core::fmt::Debug,
      {
          fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
              ::core::fmt::Debug::fmt(self.trace(), f)
          }
      }

      impl ::core::fmt::Display for $name
      where
          $tracer: ::core::fmt::Debug,
      {
          fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>)
            -> ::core::fmt::Result
          {
              // Always use `Debug` to format error traces, as eyre do not
              // include full back trace information in normal Display mode.
              ::core::fmt::Debug::fmt(self.trace(), f)
          }
      }

      $crate::define_std_err_impl!(
        @tracer( $tracer ),
        @name( $name )
      );

      impl $name {
        pub fn detail(&self) -> &[< $name Detail >] {
            &self.0
        }

        pub fn trace(&self) -> &$tracer {
            &self.1
        }

        pub fn add_trace<E: ::core::fmt::Display>(self, message: &E) -> Self
        where
            $tracer: $crate::ErrorMessageTracer,
        {
            let detail = self.0;
            let trace = $crate::ErrorMessageTracer::add_message(self.1, message);
            $name(detail, trace)
        }

        pub fn trace_from<E, Cont>(source: E::Source, cont: Cont) -> Self
        where
            E: $crate::ErrorSource<$tracer>,
            $tracer: $crate::ErrorMessageTracer,
            Cont: FnOnce(E::Detail) -> [< $name Detail >],
        {
            let (detail1, m_trace1) = E::error_details(source);
            let detail2 = cont(detail1);
            match m_trace1 {
                Some(trace1) => {
                    let trace2 = $crate::ErrorMessageTracer::add_message(trace1, &detail2);
                    $name(detail2, trace2)
                }
                None => {
                    let trace2 = $crate::ErrorMessageTracer::new_message(&detail2);
                    $name(detail2, trace2)
                }
            }
        }
      }
    ];
  }
}

// define the impl for `std::error::Error` only in std mode
#[cfg(feature = "std")]
#[macro_export]
#[doc(hidden)]
macro_rules! define_std_err_impl {
  ( @tracer( $tracer:ty ),
    @name( $name:ident ) $(,)?
  ) => {
    $crate::macros::paste![
      impl ::std::error::Error for $name
      where
          [< $name Detail >]: ::core::fmt::Display,
          $tracer: ::core::fmt::Debug + ::core::fmt::Display,
          $tracer: $crate::ErrorMessageTracer,
      {
          fn source(&self) -> ::core::option::Option<&(dyn ::std::error::Error + 'static)> {
              $crate::ErrorMessageTracer::as_error(self.trace())
          }
      }
    ];
  }
}

// do not define the impl for `std::error::Error` when in no_std mode
#[cfg(not(feature = "std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! define_std_err_impl {
    ( @tracer( $tracer:ty ),
    @name( $name:ident ) $(,)?
  ) => {};
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_main_error_struct {
  ( @tracer( $tracer:ty ),
    $( @doc( $doc:literal ), )?
    @name( $name:ident ) $(,)?
  ) => {
    $crate::macros::paste![
      $( #[doc = $doc] )?
      pub struct $name (pub [< $name Detail >], pub $tracer);
    ];
  }
}

#[macro_export]
#[doc(hidden)]
macro_rules! with_suberrors {
  ( @cont($cont:path),
    @ctx[ $($args:tt)* ],
    @suberrors{
      $(
        $( #[$sub_attr:meta] )*
        $suberror:ident
        $( { $( $arg_name:ident : $arg_type:ty ),* $(,)? } )?
        $( [ $source:ty ] )?
        | $formatter_arg:pat | $formatter:expr
      ),* $(,)?
    } $(,)?
  ) => {
    $cont!( @ctx[ $( $args )* ], @suberrors{ $( $suberror ),* } );
  }
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_error_detail {
  ( @attr[ $( $attr:meta ),* ],
    @name( $name:ident ),
    @suberrors{ $($suberrors:tt)* } $(,)?
  ) => {
    $crate::with_suberrors!(
      @cont($crate::define_error_detail_enum),
      @ctx[
        @attr[ $( $attr ),* ],
        @name($name)
      ],
      @suberrors{ $( $suberrors )* }
    );

    $crate::with_suberrors!(
      @cont($crate::define_error_detail_display),
      @ctx[
        @name($name)
      ],
      @suberrors{ $( $suberrors )* }
    );
  }
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_error_detail_enum {
  ( @ctx[
      @attr[ $( $attr:meta ),* ],
      @name($name:ident)
    ],
    @suberrors{ $( $suberror:ident ),* } $(,)?
  ) => {
    $crate::macros::paste! [
      $( #[$attr] )*
      pub enum [< $name Detail >] {
        $(
          $suberror (
            [< $suberror Subdetail >]
          )
        ),*
      }
    ];
  }
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_error_detail_display {
  ( @ctx[
      @name( $name:ident )
    ],
    @suberrors{ $( $suberror:ident ),* } $(,)?
  ) => {
    $crate::macros::paste! [
      impl ::core::fmt::Display for [< $name Detail >] {
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>)
          -> ::core::fmt::Result
        {
          match self {
            $(
              Self::$suberror( suberror ) => {
                ::core::write!( f, "{}",  suberror )
              }
            ),*
          }
        }
      }
    ];
  }
}

#[macro_export]
#[doc(hidden)]
macro_rules! define_suberrors {
  ( @tracer($tracer:ty),
    @attr[ $( $attr:meta ),* ],
    @name($name:ident),
    {} $(,)?
  ) => { };
  ( @tracer($tracer:ty),
    @attr[ $( $attr:meta ),* ],
    @name($name:ident),
    {
      $( #[$sub_attr:meta] )*
      $suberror:ident
        $( { $( $arg_name:ident : $arg_type:ty ),* $(,)? } )?
        $( [ $source:ty ] )?
        | $formatter_arg:pat | $formatter:expr

      $( , $($tail:tt)* )?
    }
  ) => {
    $crate::macros::paste![
      $crate::define_suberror! {
        @tracer( $tracer ),
        @attr[ $( $attr ),* ],
        @sub_attr[ $( $sub_attr ),* ],
        @name( $name ),
        @suberror( $suberror ),
        @args( $( $( $arg_name : $arg_type ),* )? )
        $( @source[ $source ] )?
      }

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

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

    $crate::define_suberrors! {
      @tracer($tracer),
      @attr[ $( $attr ),* ],
      @name($name),
      { $( $( $tail )* )? }
    }
  };
}

/// Internal macro used to define suberror structs
#[macro_export]
#[doc(hidden)]
macro_rules! define_suberror {
  ( @tracer( $tracer:ty ),
    @attr[ $( $attr:meta ),* ],
    @sub_attr[ $( $sub_attr:meta ),* ],
    @name( $name:ident ),
    @suberror( $suberror:ident ),
    @args( $( $arg_name:ident: $arg_type:ty ),* )
    @source[ Self ]
  ) => {
    $crate::macros::paste! [
      $( #[ $attr ] )*
      $( #[ $sub_attr ] )*
      pub struct [< $suberror Subdetail >] {
        $( pub $arg_name: $arg_type, )*
        pub source: $crate::alloc::boxed::Box< [< $name Detail >] >
      }
    ];
  };
  ( @tracer( $tracer:ty ),
    @attr[ $( $attr:meta ),* ],
    @sub_attr[ $( $sub_attr:meta ),* ],
    @name( $name:ident ),
    @suberror( $suberror:ident ),
    @args( $( $arg_name:ident: $arg_type:ty ),* )
    $( @source[ $source:ty ] )?
  ) => {
    $crate::macros::paste! [
      $( #[ $attr ] )*
      $( #[ $sub_attr ] )*
      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]
#[doc(hidden)]
macro_rules! define_error_constructor {
  ( @tracer( $tracer:ty ),
    @name( $name:ident ),
    @suberror( $suberror:ident ),
    @args( $( $arg_name:ident: $arg_type:ty ),* ) $(,)?
  ) => {
    $crate::macros::paste! [
      pub fn [< $suberror:snake >](
        $( $arg_name: $arg_type, )*
      ) -> $name
      {
        let detail = [< $name Detail >]::$suberror([< $suberror Subdetail >] {
          $( $arg_name, )*
        });

        let trace = < $tracer as $crate::ErrorMessageTracer >::new_message(&detail);
        $name(detail, trace)
      }
    ];
  };
  ( @tracer( $tracer:ty ),
    @name( $name:ident ),
    @suberror( $suberror:ident ),
    @args( $( $arg_name:ident: $arg_type:ty ),* )
    @source[ Self ]
  ) => {
    $crate::macros::paste! [
      pub fn [< $suberror:snake >](
        $( $arg_name: $arg_type, )*
        source: $name
      ) -> $name
      {
        let detail = [< $name Detail >]::$suberror([< $suberror Subdetail >] {
          $( $arg_name, )*
          source: Box::new(source.0),
        });

        let trace = source.1.add_message(&detail);

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