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