]> git.lizzy.rs Git - rust.git/blob - library/std/src/error.rs
Auto merge of #92287 - JulianKnodt:slice_remainder, r=yaahc
[rust.git] / library / std / src / error.rs
1 //! Traits for working with Errors.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 // A note about crates and the facade:
6 //
7 // Originally, the `Error` trait was defined in libcore, and the impls
8 // were scattered about. However, coherence objected to this
9 // arrangement, because to create the blanket impls for `Box` required
10 // knowing that `&str: !Error`, and we have no means to deal with that
11 // sort of conflict just now. Therefore, for the time being, we have
12 // moved the `Error` trait into libstd. As we evolve a sol'n to the
13 // coherence challenge (e.g., specialization, neg impls, etc) we can
14 // reconsider what crate these items belong in.
15
16 #[cfg(test)]
17 mod tests;
18
19 use core::array;
20 use core::convert::Infallible;
21
22 use crate::alloc::{AllocError, LayoutError};
23 use crate::any::TypeId;
24 use crate::backtrace::Backtrace;
25 use crate::borrow::Cow;
26 use crate::cell;
27 use crate::char;
28 use crate::fmt::{self, Debug, Display, Write};
29 use crate::io;
30 use crate::mem::transmute;
31 use crate::num;
32 use crate::str;
33 use crate::string;
34 use crate::sync::Arc;
35 use crate::time;
36
37 /// `Error` is a trait representing the basic expectations for error values,
38 /// i.e., values of type `E` in [`Result<T, E>`].
39 ///
40 /// Errors must describe themselves through the [`Display`] and [`Debug`]
41 /// traits. Error messages are typically concise lowercase sentences without
42 /// trailing punctuation:
43 ///
44 /// ```
45 /// let err = "NaN".parse::<u32>().unwrap_err();
46 /// assert_eq!(err.to_string(), "invalid digit found in string");
47 /// ```
48 ///
49 /// Errors may provide cause chain information. [`Error::source()`] is generally
50 /// used when errors cross "abstraction boundaries". If one module must report
51 /// an error that is caused by an error from a lower-level module, it can allow
52 /// accessing that error via [`Error::source()`]. This makes it possible for the
53 /// high-level module to provide its own errors while also revealing some of the
54 /// implementation for debugging via `source` chains.
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub trait Error: Debug + Display {
57     /// The lower-level source of this error, if any.
58     ///
59     /// # Examples
60     ///
61     /// ```
62     /// use std::error::Error;
63     /// use std::fmt;
64     ///
65     /// #[derive(Debug)]
66     /// struct SuperError {
67     ///     source: SuperErrorSideKick,
68     /// }
69     ///
70     /// impl fmt::Display for SuperError {
71     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72     ///         write!(f, "SuperError is here!")
73     ///     }
74     /// }
75     ///
76     /// impl Error for SuperError {
77     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
78     ///         Some(&self.source)
79     ///     }
80     /// }
81     ///
82     /// #[derive(Debug)]
83     /// struct SuperErrorSideKick;
84     ///
85     /// impl fmt::Display for SuperErrorSideKick {
86     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87     ///         write!(f, "SuperErrorSideKick is here!")
88     ///     }
89     /// }
90     ///
91     /// impl Error for SuperErrorSideKick {}
92     ///
93     /// fn get_super_error() -> Result<(), SuperError> {
94     ///     Err(SuperError { source: SuperErrorSideKick })
95     /// }
96     ///
97     /// fn main() {
98     ///     match get_super_error() {
99     ///         Err(e) => {
100     ///             println!("Error: {e}");
101     ///             println!("Caused by: {}", e.source().unwrap());
102     ///         }
103     ///         _ => println!("No error"),
104     ///     }
105     /// }
106     /// ```
107     #[stable(feature = "error_source", since = "1.30.0")]
108     fn source(&self) -> Option<&(dyn Error + 'static)> {
109         None
110     }
111
112     /// Gets the `TypeId` of `self`.
113     #[doc(hidden)]
114     #[unstable(
115         feature = "error_type_id",
116         reason = "this is memory-unsafe to override in user code",
117         issue = "60784"
118     )]
119     fn type_id(&self, _: private::Internal) -> TypeId
120     where
121         Self: 'static,
122     {
123         TypeId::of::<Self>()
124     }
125
126     /// Returns a stack backtrace, if available, of where this error occurred.
127     ///
128     /// This function allows inspecting the location, in code, of where an error
129     /// happened. The returned `Backtrace` contains information about the stack
130     /// trace of the OS thread of execution of where the error originated from.
131     ///
132     /// Note that not all errors contain a `Backtrace`. Also note that a
133     /// `Backtrace` may actually be empty. For more information consult the
134     /// `Backtrace` type itself.
135     #[unstable(feature = "backtrace", issue = "53487")]
136     fn backtrace(&self) -> Option<&Backtrace> {
137         None
138     }
139
140     /// ```
141     /// if let Err(e) = "xc".parse::<u32>() {
142     ///     // Print `e` itself, no need for description().
143     ///     eprintln!("Error: {e}");
144     /// }
145     /// ```
146     #[stable(feature = "rust1", since = "1.0.0")]
147     #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
148     fn description(&self) -> &str {
149         "description() is deprecated; use Display"
150     }
151
152     #[stable(feature = "rust1", since = "1.0.0")]
153     #[rustc_deprecated(
154         since = "1.33.0",
155         reason = "replaced by Error::source, which can support downcasting"
156     )]
157     #[allow(missing_docs)]
158     fn cause(&self) -> Option<&dyn Error> {
159         self.source()
160     }
161 }
162
163 mod private {
164     // This is a hack to prevent `type_id` from being overridden by `Error`
165     // implementations, since that can enable unsound downcasting.
166     #[unstable(feature = "error_type_id", issue = "60784")]
167     #[derive(Debug)]
168     pub struct Internal;
169 }
170
171 #[stable(feature = "rust1", since = "1.0.0")]
172 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
173     /// Converts a type of [`Error`] into a box of dyn [`Error`].
174     ///
175     /// # Examples
176     ///
177     /// ```
178     /// use std::error::Error;
179     /// use std::fmt;
180     /// use std::mem;
181     ///
182     /// #[derive(Debug)]
183     /// struct AnError;
184     ///
185     /// impl fmt::Display for AnError {
186     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187     ///         write!(f, "An error")
188     ///     }
189     /// }
190     ///
191     /// impl Error for AnError {}
192     ///
193     /// let an_error = AnError;
194     /// assert!(0 == mem::size_of_val(&an_error));
195     /// let a_boxed_error = Box::<dyn Error>::from(an_error);
196     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
197     /// ```
198     fn from(err: E) -> Box<dyn Error + 'a> {
199         Box::new(err)
200     }
201 }
202
203 #[stable(feature = "rust1", since = "1.0.0")]
204 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
205     /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
206     /// dyn [`Error`] + [`Send`] + [`Sync`].
207     ///
208     /// # Examples
209     ///
210     /// ```
211     /// use std::error::Error;
212     /// use std::fmt;
213     /// use std::mem;
214     ///
215     /// #[derive(Debug)]
216     /// struct AnError;
217     ///
218     /// impl fmt::Display for AnError {
219     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220     ///         write!(f, "An error")
221     ///     }
222     /// }
223     ///
224     /// impl Error for AnError {}
225     ///
226     /// unsafe impl Send for AnError {}
227     ///
228     /// unsafe impl Sync for AnError {}
229     ///
230     /// let an_error = AnError;
231     /// assert!(0 == mem::size_of_val(&an_error));
232     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
233     /// assert!(
234     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
235     /// ```
236     fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
237         Box::new(err)
238     }
239 }
240
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl From<String> for Box<dyn Error + Send + Sync> {
243     /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
244     ///
245     /// # Examples
246     ///
247     /// ```
248     /// use std::error::Error;
249     /// use std::mem;
250     ///
251     /// let a_string_error = "a string error".to_string();
252     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
253     /// assert!(
254     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
255     /// ```
256     #[inline]
257     fn from(err: String) -> Box<dyn Error + Send + Sync> {
258         struct StringError(String);
259
260         impl Error for StringError {
261             #[allow(deprecated)]
262             fn description(&self) -> &str {
263                 &self.0
264             }
265         }
266
267         impl Display for StringError {
268             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269                 Display::fmt(&self.0, f)
270             }
271         }
272
273         // Purposefully skip printing "StringError(..)"
274         impl Debug for StringError {
275             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276                 Debug::fmt(&self.0, f)
277             }
278         }
279
280         Box::new(StringError(err))
281     }
282 }
283
284 #[stable(feature = "string_box_error", since = "1.6.0")]
285 impl From<String> for Box<dyn Error> {
286     /// Converts a [`String`] into a box of dyn [`Error`].
287     ///
288     /// # Examples
289     ///
290     /// ```
291     /// use std::error::Error;
292     /// use std::mem;
293     ///
294     /// let a_string_error = "a string error".to_string();
295     /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
296     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
297     /// ```
298     fn from(str_err: String) -> Box<dyn Error> {
299         let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
300         let err2: Box<dyn Error> = err1;
301         err2
302     }
303 }
304
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
307     /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
308     ///
309     /// [`str`]: prim@str
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use std::error::Error;
315     /// use std::mem;
316     ///
317     /// let a_str_error = "a str error";
318     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
319     /// assert!(
320     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
321     /// ```
322     #[inline]
323     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
324         From::from(String::from(err))
325     }
326 }
327
328 #[stable(feature = "string_box_error", since = "1.6.0")]
329 impl From<&str> for Box<dyn Error> {
330     /// Converts a [`str`] into a box of dyn [`Error`].
331     ///
332     /// [`str`]: prim@str
333     ///
334     /// # Examples
335     ///
336     /// ```
337     /// use std::error::Error;
338     /// use std::mem;
339     ///
340     /// let a_str_error = "a str error";
341     /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
342     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
343     /// ```
344     fn from(err: &str) -> Box<dyn Error> {
345         From::from(String::from(err))
346     }
347 }
348
349 #[stable(feature = "cow_box_error", since = "1.22.0")]
350 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
351     /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use std::error::Error;
357     /// use std::mem;
358     /// use std::borrow::Cow;
359     ///
360     /// let a_cow_str_error = Cow::from("a str error");
361     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
362     /// assert!(
363     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
364     /// ```
365     fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
366         From::from(String::from(err))
367     }
368 }
369
370 #[stable(feature = "cow_box_error", since = "1.22.0")]
371 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
372     /// Converts a [`Cow`] into a box of dyn [`Error`].
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::error::Error;
378     /// use std::mem;
379     /// use std::borrow::Cow;
380     ///
381     /// let a_cow_str_error = Cow::from("a str error");
382     /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
383     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
384     /// ```
385     fn from(err: Cow<'a, str>) -> Box<dyn Error> {
386         From::from(String::from(err))
387     }
388 }
389
390 #[unstable(feature = "never_type", issue = "35121")]
391 impl Error for ! {}
392
393 #[unstable(
394     feature = "allocator_api",
395     reason = "the precise API and guarantees it provides may be tweaked.",
396     issue = "32838"
397 )]
398 impl Error for AllocError {}
399
400 #[stable(feature = "alloc_layout", since = "1.28.0")]
401 impl Error for LayoutError {}
402
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl Error for str::ParseBoolError {
405     #[allow(deprecated)]
406     fn description(&self) -> &str {
407         "failed to parse bool"
408     }
409 }
410
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl Error for str::Utf8Error {
413     #[allow(deprecated)]
414     fn description(&self) -> &str {
415         "invalid utf-8: corrupt contents"
416     }
417 }
418
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl Error for num::ParseIntError {
421     #[allow(deprecated)]
422     fn description(&self) -> &str {
423         self.__description()
424     }
425 }
426
427 #[stable(feature = "try_from", since = "1.34.0")]
428 impl Error for num::TryFromIntError {
429     #[allow(deprecated)]
430     fn description(&self) -> &str {
431         self.__description()
432     }
433 }
434
435 #[stable(feature = "try_from", since = "1.34.0")]
436 impl Error for array::TryFromSliceError {
437     #[allow(deprecated)]
438     fn description(&self) -> &str {
439         self.__description()
440     }
441 }
442
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl Error for num::ParseFloatError {
445     #[allow(deprecated)]
446     fn description(&self) -> &str {
447         self.__description()
448     }
449 }
450
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl Error for string::FromUtf8Error {
453     #[allow(deprecated)]
454     fn description(&self) -> &str {
455         "invalid utf-8"
456     }
457 }
458
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl Error for string::FromUtf16Error {
461     #[allow(deprecated)]
462     fn description(&self) -> &str {
463         "invalid utf-16"
464     }
465 }
466
467 #[stable(feature = "str_parse_error2", since = "1.8.0")]
468 impl Error for Infallible {
469     fn description(&self) -> &str {
470         match *self {}
471     }
472 }
473
474 #[stable(feature = "decode_utf16", since = "1.9.0")]
475 impl Error for char::DecodeUtf16Error {
476     #[allow(deprecated)]
477     fn description(&self) -> &str {
478         "unpaired surrogate found"
479     }
480 }
481
482 #[stable(feature = "u8_from_char", since = "1.59.0")]
483 impl Error for char::TryFromCharError {}
484
485 #[unstable(feature = "map_try_insert", issue = "82766")]
486 impl<'a, K: Debug + Ord, V: Debug> Error
487     for crate::collections::btree_map::OccupiedError<'a, K, V>
488 {
489     #[allow(deprecated)]
490     fn description(&self) -> &str {
491         "key already exists"
492     }
493 }
494
495 #[unstable(feature = "map_try_insert", issue = "82766")]
496 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
497     #[allow(deprecated)]
498     fn description(&self) -> &str {
499         "key already exists"
500     }
501 }
502
503 #[stable(feature = "box_error", since = "1.8.0")]
504 impl<T: Error> Error for Box<T> {
505     #[allow(deprecated, deprecated_in_future)]
506     fn description(&self) -> &str {
507         Error::description(&**self)
508     }
509
510     #[allow(deprecated)]
511     fn cause(&self) -> Option<&dyn Error> {
512         Error::cause(&**self)
513     }
514
515     fn source(&self) -> Option<&(dyn Error + 'static)> {
516         Error::source(&**self)
517     }
518 }
519
520 #[unstable(feature = "thin_box", issue = "92791")]
521 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
522     fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
523         use core::ops::Deref;
524         self.deref().source()
525     }
526 }
527
528 #[stable(feature = "error_by_ref", since = "1.51.0")]
529 impl<'a, T: Error + ?Sized> Error for &'a T {
530     #[allow(deprecated, deprecated_in_future)]
531     fn description(&self) -> &str {
532         Error::description(&**self)
533     }
534
535     #[allow(deprecated)]
536     fn cause(&self) -> Option<&dyn Error> {
537         Error::cause(&**self)
538     }
539
540     fn source(&self) -> Option<&(dyn Error + 'static)> {
541         Error::source(&**self)
542     }
543
544     fn backtrace(&self) -> Option<&Backtrace> {
545         Error::backtrace(&**self)
546     }
547 }
548
549 #[stable(feature = "arc_error", since = "1.52.0")]
550 impl<T: Error + ?Sized> Error for Arc<T> {
551     #[allow(deprecated, deprecated_in_future)]
552     fn description(&self) -> &str {
553         Error::description(&**self)
554     }
555
556     #[allow(deprecated)]
557     fn cause(&self) -> Option<&dyn Error> {
558         Error::cause(&**self)
559     }
560
561     fn source(&self) -> Option<&(dyn Error + 'static)> {
562         Error::source(&**self)
563     }
564
565     fn backtrace(&self) -> Option<&Backtrace> {
566         Error::backtrace(&**self)
567     }
568 }
569
570 #[stable(feature = "fmt_error", since = "1.11.0")]
571 impl Error for fmt::Error {
572     #[allow(deprecated)]
573     fn description(&self) -> &str {
574         "an error occurred when formatting an argument"
575     }
576 }
577
578 #[stable(feature = "try_borrow", since = "1.13.0")]
579 impl Error for cell::BorrowError {
580     #[allow(deprecated)]
581     fn description(&self) -> &str {
582         "already mutably borrowed"
583     }
584 }
585
586 #[stable(feature = "try_borrow", since = "1.13.0")]
587 impl Error for cell::BorrowMutError {
588     #[allow(deprecated)]
589     fn description(&self) -> &str {
590         "already borrowed"
591     }
592 }
593
594 #[stable(feature = "try_from", since = "1.34.0")]
595 impl Error for char::CharTryFromError {
596     #[allow(deprecated)]
597     fn description(&self) -> &str {
598         "converted integer out of range for `char`"
599     }
600 }
601
602 #[stable(feature = "char_from_str", since = "1.20.0")]
603 impl Error for char::ParseCharError {
604     #[allow(deprecated)]
605     fn description(&self) -> &str {
606         self.__description()
607     }
608 }
609
610 #[stable(feature = "try_reserve", since = "1.57.0")]
611 impl Error for alloc::collections::TryReserveError {}
612
613 #[unstable(feature = "duration_checked_float", issue = "83400")]
614 impl Error for time::FromFloatSecsError {}
615
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl Error for alloc::ffi::NulError {
618     #[allow(deprecated)]
619     fn description(&self) -> &str {
620         "nul byte found in data"
621     }
622 }
623
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl From<alloc::ffi::NulError> for io::Error {
626     /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
627     fn from(_: alloc::ffi::NulError) -> io::Error {
628         io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
629     }
630 }
631
632 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
633 impl Error for core::ffi::FromBytesWithNulError {
634     #[allow(deprecated)]
635     fn description(&self) -> &str {
636         self.__description()
637     }
638 }
639
640 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
641 impl Error for core::ffi::FromBytesUntilNulError {}
642
643 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
644 impl Error for alloc::ffi::FromVecWithNulError {}
645
646 #[stable(feature = "cstring_into", since = "1.7.0")]
647 impl Error for alloc::ffi::IntoStringError {
648     #[allow(deprecated)]
649     fn description(&self) -> &str {
650         "C string contained non-utf8 bytes"
651     }
652
653     fn source(&self) -> Option<&(dyn Error + 'static)> {
654         Some(self.__source())
655     }
656 }
657
658 // Copied from `any.rs`.
659 impl dyn Error + 'static {
660     /// Returns `true` if the inner type is the same as `T`.
661     #[stable(feature = "error_downcast", since = "1.3.0")]
662     #[inline]
663     pub fn is<T: Error + 'static>(&self) -> bool {
664         // Get `TypeId` of the type this function is instantiated with.
665         let t = TypeId::of::<T>();
666
667         // Get `TypeId` of the type in the trait object (`self`).
668         let concrete = self.type_id(private::Internal);
669
670         // Compare both `TypeId`s on equality.
671         t == concrete
672     }
673
674     /// Returns some reference to the inner value if it is of type `T`, or
675     /// `None` if it isn't.
676     #[stable(feature = "error_downcast", since = "1.3.0")]
677     #[inline]
678     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
679         if self.is::<T>() {
680             unsafe { Some(&*(self as *const dyn Error as *const T)) }
681         } else {
682             None
683         }
684     }
685
686     /// Returns some mutable reference to the inner value if it is of type `T`, or
687     /// `None` if it isn't.
688     #[stable(feature = "error_downcast", since = "1.3.0")]
689     #[inline]
690     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
691         if self.is::<T>() {
692             unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
693         } else {
694             None
695         }
696     }
697 }
698
699 impl dyn Error + 'static + Send {
700     /// Forwards to the method defined on the type `dyn Error`.
701     #[stable(feature = "error_downcast", since = "1.3.0")]
702     #[inline]
703     pub fn is<T: Error + 'static>(&self) -> bool {
704         <dyn Error + 'static>::is::<T>(self)
705     }
706
707     /// Forwards to the method defined on the type `dyn Error`.
708     #[stable(feature = "error_downcast", since = "1.3.0")]
709     #[inline]
710     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
711         <dyn Error + 'static>::downcast_ref::<T>(self)
712     }
713
714     /// Forwards to the method defined on the type `dyn Error`.
715     #[stable(feature = "error_downcast", since = "1.3.0")]
716     #[inline]
717     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
718         <dyn Error + 'static>::downcast_mut::<T>(self)
719     }
720 }
721
722 impl dyn Error + 'static + Send + Sync {
723     /// Forwards to the method defined on the type `dyn Error`.
724     #[stable(feature = "error_downcast", since = "1.3.0")]
725     #[inline]
726     pub fn is<T: Error + 'static>(&self) -> bool {
727         <dyn Error + 'static>::is::<T>(self)
728     }
729
730     /// Forwards to the method defined on the type `dyn Error`.
731     #[stable(feature = "error_downcast", since = "1.3.0")]
732     #[inline]
733     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
734         <dyn Error + 'static>::downcast_ref::<T>(self)
735     }
736
737     /// Forwards to the method defined on the type `dyn Error`.
738     #[stable(feature = "error_downcast", since = "1.3.0")]
739     #[inline]
740     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
741         <dyn Error + 'static>::downcast_mut::<T>(self)
742     }
743 }
744
745 impl dyn Error {
746     #[inline]
747     #[stable(feature = "error_downcast", since = "1.3.0")]
748     /// Attempts to downcast the box to a concrete type.
749     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
750         if self.is::<T>() {
751             unsafe {
752                 let raw: *mut dyn Error = Box::into_raw(self);
753                 Ok(Box::from_raw(raw as *mut T))
754             }
755         } else {
756             Err(self)
757         }
758     }
759
760     /// Returns an iterator starting with the current error and continuing with
761     /// recursively calling [`Error::source`].
762     ///
763     /// If you want to omit the current error and only use its sources,
764     /// use `skip(1)`.
765     ///
766     /// # Examples
767     ///
768     /// ```
769     /// #![feature(error_iter)]
770     /// use std::error::Error;
771     /// use std::fmt;
772     ///
773     /// #[derive(Debug)]
774     /// struct A;
775     ///
776     /// #[derive(Debug)]
777     /// struct B(Option<Box<dyn Error + 'static>>);
778     ///
779     /// impl fmt::Display for A {
780     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781     ///         write!(f, "A")
782     ///     }
783     /// }
784     ///
785     /// impl fmt::Display for B {
786     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787     ///         write!(f, "B")
788     ///     }
789     /// }
790     ///
791     /// impl Error for A {}
792     ///
793     /// impl Error for B {
794     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
795     ///         self.0.as_ref().map(|e| e.as_ref())
796     ///     }
797     /// }
798     ///
799     /// let b = B(Some(Box::new(A)));
800     ///
801     /// // let err : Box<Error> = b.into(); // or
802     /// let err = &b as &(dyn Error);
803     ///
804     /// let mut iter = err.chain();
805     ///
806     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
807     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
808     /// assert!(iter.next().is_none());
809     /// assert!(iter.next().is_none());
810     /// ```
811     #[unstable(feature = "error_iter", issue = "58520")]
812     #[inline]
813     pub fn chain(&self) -> Chain<'_> {
814         Chain { current: Some(self) }
815     }
816 }
817
818 /// An iterator over an [`Error`] and its sources.
819 ///
820 /// If you want to omit the initial error and only process
821 /// its sources, use `skip(1)`.
822 #[unstable(feature = "error_iter", issue = "58520")]
823 #[derive(Clone, Debug)]
824 pub struct Chain<'a> {
825     current: Option<&'a (dyn Error + 'static)>,
826 }
827
828 #[unstable(feature = "error_iter", issue = "58520")]
829 impl<'a> Iterator for Chain<'a> {
830     type Item = &'a (dyn Error + 'static);
831
832     fn next(&mut self) -> Option<Self::Item> {
833         let current = self.current;
834         self.current = self.current.and_then(Error::source);
835         current
836     }
837 }
838
839 impl dyn Error + Send {
840     #[inline]
841     #[stable(feature = "error_downcast", since = "1.3.0")]
842     /// Attempts to downcast the box to a concrete type.
843     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
844         let err: Box<dyn Error> = self;
845         <dyn Error>::downcast(err).map_err(|s| unsafe {
846             // Reapply the `Send` marker.
847             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
848         })
849     }
850 }
851
852 impl dyn Error + Send + Sync {
853     #[inline]
854     #[stable(feature = "error_downcast", since = "1.3.0")]
855     /// Attempts to downcast the box to a concrete type.
856     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
857         let err: Box<dyn Error> = self;
858         <dyn Error>::downcast(err).map_err(|s| unsafe {
859             // Reapply the `Send + Sync` marker.
860             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
861         })
862     }
863 }
864
865 /// An error reporter that print's an error and its sources.
866 ///
867 /// Report also exposes configuration options for formatting the error chain, either entirely on a
868 /// single line, or in multi-line format with each cause in the error chain on a new line.
869 ///
870 /// `Report` only requires that the wrapped error implements `Error`. It doesn't require that the
871 /// wrapped error be `Send`, `Sync`, or `'static`.
872 ///
873 /// # Examples
874 ///
875 /// ```rust
876 /// #![feature(error_reporter)]
877 /// use std::error::{Error, Report};
878 /// use std::fmt;
879 ///
880 /// #[derive(Debug)]
881 /// struct SuperError {
882 ///     source: SuperErrorSideKick,
883 /// }
884 ///
885 /// impl fmt::Display for SuperError {
886 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887 ///         write!(f, "SuperError is here!")
888 ///     }
889 /// }
890 ///
891 /// impl Error for SuperError {
892 ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
893 ///         Some(&self.source)
894 ///     }
895 /// }
896 ///
897 /// #[derive(Debug)]
898 /// struct SuperErrorSideKick;
899 ///
900 /// impl fmt::Display for SuperErrorSideKick {
901 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 ///         write!(f, "SuperErrorSideKick is here!")
903 ///     }
904 /// }
905 ///
906 /// impl Error for SuperErrorSideKick {}
907 ///
908 /// fn get_super_error() -> Result<(), SuperError> {
909 ///     Err(SuperError { source: SuperErrorSideKick })
910 /// }
911 ///
912 /// fn main() {
913 ///     match get_super_error() {
914 ///         Err(e) => println!("Error: {}", Report::new(e)),
915 ///         _ => println!("No error"),
916 ///     }
917 /// }
918 /// ```
919 ///
920 /// This example produces the following output:
921 ///
922 /// ```console
923 /// Error: SuperError is here!: SuperErrorSideKick is here!
924 /// ```
925 ///
926 /// ## Output consistency
927 ///
928 /// Report prints the same output via `Display` and `Debug`, so it works well with
929 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
930 ///
931 /// ```should_panic
932 /// #![feature(error_reporter)]
933 /// use std::error::Report;
934 /// # use std::error::Error;
935 /// # use std::fmt;
936 /// # #[derive(Debug)]
937 /// # struct SuperError {
938 /// #     source: SuperErrorSideKick,
939 /// # }
940 /// # impl fmt::Display for SuperError {
941 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 /// #         write!(f, "SuperError is here!")
943 /// #     }
944 /// # }
945 /// # impl Error for SuperError {
946 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
947 /// #         Some(&self.source)
948 /// #     }
949 /// # }
950 /// # #[derive(Debug)]
951 /// # struct SuperErrorSideKick;
952 /// # impl fmt::Display for SuperErrorSideKick {
953 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 /// #         write!(f, "SuperErrorSideKick is here!")
955 /// #     }
956 /// # }
957 /// # impl Error for SuperErrorSideKick {}
958 /// # fn get_super_error() -> Result<(), SuperError> {
959 /// #     Err(SuperError { source: SuperErrorSideKick })
960 /// # }
961 ///
962 /// get_super_error().map_err(Report::new).unwrap();
963 /// ```
964 ///
965 /// This example produces the following output:
966 ///
967 /// ```console
968 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
969 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
970 /// ```
971 ///
972 /// ## Return from `main`
973 ///
974 /// `Report` also implements `From` for all types that implement [`Error`], this when combined with
975 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
976 /// from `main`.
977 ///
978 /// ```should_panic
979 /// #![feature(error_reporter)]
980 /// use std::error::Report;
981 /// # use std::error::Error;
982 /// # use std::fmt;
983 /// # #[derive(Debug)]
984 /// # struct SuperError {
985 /// #     source: SuperErrorSideKick,
986 /// # }
987 /// # impl fmt::Display for SuperError {
988 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989 /// #         write!(f, "SuperError is here!")
990 /// #     }
991 /// # }
992 /// # impl Error for SuperError {
993 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
994 /// #         Some(&self.source)
995 /// #     }
996 /// # }
997 /// # #[derive(Debug)]
998 /// # struct SuperErrorSideKick;
999 /// # impl fmt::Display for SuperErrorSideKick {
1000 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 /// #         write!(f, "SuperErrorSideKick is here!")
1002 /// #     }
1003 /// # }
1004 /// # impl Error for SuperErrorSideKick {}
1005 /// # fn get_super_error() -> Result<(), SuperError> {
1006 /// #     Err(SuperError { source: SuperErrorSideKick })
1007 /// # }
1008 ///
1009 /// fn main() -> Result<(), Report> {
1010 ///     get_super_error()?;
1011 ///     Ok(())
1012 /// }
1013 /// ```
1014 ///
1015 /// This example produces the following output:
1016 ///
1017 /// ```console
1018 /// Error: SuperError is here!: SuperErrorSideKick is here!
1019 /// ```
1020 ///
1021 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1022 /// output format, if you want to make sure your `Report`s are pretty printed and include backtrace
1023 /// you will need to manually convert and enable those flags.
1024 ///
1025 /// ```should_panic
1026 /// #![feature(error_reporter)]
1027 /// use std::error::Report;
1028 /// # use std::error::Error;
1029 /// # use std::fmt;
1030 /// # #[derive(Debug)]
1031 /// # struct SuperError {
1032 /// #     source: SuperErrorSideKick,
1033 /// # }
1034 /// # impl fmt::Display for SuperError {
1035 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 /// #         write!(f, "SuperError is here!")
1037 /// #     }
1038 /// # }
1039 /// # impl Error for SuperError {
1040 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1041 /// #         Some(&self.source)
1042 /// #     }
1043 /// # }
1044 /// # #[derive(Debug)]
1045 /// # struct SuperErrorSideKick;
1046 /// # impl fmt::Display for SuperErrorSideKick {
1047 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048 /// #         write!(f, "SuperErrorSideKick is here!")
1049 /// #     }
1050 /// # }
1051 /// # impl Error for SuperErrorSideKick {}
1052 /// # fn get_super_error() -> Result<(), SuperError> {
1053 /// #     Err(SuperError { source: SuperErrorSideKick })
1054 /// # }
1055 ///
1056 /// fn main() -> Result<(), Report> {
1057 ///     get_super_error()
1058 ///         .map_err(Report::from)
1059 ///         .map_err(|r| r.pretty(true).show_backtrace(true))?;
1060 ///     Ok(())
1061 /// }
1062 /// ```
1063 ///
1064 /// This example produces the following output:
1065 ///
1066 /// ```console
1067 /// Error: SuperError is here!
1068 ///
1069 /// Caused by:
1070 ///       SuperErrorSideKick is here!
1071 /// ```
1072 #[unstable(feature = "error_reporter", issue = "90172")]
1073 pub struct Report<E = Box<dyn Error>> {
1074     /// The error being reported.
1075     error: E,
1076     /// Whether a backtrace should be included as part of the report.
1077     show_backtrace: bool,
1078     /// Whether the report should be pretty-printed.
1079     pretty: bool,
1080 }
1081
1082 impl<E> Report<E>
1083 where
1084     Report<E>: From<E>,
1085 {
1086     /// Create a new `Report` from an input error.
1087     #[unstable(feature = "error_reporter", issue = "90172")]
1088     pub fn new(error: E) -> Report<E> {
1089         Self::from(error)
1090     }
1091 }
1092
1093 impl<E> Report<E> {
1094     /// Enable pretty-printing the report across multiple lines.
1095     ///
1096     /// # Examples
1097     ///
1098     /// ```rust
1099     /// #![feature(error_reporter)]
1100     /// use std::error::Report;
1101     /// # use std::error::Error;
1102     /// # use std::fmt;
1103     /// # #[derive(Debug)]
1104     /// # struct SuperError {
1105     /// #     source: SuperErrorSideKick,
1106     /// # }
1107     /// # impl fmt::Display for SuperError {
1108     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109     /// #         write!(f, "SuperError is here!")
1110     /// #     }
1111     /// # }
1112     /// # impl Error for SuperError {
1113     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1114     /// #         Some(&self.source)
1115     /// #     }
1116     /// # }
1117     /// # #[derive(Debug)]
1118     /// # struct SuperErrorSideKick;
1119     /// # impl fmt::Display for SuperErrorSideKick {
1120     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121     /// #         write!(f, "SuperErrorSideKick is here!")
1122     /// #     }
1123     /// # }
1124     /// # impl Error for SuperErrorSideKick {}
1125     ///
1126     /// let error = SuperError { source: SuperErrorSideKick };
1127     /// let report = Report::new(error).pretty(true);
1128     /// eprintln!("Error: {report:?}");
1129     /// ```
1130     ///
1131     /// This example produces the following output:
1132     ///
1133     /// ```console
1134     /// Error: SuperError is here!
1135     ///
1136     /// Caused by:
1137     ///       SuperErrorSideKick is here!
1138     /// ```
1139     ///
1140     /// When there are multiple source errors the causes will be numbered in order of iteration
1141     /// starting from the outermost error.
1142     ///
1143     /// ```rust
1144     /// #![feature(error_reporter)]
1145     /// use std::error::Report;
1146     /// # use std::error::Error;
1147     /// # use std::fmt;
1148     /// # #[derive(Debug)]
1149     /// # struct SuperError {
1150     /// #     source: SuperErrorSideKick,
1151     /// # }
1152     /// # impl fmt::Display for SuperError {
1153     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1154     /// #         write!(f, "SuperError is here!")
1155     /// #     }
1156     /// # }
1157     /// # impl Error for SuperError {
1158     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1159     /// #         Some(&self.source)
1160     /// #     }
1161     /// # }
1162     /// # #[derive(Debug)]
1163     /// # struct SuperErrorSideKick {
1164     /// #     source: SuperErrorSideKickSideKick,
1165     /// # }
1166     /// # impl fmt::Display for SuperErrorSideKick {
1167     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168     /// #         write!(f, "SuperErrorSideKick is here!")
1169     /// #     }
1170     /// # }
1171     /// # impl Error for SuperErrorSideKick {
1172     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1173     /// #         Some(&self.source)
1174     /// #     }
1175     /// # }
1176     /// # #[derive(Debug)]
1177     /// # struct SuperErrorSideKickSideKick;
1178     /// # impl fmt::Display for SuperErrorSideKickSideKick {
1179     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180     /// #         write!(f, "SuperErrorSideKickSideKick is here!")
1181     /// #     }
1182     /// # }
1183     /// # impl Error for SuperErrorSideKickSideKick { }
1184     ///
1185     /// let source = SuperErrorSideKickSideKick;
1186     /// let source = SuperErrorSideKick { source };
1187     /// let error = SuperError { source };
1188     /// let report = Report::new(error).pretty(true);
1189     /// eprintln!("Error: {report:?}");
1190     /// ```
1191     ///
1192     /// This example produces the following output:
1193     ///
1194     /// ```console
1195     /// Error: SuperError is here!
1196     ///
1197     /// Caused by:
1198     ///    0: SuperErrorSideKick is here!
1199     ///    1: SuperErrorSideKickSideKick is here!
1200     /// ```
1201     #[unstable(feature = "error_reporter", issue = "90172")]
1202     pub fn pretty(mut self, pretty: bool) -> Self {
1203         self.pretty = pretty;
1204         self
1205     }
1206
1207     /// Display backtrace if available when using pretty output format.
1208     ///
1209     /// # Examples
1210     ///
1211     /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1212     /// outermost error. In this example it will display the backtrace from the second error in the
1213     /// chain, `SuperErrorSideKick`.
1214     ///
1215     /// ```rust
1216     /// #![feature(error_reporter)]
1217     /// #![feature(backtrace)]
1218     /// # use std::error::Error;
1219     /// # use std::fmt;
1220     /// use std::error::Report;
1221     /// use std::backtrace::Backtrace;
1222     ///
1223     /// # #[derive(Debug)]
1224     /// # struct SuperError {
1225     /// #     source: SuperErrorSideKick,
1226     /// # }
1227     /// # impl fmt::Display for SuperError {
1228     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229     /// #         write!(f, "SuperError is here!")
1230     /// #     }
1231     /// # }
1232     /// # impl Error for SuperError {
1233     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1234     /// #         Some(&self.source)
1235     /// #     }
1236     /// # }
1237     /// #[derive(Debug)]
1238     /// struct SuperErrorSideKick {
1239     ///     backtrace: Backtrace,
1240     /// }
1241     ///
1242     /// impl SuperErrorSideKick {
1243     ///     fn new() -> SuperErrorSideKick {
1244     ///         SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1245     ///     }
1246     /// }
1247     ///
1248     /// impl Error for SuperErrorSideKick {
1249     ///     fn backtrace(&self) -> Option<&Backtrace> {
1250     ///         Some(&self.backtrace)
1251     ///     }
1252     /// }
1253     ///
1254     /// // The rest of the example is unchanged ...
1255     /// # impl fmt::Display for SuperErrorSideKick {
1256     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257     /// #         write!(f, "SuperErrorSideKick is here!")
1258     /// #     }
1259     /// # }
1260     ///
1261     /// let source = SuperErrorSideKick::new();
1262     /// let error = SuperError { source };
1263     /// let report = Report::new(error).pretty(true).show_backtrace(true);
1264     /// eprintln!("Error: {report:?}");
1265     /// ```
1266     ///
1267     /// This example produces something similar to the following output:
1268     ///
1269     /// ```console
1270     /// Error: SuperError is here!
1271     ///
1272     /// Caused by:
1273     ///       SuperErrorSideKick is here!
1274     ///
1275     /// Stack backtrace:
1276     ///    0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1277     ///    1: rust_out::main::_doctest_main_src_error_rs_1158_0
1278     ///    2: rust_out::main
1279     ///    3: core::ops::function::FnOnce::call_once
1280     ///    4: std::sys_common::backtrace::__rust_begin_short_backtrace
1281     ///    5: std::rt::lang_start::{{closure}}
1282     ///    6: std::panicking::try
1283     ///    7: std::rt::lang_start_internal
1284     ///    8: std::rt::lang_start
1285     ///    9: main
1286     ///   10: __libc_start_main
1287     ///   11: _start
1288     /// ```
1289     #[unstable(feature = "error_reporter", issue = "90172")]
1290     pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1291         self.show_backtrace = show_backtrace;
1292         self
1293     }
1294 }
1295
1296 impl<E> Report<E>
1297 where
1298     E: Error,
1299 {
1300     fn backtrace(&self) -> Option<&Backtrace> {
1301         // have to grab the backtrace on the first error directly since that error may not be
1302         // 'static
1303         let backtrace = self.error.backtrace();
1304         let backtrace = backtrace.or_else(|| {
1305             self.error
1306                 .source()
1307                 .map(|source| source.chain().find_map(|source| source.backtrace()))
1308                 .flatten()
1309         });
1310         backtrace
1311     }
1312
1313     /// Format the report as a single line.
1314     #[unstable(feature = "error_reporter", issue = "90172")]
1315     fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1316         write!(f, "{}", self.error)?;
1317
1318         let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1319
1320         for cause in sources {
1321             write!(f, ": {cause}")?;
1322         }
1323
1324         Ok(())
1325     }
1326
1327     /// Format the report as multiple lines, with each error cause on its own line.
1328     #[unstable(feature = "error_reporter", issue = "90172")]
1329     fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330         let error = &self.error;
1331
1332         write!(f, "{error}")?;
1333
1334         if let Some(cause) = error.source() {
1335             write!(f, "\n\nCaused by:")?;
1336
1337             let multiple = cause.source().is_some();
1338
1339             for (ind, error) in cause.chain().enumerate() {
1340                 writeln!(f)?;
1341                 let mut indented = Indented { inner: f };
1342                 if multiple {
1343                     write!(indented, "{ind: >4}: {error}")?;
1344                 } else {
1345                     write!(indented, "      {error}")?;
1346                 }
1347             }
1348         }
1349
1350         if self.show_backtrace {
1351             let backtrace = self.backtrace();
1352
1353             if let Some(backtrace) = backtrace {
1354                 let backtrace = backtrace.to_string();
1355
1356                 f.write_str("\n\nStack backtrace:\n")?;
1357                 f.write_str(backtrace.trim_end())?;
1358             }
1359         }
1360
1361         Ok(())
1362     }
1363 }
1364
1365 impl Report<Box<dyn Error>> {
1366     fn backtrace(&self) -> Option<&Backtrace> {
1367         // have to grab the backtrace on the first error directly since that error may not be
1368         // 'static
1369         let backtrace = self.error.backtrace();
1370         let backtrace = backtrace.or_else(|| {
1371             self.error
1372                 .source()
1373                 .map(|source| source.chain().find_map(|source| source.backtrace()))
1374                 .flatten()
1375         });
1376         backtrace
1377     }
1378
1379     /// Format the report as a single line.
1380     #[unstable(feature = "error_reporter", issue = "90172")]
1381     fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1382         write!(f, "{}", self.error)?;
1383
1384         let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1385
1386         for cause in sources {
1387             write!(f, ": {cause}")?;
1388         }
1389
1390         Ok(())
1391     }
1392
1393     /// Format the report as multiple lines, with each error cause on its own line.
1394     #[unstable(feature = "error_reporter", issue = "90172")]
1395     fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1396         let error = &self.error;
1397
1398         write!(f, "{error}")?;
1399
1400         if let Some(cause) = error.source() {
1401             write!(f, "\n\nCaused by:")?;
1402
1403             let multiple = cause.source().is_some();
1404
1405             for (ind, error) in cause.chain().enumerate() {
1406                 writeln!(f)?;
1407                 let mut indented = Indented { inner: f };
1408                 if multiple {
1409                     write!(indented, "{ind: >4}: {error}")?;
1410                 } else {
1411                     write!(indented, "      {error}")?;
1412                 }
1413             }
1414         }
1415
1416         if self.show_backtrace {
1417             let backtrace = self.backtrace();
1418
1419             if let Some(backtrace) = backtrace {
1420                 let backtrace = backtrace.to_string();
1421
1422                 f.write_str("\n\nStack backtrace:\n")?;
1423                 f.write_str(backtrace.trim_end())?;
1424             }
1425         }
1426
1427         Ok(())
1428     }
1429 }
1430
1431 #[unstable(feature = "error_reporter", issue = "90172")]
1432 impl<E> From<E> for Report<E>
1433 where
1434     E: Error,
1435 {
1436     fn from(error: E) -> Self {
1437         Report { error, show_backtrace: false, pretty: false }
1438     }
1439 }
1440
1441 #[unstable(feature = "error_reporter", issue = "90172")]
1442 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1443 where
1444     E: Error + 'a,
1445 {
1446     fn from(error: E) -> Self {
1447         let error = box error;
1448         Report { error, show_backtrace: false, pretty: false }
1449     }
1450 }
1451
1452 #[unstable(feature = "error_reporter", issue = "90172")]
1453 impl<E> fmt::Display for Report<E>
1454 where
1455     E: Error,
1456 {
1457     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458         if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1459     }
1460 }
1461
1462 #[unstable(feature = "error_reporter", issue = "90172")]
1463 impl fmt::Display for Report<Box<dyn Error>> {
1464     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1465         if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1466     }
1467 }
1468
1469 // This type intentionally outputs the same format for `Display` and `Debug`for
1470 // situations where you unwrap a `Report` or return it from main.
1471 #[unstable(feature = "error_reporter", issue = "90172")]
1472 impl<E> fmt::Debug for Report<E>
1473 where
1474     Report<E>: fmt::Display,
1475 {
1476     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477         fmt::Display::fmt(self, f)
1478     }
1479 }
1480
1481 /// Wrapper type for indenting the inner source.
1482 struct Indented<'a, D> {
1483     inner: &'a mut D,
1484 }
1485
1486 impl<T> Write for Indented<'_, T>
1487 where
1488     T: Write,
1489 {
1490     fn write_str(&mut self, s: &str) -> fmt::Result {
1491         for (i, line) in s.split('\n').enumerate() {
1492             if i > 0 {
1493                 self.inner.write_char('\n')?;
1494                 self.inner.write_str("      ")?;
1495             }
1496
1497             self.inner.write_str(line)?;
1498         }
1499
1500         Ok(())
1501     }
1502 }