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