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