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