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