]> git.lizzy.rs Git - rust.git/blob - src/libstd/error.rs
Auto merge of #61253 - nnethercote:avoid-hygiene_data-lookups, r=petrochenkov
[rust.git] / src / libstd / error.rs
1 //! Traits for working with Errors.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 // A note about crates and the facade:
6 //
7 // Originally, the `Error` trait was defined in libcore, and the impls
8 // were scattered about. However, coherence objected to this
9 // arrangement, because to create the blanket impls for `Box` required
10 // knowing that `&str: !Error`, and we have no means to deal with that
11 // sort of conflict just now. Therefore, for the time being, we have
12 // moved the `Error` trait into libstd. As we evolve a sol'n to the
13 // coherence challenge (e.g., specialization, neg impls, etc) we can
14 // reconsider what crate these items belong in.
15
16 use core::array;
17
18 use crate::alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
19 use crate::any::TypeId;
20 use crate::borrow::Cow;
21 use crate::cell;
22 use crate::char;
23 use crate::fmt::{self, Debug, Display};
24 use crate::mem::transmute;
25 use crate::num;
26 use crate::str;
27 use crate::string;
28
29 /// `Error` is a trait representing the basic expectations for error values,
30 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
31 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
32 /// cause chain information:
33 ///
34 /// The [`source`] method is generally used when errors cross "abstraction
35 /// boundaries". If one module must report an error that is caused by an error
36 /// from a lower-level module, it can allow access to that error via the
37 /// [`source`] method. This makes it possible for the high-level module to
38 /// provide its own errors while also revealing some of the implementation for
39 /// debugging via [`source`] chains.
40 ///
41 /// [`Result<T, E>`]: ../result/enum.Result.html
42 /// [`Display`]: ../fmt/trait.Display.html
43 /// [`Debug`]: ../fmt/trait.Debug.html
44 /// [`source`]: trait.Error.html#method.source
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait Error: Debug + Display {
47     /// **This method is soft-deprecated.**
48     ///
49     /// Although using it won’t cause compilation warning,
50     /// new code should use [`Display`] instead
51     /// and new `impl`s can omit it.
52     ///
53     /// To obtain error description as a string, use `to_string()`.
54     ///
55     /// [`Display`]: ../fmt/trait.Display.html
56     ///
57     /// # Examples
58     ///
59     /// ```
60     /// match "xc".parse::<u32>() {
61     ///     Err(e) => {
62     ///         // Print `e` itself, not `e.description()`.
63     ///         println!("Error: {}", e);
64     ///     }
65     ///     _ => println!("No error"),
66     /// }
67     /// ```
68     #[stable(feature = "rust1", since = "1.0.0")]
69     fn description(&self) -> &str {
70         "description() is deprecated; use Display"
71     }
72
73     /// The lower-level cause of this error, if any.
74     ///
75     /// # Examples
76     ///
77     /// ```
78     /// use std::error::Error;
79     /// use std::fmt;
80     ///
81     /// #[derive(Debug)]
82     /// struct SuperError {
83     ///     side: SuperErrorSideKick,
84     /// }
85     ///
86     /// impl fmt::Display for SuperError {
87     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88     ///         write!(f, "SuperError is here!")
89     ///     }
90     /// }
91     ///
92     /// impl Error for SuperError {
93     ///     fn description(&self) -> &str {
94     ///         "I'm the superhero of errors"
95     ///     }
96     ///
97     ///     fn cause(&self) -> Option<&dyn Error> {
98     ///         Some(&self.side)
99     ///     }
100     /// }
101     ///
102     /// #[derive(Debug)]
103     /// struct SuperErrorSideKick;
104     ///
105     /// impl fmt::Display for SuperErrorSideKick {
106     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107     ///         write!(f, "SuperErrorSideKick is here!")
108     ///     }
109     /// }
110     ///
111     /// impl Error for SuperErrorSideKick {
112     ///     fn description(&self) -> &str {
113     ///         "I'm SuperError side kick"
114     ///     }
115     /// }
116     ///
117     /// fn get_super_error() -> Result<(), SuperError> {
118     ///     Err(SuperError { side: SuperErrorSideKick })
119     /// }
120     ///
121     /// fn main() {
122     ///     match get_super_error() {
123     ///         Err(e) => {
124     ///             println!("Error: {}", e.description());
125     ///             println!("Caused by: {}", e.cause().unwrap());
126     ///         }
127     ///         _ => println!("No error"),
128     ///     }
129     /// }
130     /// ```
131     #[stable(feature = "rust1", since = "1.0.0")]
132     #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
133                                                    downcasting")]
134     fn cause(&self) -> Option<&dyn Error> {
135         self.source()
136     }
137
138     /// The lower-level source of this error, if any.
139     ///
140     /// # Examples
141     ///
142     /// ```
143     /// use std::error::Error;
144     /// use std::fmt;
145     ///
146     /// #[derive(Debug)]
147     /// struct SuperError {
148     ///     side: SuperErrorSideKick,
149     /// }
150     ///
151     /// impl fmt::Display for SuperError {
152     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153     ///         write!(f, "SuperError is here!")
154     ///     }
155     /// }
156     ///
157     /// impl Error for SuperError {
158     ///     fn description(&self) -> &str {
159     ///         "I'm the superhero of errors"
160     ///     }
161     ///
162     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
163     ///         Some(&self.side)
164     ///     }
165     /// }
166     ///
167     /// #[derive(Debug)]
168     /// struct SuperErrorSideKick;
169     ///
170     /// impl fmt::Display for SuperErrorSideKick {
171     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172     ///         write!(f, "SuperErrorSideKick is here!")
173     ///     }
174     /// }
175     ///
176     /// impl Error for SuperErrorSideKick {
177     ///     fn description(&self) -> &str {
178     ///         "I'm SuperError side kick"
179     ///     }
180     /// }
181     ///
182     /// fn get_super_error() -> Result<(), SuperError> {
183     ///     Err(SuperError { side: SuperErrorSideKick })
184     /// }
185     ///
186     /// fn main() {
187     ///     match get_super_error() {
188     ///         Err(e) => {
189     ///             println!("Error: {}", e.description());
190     ///             println!("Caused by: {}", e.source().unwrap());
191     ///         }
192     ///         _ => println!("No error"),
193     ///     }
194     /// }
195     /// ```
196     #[stable(feature = "error_source", since = "1.30.0")]
197     fn source(&self) -> Option<&(dyn Error + 'static)> { None }
198
199     /// Gets the `TypeId` of `self`
200     #[doc(hidden)]
201     #[unstable(feature = "error_type_id",
202                reason = "this is memory unsafe to override in user code",
203                issue = "60784")]
204     fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
205         TypeId::of::<Self>()
206     }
207 }
208
209 mod private {
210     // This is a hack to prevent `type_id` from being overridden by `Error`
211     // implementations, since that can enable unsound downcasting.
212     #[unstable(feature = "error_type_id", issue = "60784")]
213     #[derive(Debug)]
214     pub struct Internal;
215 }
216
217 #[stable(feature = "rust1", since = "1.0.0")]
218 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
219     /// Converts a type of [`Error`] into a box of dyn [`Error`].
220     ///
221     /// [`Error`]: ../error/trait.Error.html
222     ///
223     /// # Examples
224     ///
225     /// ```
226     /// use std::error::Error;
227     /// use std::fmt;
228     /// use std::mem;
229     ///
230     /// #[derive(Debug)]
231     /// struct AnError;
232     ///
233     /// impl fmt::Display for AnError {
234     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235     ///         write!(f , "An error")
236     ///     }
237     /// }
238     ///
239     /// impl Error for AnError {
240     ///     fn description(&self) -> &str {
241     ///         "Description of an error"
242     ///     }
243     /// }
244     ///
245     /// let an_error = AnError;
246     /// assert!(0 == mem::size_of_val(&an_error));
247     /// let a_boxed_error = Box::<dyn Error>::from(an_error);
248     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
249     /// ```
250     fn from(err: E) -> Box<dyn Error + 'a> {
251         Box::new(err)
252     }
253 }
254
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
257     /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
258     /// [`Send`] + [`Sync`].
259     ///
260     /// [`Error`]: ../error/trait.Error.html
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::error::Error;
266     /// use std::fmt;
267     /// use std::mem;
268     ///
269     /// #[derive(Debug)]
270     /// struct AnError;
271     ///
272     /// impl fmt::Display for AnError {
273     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274     ///         write!(f , "An error")
275     ///     }
276     /// }
277     ///
278     /// impl Error for AnError {
279     ///     fn description(&self) -> &str {
280     ///         "Description of an error"
281     ///     }
282     /// }
283     ///
284     /// unsafe impl Send for AnError {}
285     ///
286     /// unsafe impl Sync for AnError {}
287     ///
288     /// let an_error = AnError;
289     /// assert!(0 == mem::size_of_val(&an_error));
290     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
291     /// assert!(
292     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
293     /// ```
294     fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
295         Box::new(err)
296     }
297 }
298
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl From<String> for Box<dyn Error + Send + Sync> {
301     /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
302     ///
303     /// [`Error`]: ../error/trait.Error.html
304     ///
305     /// # Examples
306     ///
307     /// ```
308     /// use std::error::Error;
309     /// use std::mem;
310     ///
311     /// let a_string_error = "a string error".to_string();
312     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
313     /// assert!(
314     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
315     /// ```
316     fn from(err: String) -> Box<dyn Error + Send + Sync> {
317         #[derive(Debug)]
318         struct StringError(String);
319
320         impl Error for StringError {
321             fn description(&self) -> &str { &self.0 }
322         }
323
324         impl Display for StringError {
325             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326                 Display::fmt(&self.0, f)
327             }
328         }
329
330         Box::new(StringError(err))
331     }
332 }
333
334 #[stable(feature = "string_box_error", since = "1.6.0")]
335 impl From<String> for Box<dyn Error> {
336     /// Converts a [`String`] into a box of dyn [`Error`].
337     ///
338     /// [`Error`]: ../error/trait.Error.html
339     ///
340     /// # Examples
341     ///
342     /// ```
343     /// use std::error::Error;
344     /// use std::mem;
345     ///
346     /// let a_string_error = "a string error".to_string();
347     /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
348     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
349     /// ```
350     fn from(str_err: String) -> Box<dyn Error> {
351         let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
352         let err2: Box<dyn Error> = err1;
353         err2
354     }
355 }
356
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
359     /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
360     ///
361     /// [`Error`]: ../error/trait.Error.html
362     ///
363     /// # Examples
364     ///
365     /// ```
366     /// use std::error::Error;
367     /// use std::mem;
368     ///
369     /// let a_str_error = "a str error";
370     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
371     /// assert!(
372     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
373     /// ```
374     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
375         From::from(String::from(err))
376     }
377 }
378
379 #[stable(feature = "string_box_error", since = "1.6.0")]
380 impl From<&str> for Box<dyn Error> {
381     /// Converts a [`str`] into a box of dyn [`Error`].
382     ///
383     /// [`Error`]: ../error/trait.Error.html
384     ///
385     /// # Examples
386     ///
387     /// ```
388     /// use std::error::Error;
389     /// use std::mem;
390     ///
391     /// let a_str_error = "a str error";
392     /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
393     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
394     /// ```
395     fn from(err: &str) -> Box<dyn Error> {
396         From::from(String::from(err))
397     }
398 }
399
400 #[stable(feature = "cow_box_error", since = "1.22.0")]
401 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
402     /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
403     ///
404     /// [`Cow`]: ../borrow/enum.Cow.html
405     /// [`Error`]: ../error/trait.Error.html
406     ///
407     /// # Examples
408     ///
409     /// ```
410     /// use std::error::Error;
411     /// use std::mem;
412     /// use std::borrow::Cow;
413     ///
414     /// let a_cow_str_error = Cow::from("a str error");
415     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
416     /// assert!(
417     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
418     /// ```
419     fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
420         From::from(String::from(err))
421     }
422 }
423
424 #[stable(feature = "cow_box_error", since = "1.22.0")]
425 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
426     /// Converts a [`Cow`] into a box of dyn [`Error`].
427     ///
428     /// [`Cow`]: ../borrow/enum.Cow.html
429     /// [`Error`]: ../error/trait.Error.html
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// use std::error::Error;
435     /// use std::mem;
436     /// use std::borrow::Cow;
437     ///
438     /// let a_cow_str_error = Cow::from("a str error");
439     /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
440     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
441     /// ```
442     fn from(err: Cow<'a, str>) -> Box<dyn Error> {
443         From::from(String::from(err))
444     }
445 }
446
447 #[unstable(feature = "never_type", issue = "35121")]
448 impl Error for ! {
449     fn description(&self) -> &str { *self }
450 }
451
452 #[unstable(feature = "allocator_api",
453            reason = "the precise API and guarantees it provides may be tweaked.",
454            issue = "32838")]
455 impl Error for AllocErr {
456     fn description(&self) -> &str {
457         "memory allocation failed"
458     }
459 }
460
461 #[unstable(feature = "allocator_api",
462            reason = "the precise API and guarantees it provides may be tweaked.",
463            issue = "32838")]
464 impl Error for LayoutErr {
465     fn description(&self) -> &str {
466         "invalid parameters to Layout::from_size_align"
467     }
468 }
469
470 #[unstable(feature = "allocator_api",
471            reason = "the precise API and guarantees it provides may be tweaked.",
472            issue = "32838")]
473 impl Error for CannotReallocInPlace {
474     fn description(&self) -> &str {
475         CannotReallocInPlace::description(self)
476     }
477 }
478
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl Error for str::ParseBoolError {
481     fn description(&self) -> &str { "failed to parse bool" }
482 }
483
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl Error for str::Utf8Error {
486     fn description(&self) -> &str {
487         "invalid utf-8: corrupt contents"
488     }
489 }
490
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl Error for num::ParseIntError {
493     fn description(&self) -> &str {
494         self.__description()
495     }
496 }
497
498 #[stable(feature = "try_from", since = "1.34.0")]
499 impl Error for num::TryFromIntError {
500     fn description(&self) -> &str {
501         self.__description()
502     }
503 }
504
505 #[stable(feature = "try_from", since = "1.34.0")]
506 impl Error for array::TryFromSliceError {
507     fn description(&self) -> &str {
508         self.__description()
509     }
510 }
511
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Error for num::ParseFloatError {
514     fn description(&self) -> &str {
515         self.__description()
516     }
517 }
518
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl Error for string::FromUtf8Error {
521     fn description(&self) -> &str {
522         "invalid utf-8"
523     }
524 }
525
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl Error for string::FromUtf16Error {
528     fn description(&self) -> &str {
529         "invalid utf-16"
530     }
531 }
532
533 #[stable(feature = "str_parse_error2", since = "1.8.0")]
534 impl Error for string::ParseError {
535     fn description(&self) -> &str {
536         match *self {}
537     }
538 }
539
540 #[stable(feature = "decode_utf16", since = "1.9.0")]
541 impl Error for char::DecodeUtf16Error {
542     fn description(&self) -> &str {
543         "unpaired surrogate found"
544     }
545 }
546
547 #[stable(feature = "box_error", since = "1.8.0")]
548 impl<T: Error> Error for Box<T> {
549     fn description(&self) -> &str {
550         Error::description(&**self)
551     }
552
553     #[allow(deprecated)]
554     fn cause(&self) -> Option<&dyn Error> {
555         Error::cause(&**self)
556     }
557 }
558
559 #[stable(feature = "fmt_error", since = "1.11.0")]
560 impl Error for fmt::Error {
561     fn description(&self) -> &str {
562         "an error occurred when formatting an argument"
563     }
564 }
565
566 #[stable(feature = "try_borrow", since = "1.13.0")]
567 impl Error for cell::BorrowError {
568     fn description(&self) -> &str {
569         "already mutably borrowed"
570     }
571 }
572
573 #[stable(feature = "try_borrow", since = "1.13.0")]
574 impl Error for cell::BorrowMutError {
575     fn description(&self) -> &str {
576         "already borrowed"
577     }
578 }
579
580 #[stable(feature = "try_from", since = "1.34.0")]
581 impl Error for char::CharTryFromError {
582     fn description(&self) -> &str {
583         "converted integer out of range for `char`"
584     }
585 }
586
587 #[stable(feature = "char_from_str", since = "1.20.0")]
588 impl Error for char::ParseCharError {
589     fn description(&self) -> &str {
590         self.__description()
591     }
592 }
593
594 // copied from any.rs
595 impl dyn Error + 'static {
596     /// Returns `true` if the boxed type is the same as `T`
597     #[stable(feature = "error_downcast", since = "1.3.0")]
598     #[inline]
599     pub fn is<T: Error + 'static>(&self) -> bool {
600         // Get TypeId of the type this function is instantiated with
601         let t = TypeId::of::<T>();
602
603         // Get TypeId of the type in the trait object
604         let boxed = self.type_id(private::Internal);
605
606         // Compare both TypeIds on equality
607         t == boxed
608     }
609
610     /// Returns some reference to the boxed value if it is of type `T`, or
611     /// `None` if it isn't.
612     #[stable(feature = "error_downcast", since = "1.3.0")]
613     #[inline]
614     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
615         if self.is::<T>() {
616             unsafe {
617                 Some(&*(self as *const dyn Error as *const T))
618             }
619         } else {
620             None
621         }
622     }
623
624     /// Returns some mutable reference to the boxed value if it is of type `T`, or
625     /// `None` if it isn't.
626     #[stable(feature = "error_downcast", since = "1.3.0")]
627     #[inline]
628     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
629         if self.is::<T>() {
630             unsafe {
631                 Some(&mut *(self as *mut dyn Error as *mut T))
632             }
633         } else {
634             None
635         }
636     }
637 }
638
639 impl dyn Error + 'static + Send {
640     /// Forwards to the method defined on the type `Any`.
641     #[stable(feature = "error_downcast", since = "1.3.0")]
642     #[inline]
643     pub fn is<T: Error + 'static>(&self) -> bool {
644         <dyn Error + 'static>::is::<T>(self)
645     }
646
647     /// Forwards to the method defined on the type `Any`.
648     #[stable(feature = "error_downcast", since = "1.3.0")]
649     #[inline]
650     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
651         <dyn Error + 'static>::downcast_ref::<T>(self)
652     }
653
654     /// Forwards to the method defined on the type `Any`.
655     #[stable(feature = "error_downcast", since = "1.3.0")]
656     #[inline]
657     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
658         <dyn Error + 'static>::downcast_mut::<T>(self)
659     }
660 }
661
662 impl dyn Error + 'static + Send + Sync {
663     /// Forwards to the method defined on the type `Any`.
664     #[stable(feature = "error_downcast", since = "1.3.0")]
665     #[inline]
666     pub fn is<T: Error + 'static>(&self) -> bool {
667         <dyn Error + 'static>::is::<T>(self)
668     }
669
670     /// Forwards to the method defined on the type `Any`.
671     #[stable(feature = "error_downcast", since = "1.3.0")]
672     #[inline]
673     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
674         <dyn Error + 'static>::downcast_ref::<T>(self)
675     }
676
677     /// Forwards to the method defined on the type `Any`.
678     #[stable(feature = "error_downcast", since = "1.3.0")]
679     #[inline]
680     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
681         <dyn Error + 'static>::downcast_mut::<T>(self)
682     }
683 }
684
685 impl dyn Error {
686     #[inline]
687     #[stable(feature = "error_downcast", since = "1.3.0")]
688     /// Attempt to downcast the box to a concrete type.
689     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
690         if self.is::<T>() {
691             unsafe {
692                 let raw: *mut dyn Error = Box::into_raw(self);
693                 Ok(Box::from_raw(raw as *mut T))
694             }
695         } else {
696             Err(self)
697         }
698     }
699
700     /// Returns an iterator starting with the current error and continuing with
701     /// recursively calling [`source`].
702     ///
703     /// # Examples
704     ///
705     /// ```
706     /// #![feature(error_iter)]
707     /// use std::error::Error;
708     /// use std::fmt;
709     ///
710     /// #[derive(Debug)]
711     /// struct A;
712     ///
713     /// #[derive(Debug)]
714     /// struct B(Option<Box<dyn Error + 'static>>);
715     ///
716     /// impl fmt::Display for A {
717     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718     ///         write!(f, "A")
719     ///     }
720     /// }
721     ///
722     /// impl fmt::Display for B {
723     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724     ///         write!(f, "B")
725     ///     }
726     /// }
727     ///
728     /// impl Error for A {}
729     ///
730     /// impl Error for B {
731     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
732     ///         self.0.as_ref().map(|e| e.as_ref())
733     ///     }
734     /// }
735     ///
736     /// let b = B(Some(Box::new(A)));
737     ///
738     /// // let err : Box<Error> = b.into(); // or
739     /// let err = &b as &(dyn Error);
740     ///
741     /// let mut iter = err.iter_chain();
742     ///
743     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
744     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
745     /// assert!(iter.next().is_none());
746     /// assert!(iter.next().is_none());
747     /// ```
748     ///
749     /// [`source`]: trait.Error.html#method.source
750     #[unstable(feature = "error_iter", issue = "58520")]
751     #[inline]
752     pub fn iter_chain(&self) -> ErrorIter<'_> {
753         ErrorIter {
754             current: Some(self),
755         }
756     }
757
758     /// Returns an iterator starting with the [`source`] of this error
759     /// and continuing with recursively calling [`source`].
760     ///
761     /// # Examples
762     ///
763     /// ```
764     /// #![feature(error_iter)]
765     /// use std::error::Error;
766     /// use std::fmt;
767     ///
768     /// #[derive(Debug)]
769     /// struct A;
770     ///
771     /// #[derive(Debug)]
772     /// struct B(Option<Box<dyn Error + 'static>>);
773     ///
774     /// #[derive(Debug)]
775     /// struct C(Option<Box<dyn Error + 'static>>);
776     ///
777     /// impl fmt::Display for A {
778     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779     ///         write!(f, "A")
780     ///     }
781     /// }
782     ///
783     /// impl fmt::Display for B {
784     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785     ///         write!(f, "B")
786     ///     }
787     /// }
788     ///
789     /// impl fmt::Display for C {
790     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791     ///         write!(f, "C")
792     ///     }
793     /// }
794     ///
795     /// impl Error for A {}
796     ///
797     /// impl Error for B {
798     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
799     ///         self.0.as_ref().map(|e| e.as_ref())
800     ///     }
801     /// }
802     ///
803     /// impl Error for C {
804     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
805     ///         self.0.as_ref().map(|e| e.as_ref())
806     ///     }
807     /// }
808     ///
809     /// let b = B(Some(Box::new(A)));
810     /// let c = C(Some(Box::new(b)));
811     ///
812     /// // let err : Box<Error> = c.into(); // or
813     /// let err = &c as &(dyn Error);
814     ///
815     /// let mut iter = err.iter_sources();
816     ///
817     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
818     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
819     /// assert!(iter.next().is_none());
820     /// assert!(iter.next().is_none());
821     /// ```
822     ///
823     /// [`source`]: trait.Error.html#method.source
824     #[inline]
825     #[unstable(feature = "error_iter", issue = "58520")]
826     pub fn iter_sources(&self) -> ErrorIter<'_> {
827         ErrorIter {
828             current: self.source(),
829         }
830     }
831 }
832
833 /// An iterator over [`Error`]
834 ///
835 /// [`Error`]: trait.Error.html
836 #[unstable(feature = "error_iter", issue = "58520")]
837 #[derive(Copy, Clone, Debug)]
838 pub struct ErrorIter<'a> {
839     current: Option<&'a (dyn Error + 'static)>,
840 }
841
842 #[unstable(feature = "error_iter", issue = "58520")]
843 impl<'a> Iterator for ErrorIter<'a> {
844     type Item = &'a (dyn Error + 'static);
845
846     fn next(&mut self) -> Option<Self::Item> {
847         let current = self.current;
848         self.current = self.current.and_then(Error::source);
849         current
850     }
851 }
852
853 impl dyn Error + Send {
854     #[inline]
855     #[stable(feature = "error_downcast", since = "1.3.0")]
856     /// Attempt to downcast the box to a concrete type.
857     pub fn downcast<T: Error + 'static>(self: Box<Self>)
858                                         -> Result<Box<T>, Box<dyn Error + Send>> {
859         let err: Box<dyn Error> = self;
860         <dyn Error>::downcast(err).map_err(|s| unsafe {
861             // reapply the Send marker
862             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
863         })
864     }
865 }
866
867 impl dyn Error + Send + Sync {
868     #[inline]
869     #[stable(feature = "error_downcast", since = "1.3.0")]
870     /// Attempt to downcast the box to a concrete type.
871     pub fn downcast<T: Error + 'static>(self: Box<Self>)
872                                         -> Result<Box<T>, Box<Self>> {
873         let err: Box<dyn Error> = self;
874         <dyn Error>::downcast(err).map_err(|s| unsafe {
875             // reapply the Send+Sync marker
876             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
877         })
878     }
879 }
880
881 #[cfg(test)]
882 mod tests {
883     use super::Error;
884     use crate::fmt;
885
886     #[derive(Debug, PartialEq)]
887     struct A;
888     #[derive(Debug, PartialEq)]
889     struct B;
890
891     impl fmt::Display for A {
892         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893             write!(f, "A")
894         }
895     }
896     impl fmt::Display for B {
897         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898             write!(f, "B")
899         }
900     }
901
902     impl Error for A {
903         fn description(&self) -> &str { "A-desc" }
904     }
905     impl Error for B {
906         fn description(&self) -> &str { "A-desc" }
907     }
908
909     #[test]
910     fn downcasting() {
911         let mut a = A;
912         let a = &mut a as &mut (dyn Error + 'static);
913         assert_eq!(a.downcast_ref::<A>(), Some(&A));
914         assert_eq!(a.downcast_ref::<B>(), None);
915         assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
916         assert_eq!(a.downcast_mut::<B>(), None);
917
918         let a: Box<dyn Error> = Box::new(A);
919         match a.downcast::<B>() {
920             Ok(..) => panic!("expected error"),
921             Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),
922         }
923     }
924 }