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
//  LIB.rs
//    by Lut99
//
//  Created:
//    22 Sep 2023, 12:17:19
//  Last edited:
//    17 Mar 2024, 12:54:12
//  Auto updated?
//    Yes
//
//  Description:
//!   Small Rust crate for printing nice errors traits based on [`Error::source()`].
//!   
//!   # Usage
//!   Using the crate is quite straightforward.
//!   
//!   First, create your errors as usual:
//!   ```rust
//!   # use std::error::Error;
//!   # use std::fmt::{Display, Formatter, Result as FResult};
//!   #[derive(Debug)]
//!   struct SomeError {
//!       msg : String,
//!   }
//!   impl Display for SomeError {
//!       fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!           write!(f, "{}", self.msg)
//!       }
//!   }
//!   impl Error for SomeError {}
//!   
//!   #[derive(Debug)]
//!   struct HigherError {
//!       msg   : String,
//!       child : SomeError,
//!   }
//!   impl Display for HigherError {
//!       fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!           write!(f, "{}", self.msg)
//!       }
//!   }
//!   impl Error for HigherError {
//!       fn source(&self) -> Option<&(dyn 'static + Error)> {
//!           Some(&self.child)
//!       }
//!   }
//!   ```
//!   
//!   Then, when it is time to report them to the user, do not print them directly but instead use the `ErrorTrace`-trait's `trace()` function:
//!   ```rust
//!   use error_trace::ErrorTrace as _;
//!   
//!   # use std::error::Error;
//!   # use std::fmt::{Display, Formatter, Result as FResult};
//!   # #[derive(Debug)]
//!   # struct SomeError {
//!   #     msg : String,
//!   # }
//!   # impl Display for SomeError {
//!   #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!   #         write!(f, "{}", self.msg)
//!   #     }
//!   # }
//!   # impl Error for SomeError {}
//!   #
//!   # #[derive(Debug)]
//!   # struct HigherError {
//!   #     msg   : String,
//!   #     child : SomeError,
//!   # }
//!   # impl Display for HigherError {
//!   #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!   #         write!(f, "{}", self.msg)
//!   #     }
//!   # }
//!   # impl Error for HigherError {
//!   #     fn source(&self) -> Option<&(dyn 'static + Error)> {
//!   #         Some(&self.child)
//!   #     }
//!   # }
//!   // ...
//!   
//!   let err: HigherError = HigherError {
//!       msg: "Oh no, something went wrong!".into(),
//!       child: SomeError{
//!           msg: "A specific reason".into()
//!       }
//!   };
//!   eprintln!("{}", err.trace());
//!   ```
//!   This will show you:
//!   ```text
//!   Oh no, something went wrong!
//!   
//!   Caused by:
//!    o A specific reason
//!   ```
//!   
//!   If you enable the `colours`-feature, you can additionally print some neat colours:
//!   ```rust
//!   use error_trace::ErrorTrace as _;
//!   
//!   # use std::error::Error;
//!   # use std::fmt::{Display, Formatter, Result as FResult};
//!   # #[derive(Debug)]
//!   # struct SomeError {
//!   #     msg : String,
//!   # }
//!   # impl Display for SomeError {
//!   #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!   #         write!(f, "{}", self.msg)
//!   #     }
//!   # }
//!   # impl Error for SomeError {}
//!   #
//!   # #[derive(Debug)]
//!   # struct HigherError {
//!   #     msg   : String,
//!   #     child : SomeError,
//!   # }
//!   # impl Display for HigherError {
//!   #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
//!   #         write!(f, "{}", self.msg)
//!   #     }
//!   # }
//!   # impl Error for HigherError {
//!   #     fn source(&self) -> Option<&(dyn 'static + Error)> {
//!   #         Some(&self.child)
//!   #     }
//!   # }
//!   // ...
//!   
//!   let err: HigherError = HigherError {
//!       msg: "Oh no, something went wrong!".into(),
//!       child: SomeError{
//!           msg: "A specific reason".into()
//!       }
//!   };
//!   
//!   // Requires the `colours`-feature!
//!   eprintln!("{}", err.trace_coloured());
//!   ```
//!   ![Showing the same error as above but with some errors](https://github.com/Lut99/error-trace-rs/raw/main/img/example_colours.png)
//!
//!   Finally, when used in a situation where you want to show a quick error but are sure to never needs its contents, you can use the [`trace!()`]-macro:
//!   ```rust
//!   use error_trace::trace;
//!  
//!   // Do something that fails
//!   let err = std::str::from_utf8(&[0xFF]).unwrap_err();
//!  
//!   // Format it with a one-time parent error
//!   eprintln!("{}", trace!(("Oh no, everything went wrong!"), err));
//!   ```
//!
//!   For users of the `colours`-feature, there is the associated [`trace_coloured!()`]-macro:
//!   ```rust
//!   use error_trace::trace_coloured;
//!  
//!   // Do something that fails
//!   let err = std::str::from_utf8(&[0xFF]).unwrap_err();
//!  
//!   // Format it with a one-time parent error
//!   eprintln!("{}", trace_coloured!(("Oh no, everything went wrong!"), err));
//!   ```
//!   
//!   
//!   # Installation
//!   To use this crate into one of your projects, simply add it to your `Cargo.toml` file:
//!   ```toml
//!   error-trace = { git = "https://github.com/Lut99/error-trace-rs" }
//!   ```
//!   Optionally, you can commit to a particular tag:
//!   ```toml
//!   error-trace = { git = "https://github.com/Lut99/error-trace-rs", tag = "v1.1.0" }
//!   ```
//!   
//!   To build this crate's documentation and open it, run:
//!   ```bash
//!   cargo doc --all-features --no-deps --open
//!   ```
//!   in the root of the repository.
//!   
//!   ## Features
//!   The crate has the following features:
//!   - `colors`: Alias for the `colours`-trait.
//!   - `colours`: Enables the use of [`trace_coloured()`].
//!   - `macros`: Enables the use of the [`trace!()`]- and [`trace_coloured!()`]-macros.
//

use std::borrow::Cow;
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FResult};

#[cfg(feature = "colours")]
use console::style;


/***** MACROS *****/
/// Creates a one-time [`ErrorTrace`]-compatible type from the given string, then calls [`trace()`](ErrorTrace::trace()) on it.
///
/// # Arguments
/// The macro has the following signature:
/// ```plain
/// (`$($args:tt)*), $err:expr
/// ```
/// - `$($args:tt)*`: A message to use for the toplevel error. This can be given the arguments to a [`format!`]-call.
/// - `$err:expr`: The error to embed in the newly built type.
///
/// # Returns
/// An [`ErrorTraceFormatter`] that can be displayed immediately.
///
/// # Example
/// ```rust
/// use error_trace::trace;
///
/// // Do something that fails
/// let err = std::str::from_utf8(&[0xFF]).unwrap_err();
///
/// // Format it with a one-time parent error
/// assert_eq!(
///     trace!(("Oh no, everything went wrong!"), err).to_string(),
///     r#"Oh no, everything went wrong!
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
/// ```
/// One can use full format strings for the message:
/// ```rust
/// use error_trace::trace;
///
/// // Do something that fails
/// let bytes: [u8; 1] = [0xFF];
/// let err = std::str::from_utf8(&bytes).unwrap_err();
///
/// // Format it with a one-time parent error
/// assert_eq!(
///     trace!(("Failed to parse '{:?}'", bytes.as_slice()), err).to_string(),
///     r#"Failed to parse '[255]'
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
///
///
/// // Equivalent to above (but using a neater format syntax!)
/// assert_eq!(
///     trace!(("Failed to parse '{bytes:?}'"), err).to_string(),
///     r#"Failed to parse '[255]'
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
/// ```
#[cfg(feature = "macros")]
#[macro_export]
macro_rules! trace {
    (($($args:tt)*), $err:expr) => {
        ::error_trace::ErrorTraceFormatter::new(format!($($args)*), Some(&$err))
    };
}

/// Creates a one-time [`ErrorTrace`]-compatible type from the given string, then calls [`trace_coloured()`](ErrorTrace::trace_coloured()) on it.
///
/// # Arguments
/// The macro has the following signature:
/// ```plain
/// ($($args:tt)*), $err:expr
/// ```
/// - `$($args:tt)*`: A message to use for the toplevel error. This can be given the arguments to a [`format!`]-call.
/// - `$err:expr`: The error to embed in the newly built type.
///
/// # Returns
/// An [`ErrorTraceColourFormatter`] that can be displayed immediately.
///
/// # Example
/// ```rust
/// use error_trace::trace_coloured;
///
/// // Do something that fails
/// let err = std::str::from_utf8(&[0xFF]).unwrap_err();
///
/// // Colours aren't visible here, because we're writing to a string; but try writing to stdout/stderr!
/// assert_eq!(
///     trace_coloured!(("Oh no, everything went wrong!"), err).to_string(),
///     r#"Oh no, everything went wrong!
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
/// ```
/// One can use full format strings for the message:
/// ```rust
/// use error_trace::trace_coloured;
///
/// // Do something that fails
/// let bytes: [u8; 1] = [0xFF];
/// let err = std::str::from_utf8(&bytes).unwrap_err();
///
/// // Format it with a one-time parent error
/// assert_eq!(
///     trace_coloured!(("Failed to parse '{:?}'", bytes.as_slice()), err).to_string(),
///     r#"Failed to parse '[255]'
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
///
///
/// // Equivalent to above (but using a neater format syntax!)
/// assert_eq!(
///     trace_coloured!(("Failed to parse '{bytes:?}'"), err).to_string(),
///     r#"Failed to parse '[255]'
///
/// Caused by:
///  o invalid utf-8 sequence of 1 bytes from index 0
///
/// "#
/// );
/// ```
#[cfg(all(feature = "colours", feature = "macros"))]
#[macro_export]
macro_rules! trace_coloured {
    (($($args:tt)*), $err:expr) => {
        ::error_trace::ErrorTraceColourFormatter::new(format!($($args)*), Some(&$err))
    };
}





/***** FORMATTERS *****/
/// Formats an error and all its dependencies.
///
/// If you have the `colours`-feature enabled, then you can also use [`ErrorTraceColourFormatter`] to do the same but with colours.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use std::fmt::{Display, Formatter, Result as FResult};
/// use error_trace::{ErrorTrace as _, ErrorTraceFormatter};
///
/// #[derive(Debug)]
/// struct ExampleError {
///     msg: String,
/// }
/// impl Display for ExampleError {
///     fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.msg) }
/// }
/// impl Error for ExampleError {}
///
/// let err = ExampleError { msg: "Hello, world!".into() };
/// let fmt: ErrorTraceFormatter = err.trace();
/// assert_eq!(format!("{fmt}"), "Hello, world!");
/// ```
pub struct ErrorTraceFormatter<'s, 'e> {
    /// The message that is the main error message.
    msg: Cow<'s, str>,
    /// An optional nested error to format that is the first element in the tree.
    err: Option<&'e (dyn 'static + Error)>,
}
impl<'s, 'e> ErrorTraceFormatter<'s, 'e> {
    /// Builds a formatter for a given "anonymous error".
    ///
    /// This is useful for creating one-time error traces where you don't want to create the root type.
    ///
    /// For even more convenience, see the [`trace!`]-macro.
    ///
    /// # Arguments
    /// - `msg`: A message that is printed as "current error".
    /// - `err`: An optional error that, if any, will cause this formatter to start printing a trace based on the error's [`Error::source()`]-implementation.
    ///
    /// # Returns
    /// A new ErrorTraceFormatter ready to rock-n-roll.
    #[inline]
    pub fn new(msg: impl Into<Cow<'s, str>>, err: Option<&'e (dyn 'static + Error)>) -> Self { Self { msg: msg.into(), err } }
}
impl<'s, 'e> Display for ErrorTraceFormatter<'s, 'e> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
        // Match on beautiness
        if f.alternate() {
            // Always print the thing
            write!(f, "{:#}", self.msg)?;

            // Print any deps if any
            if let Some(source) = self.err {
                // Write the thingy
                write!(f, "\n\nCaused by:")?;

                let mut source: Option<&dyn Error> = Some(source);
                while let Some(err) = source.take() {
                    // Print it
                    write!(f, "\n o {err:#}")?;
                    source = err.source();
                }

                // Write closing enters
                writeln!(f, "\n")?;
            }
        } else {
            // Always print the thing
            write!(f, "{}", self.msg)?;

            // Print any deps if any
            if let Some(source) = self.err {
                // Write the thingy
                write!(f, "\n\nCaused by:")?;

                let mut source: Option<&dyn Error> = Some(source);
                while let Some(err) = source.take() {
                    // Print it
                    write!(f, "\n o {err}")?;
                    source = err.source();
                }

                // Write closing enters
                writeln!(f, "\n")?;
            }
        }

        // Done!
        Ok(())
    }
}

/// Formats an error and all its dependencies using neat ANSI-colours if the formatter to which we're writing supports it.
///
/// Whether colours are enabled or not can be checked by [`console`]'s [`colors_enabled_stderr()`](console::colors_enabled_stderr()) function, and controlled by [`set_colors_enabled_stderr()`](console::set_colors_enabled_stderr()).
///
/// See [`ErrorTraceFormatter`] to do the same but without ANSI colours at all.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use std::fmt::{Display, Formatter, Result as FResult};
/// use error_trace::{ErrorTraceColourFormatter, ErrorTrace as _};
///
/// #[derive(Debug)]
/// struct ExampleError {
///     msg : String,
/// }
/// impl Display for ExampleError {
///     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
///         write!(f, "{}", self.msg)
///     }
/// }
/// impl Error for ExampleError {}
///
/// let err = ExampleError { msg: "Hello, world!".into() };
/// let fmt: ErrorTraceColourFormatter = err.trace_coloured();
///
/// // Colours aren't visible here, because we're writing to a string; but try writing to stdout/stderr!
/// assert_eq!(format!("{fmt}"), "Hello, world!");
/// ```
#[cfg(feature = "colours")]
pub struct ErrorTraceColourFormatter<'s, 'e> {
    /// The message that is the main error message.
    msg: Cow<'s, str>,
    /// An optional nested error to format that is the first element in the tree.
    err: Option<&'e (dyn 'static + Error)>,
}
#[cfg(feature = "colours")]
impl<'s, 'e> ErrorTraceColourFormatter<'s, 'e> {
    /// Builds a formatter for a given "anonymous error".
    ///
    /// This is useful for creating one-time error traces where you don't want to create the root type.
    ///
    /// For even more convenience, see the [`trace!`]-macro.
    ///
    /// # Arguments
    /// - `msg`: A message that is printed as "current error".
    /// - `err`: An optional error that, if any, will cause this formatter to start printing a trace based on the error's [`Error::source()`]-implementation.
    ///
    /// # Returns
    /// A new ErrorTraceColourFormatter ready to rock-n-roll.
    #[inline]
    pub fn new(msg: impl Into<Cow<'s, str>>, err: Option<&'e (dyn 'static + Error)>) -> Self { Self { msg: msg.into(), err } }
}
#[cfg(feature = "colours")]
impl<'s, 'e> Display for ErrorTraceColourFormatter<'s, 'e> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
        // Match on beautiness
        if f.alternate() {
            // Always print the thing
            write!(f, "{}", style(format!("{:#}", self.msg)).for_stderr().bold())?;

            // Print any deps if any
            if let Some(source) = self.err {
                // Write the thingy
                write!(f, "\n\n{}", style("Caused by:").for_stderr().red().bold())?;

                let mut source: Option<&dyn Error> = Some(source);
                while let Some(err) = source.take() {
                    // Print it
                    write!(f, "\n o {}", style(format!("{err:#}")).for_stderr().bold())?;
                    source = err.source();
                }

                // Write closing enters
                writeln!(f, "\n")?;
            }
        } else {
            // Always print the thing
            write!(f, "{}", style(&self.msg).for_stderr().bold())?;

            // Print any deps if any
            if let Some(source) = self.err {
                // Write the thingy
                write!(f, "\n\n{}", style("Caused by:").for_stderr().red().bold())?;

                let mut source: Option<&dyn Error> = Some(source);
                while let Some(err) = source.take() {
                    // Print it
                    write!(f, "\n o {}", style(err).for_stderr().bold())?;
                    source = err.source();
                }

                // Write closing enters
                writeln!(f, "\n")?;
            }
        }

        // Done!
        Ok(())
    }
}





/***** LIBRARY *****/
/// Allows one to write an error and all of its dependencies.
///
/// # Example
/// ```rust
/// use std::error::Error;
/// use std::fmt::{Display, Formatter, Result as FResult};
///
/// use error_trace::ErrorTrace as _;
///
/// #[derive(Debug)]
/// struct SomeError {
///     msg: String,
/// }
/// impl Display for SomeError {
///     fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.msg) }
/// }
/// impl Error for SomeError {}
///
/// #[derive(Debug)]
/// struct HigherError {
///     msg:   String,
///     child: SomeError,
/// }
/// impl Display for HigherError {
///     fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.msg) }
/// }
/// impl Error for HigherError {
///     fn source(&self) -> Option<&(dyn 'static + Error)> { Some(&self.child) }
/// }
///
///
///
/// let err = HigherError {
///     msg:   "Oh no, something went wrong!".into(),
///     child: SomeError { msg: "A specific reason".into() },
/// };
/// assert_eq!(
///     err.trace().to_string(),
///     r#"Oh no, something went wrong!
///
/// Caused by:
///  o A specific reason
///
/// "#
/// );
/// ```
pub trait ErrorTrace: Error {
    /// Returns a formatter for showing this Error and all its [source](Error::source())s.
    ///
    /// This function can be used similarly to [`Path::display()`](std::path::Path::display()), since its result
    /// implements both [`Debug`] and [`Display`].
    ///
    /// # Returns
    /// A new [`ErrorTraceFormatter`] that implements [`Debug`] and [`Display`].
    ///
    /// # Example
    /// ```rust
    /// # use std::error::Error;
    /// # use std::fmt::{Display, Formatter, Result as FResult};
    /// #
    /// use error_trace::ErrorTrace as _;
    ///
    /// # #[derive(Debug)]
    /// # struct SomeError {
    /// #     msg : String,
    /// # }
    /// # impl Display for SomeError {
    /// #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
    /// #         write!(f, "{}", self.msg)
    /// #     }
    /// # }
    /// # impl Error for SomeError {}
    /// #
    /// # #[derive(Debug)]
    /// # struct HigherError {
    /// #     msg   : String,
    /// #     child : SomeError,
    /// # }
    /// # impl Display for HigherError {
    /// #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
    /// #         write!(f, "{}", self.msg)
    /// #     }
    /// # }
    /// # impl Error for HigherError {
    /// #     fn source(&self) -> Option<&(dyn 'static + Error)> {
    /// #         Some(&self.child)
    /// #     }
    /// # }
    /// #
    /// #
    /// #
    /// let err = HigherError { msg: "Oh no, something went wrong!".into(), child: SomeError { msg: "A specific reason".into() } };
    /// assert_eq!(err.trace().to_string(), r#"Oh no, something went wrong!
    ///
    /// Caused by:
    ///  o A specific reason
    ///
    /// "#);
    fn trace(&self) -> ErrorTraceFormatter;

    /// Returns a formatter for showing this Error and all its [source](Error::source())s with nice colours.
    ///
    /// This function can be used similarly to [`Path::display()`](std::path::Path::display()), since its result
    /// implements both [`Debug`] and [`Display`].
    ///
    /// # Returns
    /// A new [`ErrorTraceColourFormatter`] that implements [`Debug`] and [`Display`].
    ///
    /// # Example
    /// ```rust
    /// # use std::error::Error;
    /// # use std::fmt::{Display, Formatter, Result as FResult};
    /// #
    /// use error_trace::ErrorTrace as _;
    ///
    /// # #[derive(Debug)]
    /// # struct SomeError {
    /// #     msg : String,
    /// # }
    /// # impl Display for SomeError {
    /// #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
    /// #         write!(f, "{}", self.msg)
    /// #     }
    /// # }
    /// # impl Error for SomeError {}
    /// #
    /// # #[derive(Debug)]
    /// # struct HigherError {
    /// #     msg   : String,
    /// #     child : SomeError,
    /// # }
    /// # impl Display for HigherError {
    /// #     fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
    /// #         write!(f, "{}", self.msg)
    /// #     }
    /// # }
    /// # impl Error for HigherError {
    /// #     fn source(&self) -> Option<&(dyn 'static + Error)> {
    /// #         Some(&self.child)
    /// #     }
    /// # }
    /// #
    /// #
    /// #
    /// let err = HigherError { msg: "Oh no, something went wrong!".into(), child: SomeError { msg: "A specific reason".into() } };
    /// assert_eq!(err.trace_coloured().to_string(), r#"Oh no, something went wrong!
    ///
    /// Caused by:
    ///  o A specific reason
    ///
    /// "#);
    #[cfg(feature = "colours")]
    fn trace_coloured(&self) -> ErrorTraceColourFormatter;
}
impl<T: ?Sized + Error> ErrorTrace for T {
    fn trace(&self) -> ErrorTraceFormatter { ErrorTraceFormatter { msg: Cow::Owned(self.to_string()), err: self.source() } }

    #[cfg(feature = "colours")]
    fn trace_coloured(&self) -> ErrorTraceColourFormatter { ErrorTraceColourFormatter { msg: Cow::Owned(self.to_string()), err: self.source() } }
}