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