]> git.lizzy.rs Git - rust.git/blob - library/std/src/error.rs
Auto merge of #93146 - workingjubilee:use-std-simd, r=Mark-Simulacrum
[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 #[stable(feature = "error_by_ref", since = "1.51.0")]
520 impl<'a, T: Error + ?Sized> Error for &'a T {
521     #[allow(deprecated, deprecated_in_future)]
522     fn description(&self) -> &str {
523         Error::description(&**self)
524     }
525
526     #[allow(deprecated)]
527     fn cause(&self) -> Option<&dyn Error> {
528         Error::cause(&**self)
529     }
530
531     fn source(&self) -> Option<&(dyn Error + 'static)> {
532         Error::source(&**self)
533     }
534
535     fn backtrace(&self) -> Option<&Backtrace> {
536         Error::backtrace(&**self)
537     }
538 }
539
540 #[stable(feature = "arc_error", since = "1.52.0")]
541 impl<T: Error + ?Sized> Error for Arc<T> {
542     #[allow(deprecated, deprecated_in_future)]
543     fn description(&self) -> &str {
544         Error::description(&**self)
545     }
546
547     #[allow(deprecated)]
548     fn cause(&self) -> Option<&dyn Error> {
549         Error::cause(&**self)
550     }
551
552     fn source(&self) -> Option<&(dyn Error + 'static)> {
553         Error::source(&**self)
554     }
555
556     fn backtrace(&self) -> Option<&Backtrace> {
557         Error::backtrace(&**self)
558     }
559 }
560
561 #[stable(feature = "fmt_error", since = "1.11.0")]
562 impl Error for fmt::Error {
563     #[allow(deprecated)]
564     fn description(&self) -> &str {
565         "an error occurred when formatting an argument"
566     }
567 }
568
569 #[stable(feature = "try_borrow", since = "1.13.0")]
570 impl Error for cell::BorrowError {
571     #[allow(deprecated)]
572     fn description(&self) -> &str {
573         "already mutably borrowed"
574     }
575 }
576
577 #[stable(feature = "try_borrow", since = "1.13.0")]
578 impl Error for cell::BorrowMutError {
579     #[allow(deprecated)]
580     fn description(&self) -> &str {
581         "already borrowed"
582     }
583 }
584
585 #[stable(feature = "try_from", since = "1.34.0")]
586 impl Error for char::CharTryFromError {
587     #[allow(deprecated)]
588     fn description(&self) -> &str {
589         "converted integer out of range for `char`"
590     }
591 }
592
593 #[stable(feature = "char_from_str", since = "1.20.0")]
594 impl Error for char::ParseCharError {
595     #[allow(deprecated)]
596     fn description(&self) -> &str {
597         self.__description()
598     }
599 }
600
601 #[stable(feature = "try_reserve", since = "1.57.0")]
602 impl Error for alloc::collections::TryReserveError {}
603
604 #[unstable(feature = "duration_checked_float", issue = "83400")]
605 impl Error for time::FromFloatSecsError {}
606
607 // Copied from `any.rs`.
608 impl dyn Error + 'static {
609     /// Returns `true` if the inner type is the same as `T`.
610     #[stable(feature = "error_downcast", since = "1.3.0")]
611     #[inline]
612     pub fn is<T: Error + 'static>(&self) -> bool {
613         // Get `TypeId` of the type this function is instantiated with.
614         let t = TypeId::of::<T>();
615
616         // Get `TypeId` of the type in the trait object (`self`).
617         let concrete = self.type_id(private::Internal);
618
619         // Compare both `TypeId`s on equality.
620         t == concrete
621     }
622
623     /// Returns some reference to the inner value if it is of type `T`, or
624     /// `None` if it isn't.
625     #[stable(feature = "error_downcast", since = "1.3.0")]
626     #[inline]
627     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
628         if self.is::<T>() {
629             unsafe { Some(&*(self as *const dyn Error as *const T)) }
630         } else {
631             None
632         }
633     }
634
635     /// Returns some mutable reference to the inner value if it is of type `T`, or
636     /// `None` if it isn't.
637     #[stable(feature = "error_downcast", since = "1.3.0")]
638     #[inline]
639     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
640         if self.is::<T>() {
641             unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
642         } else {
643             None
644         }
645     }
646 }
647
648 impl dyn Error + 'static + Send {
649     /// Forwards to the method defined on the type `dyn Error`.
650     #[stable(feature = "error_downcast", since = "1.3.0")]
651     #[inline]
652     pub fn is<T: Error + 'static>(&self) -> bool {
653         <dyn Error + 'static>::is::<T>(self)
654     }
655
656     /// Forwards to the method defined on the type `dyn Error`.
657     #[stable(feature = "error_downcast", since = "1.3.0")]
658     #[inline]
659     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
660         <dyn Error + 'static>::downcast_ref::<T>(self)
661     }
662
663     /// Forwards to the method defined on the type `dyn Error`.
664     #[stable(feature = "error_downcast", since = "1.3.0")]
665     #[inline]
666     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
667         <dyn Error + 'static>::downcast_mut::<T>(self)
668     }
669 }
670
671 impl dyn Error + 'static + Send + Sync {
672     /// Forwards to the method defined on the type `dyn Error`.
673     #[stable(feature = "error_downcast", since = "1.3.0")]
674     #[inline]
675     pub fn is<T: Error + 'static>(&self) -> bool {
676         <dyn Error + 'static>::is::<T>(self)
677     }
678
679     /// Forwards to the method defined on the type `dyn Error`.
680     #[stable(feature = "error_downcast", since = "1.3.0")]
681     #[inline]
682     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
683         <dyn Error + 'static>::downcast_ref::<T>(self)
684     }
685
686     /// Forwards to the method defined on the type `dyn Error`.
687     #[stable(feature = "error_downcast", since = "1.3.0")]
688     #[inline]
689     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
690         <dyn Error + 'static>::downcast_mut::<T>(self)
691     }
692 }
693
694 impl dyn Error {
695     #[inline]
696     #[stable(feature = "error_downcast", since = "1.3.0")]
697     /// Attempts to downcast the box to a concrete type.
698     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
699         if self.is::<T>() {
700             unsafe {
701                 let raw: *mut dyn Error = Box::into_raw(self);
702                 Ok(Box::from_raw(raw as *mut T))
703             }
704         } else {
705             Err(self)
706         }
707     }
708
709     /// Returns an iterator starting with the current error and continuing with
710     /// recursively calling [`Error::source`].
711     ///
712     /// If you want to omit the current error and only use its sources,
713     /// use `skip(1)`.
714     ///
715     /// # Examples
716     ///
717     /// ```
718     /// #![feature(error_iter)]
719     /// use std::error::Error;
720     /// use std::fmt;
721     ///
722     /// #[derive(Debug)]
723     /// struct A;
724     ///
725     /// #[derive(Debug)]
726     /// struct B(Option<Box<dyn Error + 'static>>);
727     ///
728     /// impl fmt::Display for A {
729     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730     ///         write!(f, "A")
731     ///     }
732     /// }
733     ///
734     /// impl fmt::Display for B {
735     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736     ///         write!(f, "B")
737     ///     }
738     /// }
739     ///
740     /// impl Error for A {}
741     ///
742     /// impl Error for B {
743     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
744     ///         self.0.as_ref().map(|e| e.as_ref())
745     ///     }
746     /// }
747     ///
748     /// let b = B(Some(Box::new(A)));
749     ///
750     /// // let err : Box<Error> = b.into(); // or
751     /// let err = &b as &(dyn Error);
752     ///
753     /// let mut iter = err.chain();
754     ///
755     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
756     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
757     /// assert!(iter.next().is_none());
758     /// assert!(iter.next().is_none());
759     /// ```
760     #[unstable(feature = "error_iter", issue = "58520")]
761     #[inline]
762     pub fn chain(&self) -> Chain<'_> {
763         Chain { current: Some(self) }
764     }
765 }
766
767 /// An iterator over an [`Error`] and its sources.
768 ///
769 /// If you want to omit the initial error and only process
770 /// its sources, use `skip(1)`.
771 #[unstable(feature = "error_iter", issue = "58520")]
772 #[derive(Clone, Debug)]
773 pub struct Chain<'a> {
774     current: Option<&'a (dyn Error + 'static)>,
775 }
776
777 #[unstable(feature = "error_iter", issue = "58520")]
778 impl<'a> Iterator for Chain<'a> {
779     type Item = &'a (dyn Error + 'static);
780
781     fn next(&mut self) -> Option<Self::Item> {
782         let current = self.current;
783         self.current = self.current.and_then(Error::source);
784         current
785     }
786 }
787
788 impl dyn Error + Send {
789     #[inline]
790     #[stable(feature = "error_downcast", since = "1.3.0")]
791     /// Attempts to downcast the box to a concrete type.
792     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
793         let err: Box<dyn Error> = self;
794         <dyn Error>::downcast(err).map_err(|s| unsafe {
795             // Reapply the `Send` marker.
796             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
797         })
798     }
799 }
800
801 impl dyn Error + Send + Sync {
802     #[inline]
803     #[stable(feature = "error_downcast", since = "1.3.0")]
804     /// Attempts to downcast the box to a concrete type.
805     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
806         let err: Box<dyn Error> = self;
807         <dyn Error>::downcast(err).map_err(|s| unsafe {
808             // Reapply the `Send + Sync` marker.
809             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
810         })
811     }
812 }
813
814 /// An error reporter that print's an error and its sources.
815 ///
816 /// Report also exposes configuration options for formatting the error chain, either entirely on a
817 /// single line, or in multi-line format with each cause in the error chain on a new line.
818 ///
819 /// `Report` only requires that the wrapped error implements `Error`. It doesn't require that the
820 /// wrapped error be `Send`, `Sync`, or `'static`.
821 ///
822 /// # Examples
823 ///
824 /// ```rust
825 /// #![feature(error_reporter)]
826 /// use std::error::{Error, Report};
827 /// use std::fmt;
828 ///
829 /// #[derive(Debug)]
830 /// struct SuperError {
831 ///     source: SuperErrorSideKick,
832 /// }
833 ///
834 /// impl fmt::Display for SuperError {
835 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 ///         write!(f, "SuperError is here!")
837 ///     }
838 /// }
839 ///
840 /// impl Error for SuperError {
841 ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
842 ///         Some(&self.source)
843 ///     }
844 /// }
845 ///
846 /// #[derive(Debug)]
847 /// struct SuperErrorSideKick;
848 ///
849 /// impl fmt::Display for SuperErrorSideKick {
850 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 ///         write!(f, "SuperErrorSideKick is here!")
852 ///     }
853 /// }
854 ///
855 /// impl Error for SuperErrorSideKick {}
856 ///
857 /// fn get_super_error() -> Result<(), SuperError> {
858 ///     Err(SuperError { source: SuperErrorSideKick })
859 /// }
860 ///
861 /// fn main() {
862 ///     match get_super_error() {
863 ///         Err(e) => println!("Error: {}", Report::new(e)),
864 ///         _ => println!("No error"),
865 ///     }
866 /// }
867 /// ```
868 ///
869 /// This example produces the following output:
870 ///
871 /// ```console
872 /// Error: SuperError is here!: SuperErrorSideKick is here!
873 /// ```
874 ///
875 /// ## Output consistency
876 ///
877 /// Report prints the same output via `Display` and `Debug`, so it works well with
878 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
879 ///
880 /// ```should_panic
881 /// #![feature(error_reporter)]
882 /// use std::error::Report;
883 /// # use std::error::Error;
884 /// # use std::fmt;
885 /// # #[derive(Debug)]
886 /// # struct SuperError {
887 /// #     source: SuperErrorSideKick,
888 /// # }
889 /// # impl fmt::Display for SuperError {
890 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891 /// #         write!(f, "SuperError is here!")
892 /// #     }
893 /// # }
894 /// # impl Error for SuperError {
895 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
896 /// #         Some(&self.source)
897 /// #     }
898 /// # }
899 /// # #[derive(Debug)]
900 /// # struct SuperErrorSideKick;
901 /// # impl fmt::Display for SuperErrorSideKick {
902 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 /// #         write!(f, "SuperErrorSideKick is here!")
904 /// #     }
905 /// # }
906 /// # impl Error for SuperErrorSideKick {}
907 /// # fn get_super_error() -> Result<(), SuperError> {
908 /// #     Err(SuperError { source: SuperErrorSideKick })
909 /// # }
910 ///
911 /// get_super_error().map_err(Report::new).unwrap();
912 /// ```
913 ///
914 /// This example produces the following output:
915 ///
916 /// ```console
917 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
918 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
919 /// ```
920 ///
921 /// ## Return from `main`
922 ///
923 /// `Report` also implements `From` for all types that implement [`Error`], this when combined with
924 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
925 /// from `main`.
926 ///
927 /// ```should_panic
928 /// #![feature(error_reporter)]
929 /// use std::error::Report;
930 /// # use std::error::Error;
931 /// # use std::fmt;
932 /// # #[derive(Debug)]
933 /// # struct SuperError {
934 /// #     source: SuperErrorSideKick,
935 /// # }
936 /// # impl fmt::Display for SuperError {
937 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938 /// #         write!(f, "SuperError is here!")
939 /// #     }
940 /// # }
941 /// # impl Error for SuperError {
942 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
943 /// #         Some(&self.source)
944 /// #     }
945 /// # }
946 /// # #[derive(Debug)]
947 /// # struct SuperErrorSideKick;
948 /// # impl fmt::Display for SuperErrorSideKick {
949 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950 /// #         write!(f, "SuperErrorSideKick is here!")
951 /// #     }
952 /// # }
953 /// # impl Error for SuperErrorSideKick {}
954 /// # fn get_super_error() -> Result<(), SuperError> {
955 /// #     Err(SuperError { source: SuperErrorSideKick })
956 /// # }
957 ///
958 /// fn main() -> Result<(), Report> {
959 ///     get_super_error()?;
960 ///     Ok(())
961 /// }
962 /// ```
963 ///
964 /// This example produces the following output:
965 ///
966 /// ```console
967 /// Error: SuperError is here!: SuperErrorSideKick is here!
968 /// ```
969 ///
970 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
971 /// output format, if you want to make sure your `Report`s are pretty printed and include backtrace
972 /// you will need to manually convert and enable those flags.
973 ///
974 /// ```should_panic
975 /// #![feature(error_reporter)]
976 /// use std::error::Report;
977 /// # use std::error::Error;
978 /// # use std::fmt;
979 /// # #[derive(Debug)]
980 /// # struct SuperError {
981 /// #     source: SuperErrorSideKick,
982 /// # }
983 /// # impl fmt::Display for SuperError {
984 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985 /// #         write!(f, "SuperError is here!")
986 /// #     }
987 /// # }
988 /// # impl Error for SuperError {
989 /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
990 /// #         Some(&self.source)
991 /// #     }
992 /// # }
993 /// # #[derive(Debug)]
994 /// # struct SuperErrorSideKick;
995 /// # impl fmt::Display for SuperErrorSideKick {
996 /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 /// #         write!(f, "SuperErrorSideKick is here!")
998 /// #     }
999 /// # }
1000 /// # impl Error for SuperErrorSideKick {}
1001 /// # fn get_super_error() -> Result<(), SuperError> {
1002 /// #     Err(SuperError { source: SuperErrorSideKick })
1003 /// # }
1004 ///
1005 /// fn main() -> Result<(), Report> {
1006 ///     get_super_error()
1007 ///         .map_err(Report::from)
1008 ///         .map_err(|r| r.pretty(true).show_backtrace(true))?;
1009 ///     Ok(())
1010 /// }
1011 /// ```
1012 ///
1013 /// This example produces the following output:
1014 ///
1015 /// ```console
1016 /// Error: SuperError is here!
1017 ///
1018 /// Caused by:
1019 ///       SuperErrorSideKick is here!
1020 /// ```
1021 #[unstable(feature = "error_reporter", issue = "90172")]
1022 pub struct Report<E = Box<dyn Error>> {
1023     /// The error being reported.
1024     error: E,
1025     /// Whether a backtrace should be included as part of the report.
1026     show_backtrace: bool,
1027     /// Whether the report should be pretty-printed.
1028     pretty: bool,
1029 }
1030
1031 impl<E> Report<E>
1032 where
1033     Report<E>: From<E>,
1034 {
1035     /// Create a new `Report` from an input error.
1036     #[unstable(feature = "error_reporter", issue = "90172")]
1037     pub fn new(error: E) -> Report<E> {
1038         Self::from(error)
1039     }
1040 }
1041
1042 impl<E> Report<E> {
1043     /// Enable pretty-printing the report across multiple lines.
1044     ///
1045     /// # Examples
1046     ///
1047     /// ```rust
1048     /// #![feature(error_reporter)]
1049     /// use std::error::Report;
1050     /// # use std::error::Error;
1051     /// # use std::fmt;
1052     /// # #[derive(Debug)]
1053     /// # struct SuperError {
1054     /// #     source: SuperErrorSideKick,
1055     /// # }
1056     /// # impl fmt::Display for SuperError {
1057     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1058     /// #         write!(f, "SuperError is here!")
1059     /// #     }
1060     /// # }
1061     /// # impl Error for SuperError {
1062     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1063     /// #         Some(&self.source)
1064     /// #     }
1065     /// # }
1066     /// # #[derive(Debug)]
1067     /// # struct SuperErrorSideKick;
1068     /// # impl fmt::Display for SuperErrorSideKick {
1069     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1070     /// #         write!(f, "SuperErrorSideKick is here!")
1071     /// #     }
1072     /// # }
1073     /// # impl Error for SuperErrorSideKick {}
1074     ///
1075     /// let error = SuperError { source: SuperErrorSideKick };
1076     /// let report = Report::new(error).pretty(true);
1077     /// eprintln!("Error: {:?}", report);
1078     /// ```
1079     ///
1080     /// This example produces the following output:
1081     ///
1082     /// ```console
1083     /// Error: SuperError is here!
1084     ///
1085     /// Caused by:
1086     ///       SuperErrorSideKick is here!
1087     /// ```
1088     ///
1089     /// When there are multiple source errors the causes will be numbered in order of iteration
1090     /// starting from the outermost error.
1091     ///
1092     /// ```rust
1093     /// #![feature(error_reporter)]
1094     /// use std::error::Report;
1095     /// # use std::error::Error;
1096     /// # use std::fmt;
1097     /// # #[derive(Debug)]
1098     /// # struct SuperError {
1099     /// #     source: SuperErrorSideKick,
1100     /// # }
1101     /// # impl fmt::Display for SuperError {
1102     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103     /// #         write!(f, "SuperError is here!")
1104     /// #     }
1105     /// # }
1106     /// # impl Error for SuperError {
1107     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1108     /// #         Some(&self.source)
1109     /// #     }
1110     /// # }
1111     /// # #[derive(Debug)]
1112     /// # struct SuperErrorSideKick {
1113     /// #     source: SuperErrorSideKickSideKick,
1114     /// # }
1115     /// # impl fmt::Display for SuperErrorSideKick {
1116     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117     /// #         write!(f, "SuperErrorSideKick is here!")
1118     /// #     }
1119     /// # }
1120     /// # impl Error for SuperErrorSideKick {
1121     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1122     /// #         Some(&self.source)
1123     /// #     }
1124     /// # }
1125     /// # #[derive(Debug)]
1126     /// # struct SuperErrorSideKickSideKick;
1127     /// # impl fmt::Display for SuperErrorSideKickSideKick {
1128     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1129     /// #         write!(f, "SuperErrorSideKickSideKick is here!")
1130     /// #     }
1131     /// # }
1132     /// # impl Error for SuperErrorSideKickSideKick { }
1133     ///
1134     /// let source = SuperErrorSideKickSideKick;
1135     /// let source = SuperErrorSideKick { source };
1136     /// let error = SuperError { source };
1137     /// let report = Report::new(error).pretty(true);
1138     /// eprintln!("Error: {:?}", report);
1139     /// ```
1140     ///
1141     /// This example produces the following output:
1142     ///
1143     /// ```console
1144     /// Error: SuperError is here!
1145     ///
1146     /// Caused by:
1147     ///    0: SuperErrorSideKick is here!
1148     ///    1: SuperErrorSideKickSideKick is here!
1149     /// ```
1150     #[unstable(feature = "error_reporter", issue = "90172")]
1151     pub fn pretty(mut self, pretty: bool) -> Self {
1152         self.pretty = pretty;
1153         self
1154     }
1155
1156     /// Display backtrace if available when using pretty output format.
1157     ///
1158     /// # Examples
1159     ///
1160     /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1161     /// outermost error. In this example it will display the backtrace from the second error in the
1162     /// chain, `SuperErrorSideKick`.
1163     ///
1164     /// ```rust
1165     /// #![feature(error_reporter)]
1166     /// #![feature(backtrace)]
1167     /// # use std::error::Error;
1168     /// # use std::fmt;
1169     /// use std::error::Report;
1170     /// use std::backtrace::Backtrace;
1171     ///
1172     /// # #[derive(Debug)]
1173     /// # struct SuperError {
1174     /// #     source: SuperErrorSideKick,
1175     /// # }
1176     /// # impl fmt::Display for SuperError {
1177     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1178     /// #         write!(f, "SuperError is here!")
1179     /// #     }
1180     /// # }
1181     /// # impl Error for SuperError {
1182     /// #     fn source(&self) -> Option<&(dyn Error + 'static)> {
1183     /// #         Some(&self.source)
1184     /// #     }
1185     /// # }
1186     /// #[derive(Debug)]
1187     /// struct SuperErrorSideKick {
1188     ///     backtrace: Backtrace,
1189     /// }
1190     ///
1191     /// impl SuperErrorSideKick {
1192     ///     fn new() -> SuperErrorSideKick {
1193     ///         SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1194     ///     }
1195     /// }
1196     ///
1197     /// impl Error for SuperErrorSideKick {
1198     ///     fn backtrace(&self) -> Option<&Backtrace> {
1199     ///         Some(&self.backtrace)
1200     ///     }
1201     /// }
1202     ///
1203     /// // The rest of the example is unchanged ...
1204     /// # impl fmt::Display for SuperErrorSideKick {
1205     /// #     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206     /// #         write!(f, "SuperErrorSideKick is here!")
1207     /// #     }
1208     /// # }
1209     ///
1210     /// let source = SuperErrorSideKick::new();
1211     /// let error = SuperError { source };
1212     /// let report = Report::new(error).pretty(true).show_backtrace(true);
1213     /// eprintln!("Error: {:?}", report);
1214     /// ```
1215     ///
1216     /// This example produces something similar to the following output:
1217     ///
1218     /// ```console
1219     /// Error: SuperError is here!
1220     ///
1221     /// Caused by:
1222     ///       SuperErrorSideKick is here!
1223     ///
1224     /// Stack backtrace:
1225     ///    0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1226     ///    1: rust_out::main::_doctest_main_src_error_rs_1158_0
1227     ///    2: rust_out::main
1228     ///    3: core::ops::function::FnOnce::call_once
1229     ///    4: std::sys_common::backtrace::__rust_begin_short_backtrace
1230     ///    5: std::rt::lang_start::{{closure}}
1231     ///    6: std::panicking::try
1232     ///    7: std::rt::lang_start_internal
1233     ///    8: std::rt::lang_start
1234     ///    9: main
1235     ///   10: __libc_start_main
1236     ///   11: _start
1237     /// ```
1238     #[unstable(feature = "error_reporter", issue = "90172")]
1239     pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1240         self.show_backtrace = show_backtrace;
1241         self
1242     }
1243 }
1244
1245 impl<E> Report<E>
1246 where
1247     E: Error,
1248 {
1249     fn backtrace(&self) -> Option<&Backtrace> {
1250         // have to grab the backtrace on the first error directly since that error may not be
1251         // 'static
1252         let backtrace = self.error.backtrace();
1253         let backtrace = backtrace.or_else(|| {
1254             self.error
1255                 .source()
1256                 .map(|source| source.chain().find_map(|source| source.backtrace()))
1257                 .flatten()
1258         });
1259         backtrace
1260     }
1261
1262     /// Format the report as a single line.
1263     #[unstable(feature = "error_reporter", issue = "90172")]
1264     fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1265         write!(f, "{}", self.error)?;
1266
1267         let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1268
1269         for cause in sources {
1270             write!(f, ": {}", cause)?;
1271         }
1272
1273         Ok(())
1274     }
1275
1276     /// Format the report as multiple lines, with each error cause on its own line.
1277     #[unstable(feature = "error_reporter", issue = "90172")]
1278     fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1279         let error = &self.error;
1280
1281         write!(f, "{}", error)?;
1282
1283         if let Some(cause) = error.source() {
1284             write!(f, "\n\nCaused by:")?;
1285
1286             let multiple = cause.source().is_some();
1287
1288             for (ind, error) in cause.chain().enumerate() {
1289                 writeln!(f)?;
1290                 let mut indented = Indented { inner: f };
1291                 if multiple {
1292                     write!(indented, "{: >4}: {}", ind, error)?;
1293                 } else {
1294                     write!(indented, "      {}", error)?;
1295                 }
1296             }
1297         }
1298
1299         if self.show_backtrace {
1300             let backtrace = self.backtrace();
1301
1302             if let Some(backtrace) = backtrace {
1303                 let backtrace = backtrace.to_string();
1304
1305                 f.write_str("\n\nStack backtrace:\n")?;
1306                 f.write_str(backtrace.trim_end())?;
1307             }
1308         }
1309
1310         Ok(())
1311     }
1312 }
1313
1314 impl Report<Box<dyn Error>> {
1315     fn backtrace(&self) -> Option<&Backtrace> {
1316         // have to grab the backtrace on the first error directly since that error may not be
1317         // 'static
1318         let backtrace = self.error.backtrace();
1319         let backtrace = backtrace.or_else(|| {
1320             self.error
1321                 .source()
1322                 .map(|source| source.chain().find_map(|source| source.backtrace()))
1323                 .flatten()
1324         });
1325         backtrace
1326     }
1327
1328     /// Format the report as a single line.
1329     #[unstable(feature = "error_reporter", issue = "90172")]
1330     fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1331         write!(f, "{}", self.error)?;
1332
1333         let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1334
1335         for cause in sources {
1336             write!(f, ": {}", cause)?;
1337         }
1338
1339         Ok(())
1340     }
1341
1342     /// Format the report as multiple lines, with each error cause on its own line.
1343     #[unstable(feature = "error_reporter", issue = "90172")]
1344     fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345         let error = &self.error;
1346
1347         write!(f, "{}", error)?;
1348
1349         if let Some(cause) = error.source() {
1350             write!(f, "\n\nCaused by:")?;
1351
1352             let multiple = cause.source().is_some();
1353
1354             for (ind, error) in cause.chain().enumerate() {
1355                 writeln!(f)?;
1356                 let mut indented = Indented { inner: f };
1357                 if multiple {
1358                     write!(indented, "{: >4}: {}", ind, error)?;
1359                 } else {
1360                     write!(indented, "      {}", error)?;
1361                 }
1362             }
1363         }
1364
1365         if self.show_backtrace {
1366             let backtrace = self.backtrace();
1367
1368             if let Some(backtrace) = backtrace {
1369                 let backtrace = backtrace.to_string();
1370
1371                 f.write_str("\n\nStack backtrace:\n")?;
1372                 f.write_str(backtrace.trim_end())?;
1373             }
1374         }
1375
1376         Ok(())
1377     }
1378 }
1379
1380 #[unstable(feature = "error_reporter", issue = "90172")]
1381 impl<E> From<E> for Report<E>
1382 where
1383     E: Error,
1384 {
1385     fn from(error: E) -> Self {
1386         Report { error, show_backtrace: false, pretty: false }
1387     }
1388 }
1389
1390 #[unstable(feature = "error_reporter", issue = "90172")]
1391 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1392 where
1393     E: Error + 'a,
1394 {
1395     fn from(error: E) -> Self {
1396         let error = box error;
1397         Report { error, show_backtrace: false, pretty: false }
1398     }
1399 }
1400
1401 #[unstable(feature = "error_reporter", issue = "90172")]
1402 impl<E> fmt::Display for Report<E>
1403 where
1404     E: Error,
1405 {
1406     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1407         if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1408     }
1409 }
1410
1411 #[unstable(feature = "error_reporter", issue = "90172")]
1412 impl fmt::Display for Report<Box<dyn Error>> {
1413     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1414         if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1415     }
1416 }
1417
1418 // This type intentionally outputs the same format for `Display` and `Debug`for
1419 // situations where you unwrap a `Report` or return it from main.
1420 #[unstable(feature = "error_reporter", issue = "90172")]
1421 impl<E> fmt::Debug for Report<E>
1422 where
1423     Report<E>: fmt::Display,
1424 {
1425     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1426         fmt::Display::fmt(self, f)
1427     }
1428 }
1429
1430 /// Wrapper type for indenting the inner source.
1431 struct Indented<'a, D> {
1432     inner: &'a mut D,
1433 }
1434
1435 impl<T> Write for Indented<'_, T>
1436 where
1437     T: Write,
1438 {
1439     fn write_str(&mut self, s: &str) -> fmt::Result {
1440         for (i, line) in s.split('\n').enumerate() {
1441             if i > 0 {
1442                 self.inner.write_char('\n')?;
1443                 self.inner.write_str("      ")?;
1444             }
1445
1446             self.inner.write_str(line)?;
1447         }
1448
1449         Ok(())
1450     }
1451 }