]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/error.rs
Auto merge of #68522 - estebank:impl-trait-sugg-2, r=oli-obk
[rust.git] / src / libstd / error.rs
index f62c05c4441150985f3195fa90225cb7ecdee359..b480581e21ba90c093664699ae88974dd8dd9bef 100644 (file)
@@ -15,7 +15,7 @@
 
 use core::array;
 
-use crate::alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
+use crate::alloc::{AllocErr, CannotReallocInPlace, LayoutErr};
 use crate::any::TypeId;
 use crate::backtrace::Backtrace;
 use crate::borrow::Cow;
 /// [`source`]: trait.Error.html#method.source
 #[stable(feature = "rust1", since = "1.0.0")]
 pub trait Error: Debug + Display {
-    /// **This method is soft-deprecated.**
-    ///
-    /// Although using it won’t cause compilation warning,
-    /// new code should use [`Display`] instead
-    /// and new `impl`s can omit it.
-    ///
-    /// To obtain error description as a string, use `to_string()`.
-    ///
-    /// [`Display`]: ../fmt/trait.Display.html
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// match "xc".parse::<u32>() {
-    ///     Err(e) => {
-    ///         // Print `e` itself, not `e.description()`.
-    ///         println!("Error: {}", e);
-    ///     }
-    ///     _ => println!("No error"),
-    /// }
-    /// ```
-    #[stable(feature = "rust1", since = "1.0.0")]
-    fn description(&self) -> &str {
-        "description() is deprecated; use Display"
-    }
-
-    /// The lower-level cause of this error, if any.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// use std::error::Error;
-    /// use std::fmt;
-    ///
-    /// #[derive(Debug)]
-    /// struct SuperError {
-    ///     side: SuperErrorSideKick,
-    /// }
-    ///
-    /// impl fmt::Display for SuperError {
-    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-    ///         write!(f, "SuperError is here!")
-    ///     }
-    /// }
-    ///
-    /// impl Error for SuperError {
-    ///     fn cause(&self) -> Option<&dyn Error> {
-    ///         Some(&self.side)
-    ///     }
-    /// }
-    ///
-    /// #[derive(Debug)]
-    /// struct SuperErrorSideKick;
-    ///
-    /// impl fmt::Display for SuperErrorSideKick {
-    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-    ///         write!(f, "SuperErrorSideKick is here!")
-    ///     }
-    /// }
-    ///
-    /// impl Error for SuperErrorSideKick {}
-    ///
-    /// fn get_super_error() -> Result<(), SuperError> {
-    ///     Err(SuperError { side: SuperErrorSideKick })
-    /// }
-    ///
-    /// fn main() {
-    ///     match get_super_error() {
-    ///         Err(e) => {
-    ///             println!("Error: {}", e.description());
-    ///             println!("Caused by: {}", e.cause().unwrap());
-    ///         }
-    ///         _ => println!("No error"),
-    ///     }
-    /// }
-    /// ```
-    #[stable(feature = "rust1", since = "1.0.0")]
-    #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
-                                                   downcasting")]
-    fn cause(&self) -> Option<&dyn Error> {
-        self.source()
-    }
-
     /// The lower-level source of this error, if any.
     ///
     /// # Examples
@@ -179,14 +96,21 @@ fn cause(&self) -> Option<&dyn Error> {
     /// }
     /// ```
     #[stable(feature = "error_source", since = "1.30.0")]
-    fn source(&self) -> Option<&(dyn Error + 'static)> { None }
+    fn source(&self) -> Option<&(dyn Error + 'static)> {
+        None
+    }
 
     /// Gets the `TypeId` of `self`.
     #[doc(hidden)]
-    #[unstable(feature = "error_type_id",
-               reason = "this is memory-unsafe to override in user code",
-               issue = "60784")]
-    fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
+    #[unstable(
+        feature = "error_type_id",
+        reason = "this is memory-unsafe to override in user code",
+        issue = "60784"
+    )]
+    fn type_id(&self, _: private::Internal) -> TypeId
+    where
+        Self: 'static,
+    {
         TypeId::of::<Self>()
     }
 
@@ -203,6 +127,28 @@ fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
     fn backtrace(&self) -> Option<&Backtrace> {
         None
     }
+
+    /// ```
+    /// if let Err(e) = "xc".parse::<u32>() {
+    ///     // Print `e` itself, no need for description().
+    ///     eprintln!("Error: {}", e);
+    /// }
+    /// ```
+    #[stable(feature = "rust1", since = "1.0.0")]
+    #[rustc_deprecated(since = "1.41.0", reason = "use the Display impl or to_string()")]
+    fn description(&self) -> &str {
+        "description() is deprecated; use Display"
+    }
+
+    #[stable(feature = "rust1", since = "1.0.0")]
+    #[rustc_deprecated(
+        since = "1.33.0",
+        reason = "replaced by Error::source, which can support downcasting"
+    )]
+    #[allow(missing_docs)]
+    fn cause(&self) -> Option<&dyn Error> {
+        self.source()
+    }
 }
 
 mod private {
@@ -304,11 +250,15 @@ impl From<String> for Box<dyn Error + Send + Sync> {
     /// assert!(
     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
     /// ```
+    #[inline]
     fn from(err: String) -> Box<dyn Error + Send + Sync> {
         struct StringError(String);
 
         impl Error for StringError {
-            fn description(&self) -> &str { &self.0 }
+            #[allow(deprecated)]
+            fn description(&self) -> &str {
+                &self.0
+            }
         }
 
         impl Display for StringError {
@@ -368,6 +318,7 @@ impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
     /// assert!(
     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
     /// ```
+    #[inline]
     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
         From::from(String::from(err))
     }
@@ -442,44 +393,40 @@ fn from(err: Cow<'a, str>) -> Box<dyn Error> {
 }
 
 #[unstable(feature = "never_type", issue = "35121")]
-impl Error for ! {
-    fn description(&self) -> &str { *self }
-}
-
-#[unstable(feature = "allocator_api",
-           reason = "the precise API and guarantees it provides may be tweaked.",
-           issue = "32838")]
-impl Error for AllocErr {
-    fn description(&self) -> &str {
-        "memory allocation failed"
-    }
-}
-
-#[unstable(feature = "allocator_api",
-           reason = "the precise API and guarantees it provides may be tweaked.",
-           issue = "32838")]
-impl Error for LayoutErr {
-    fn description(&self) -> &str {
-        "invalid parameters to Layout::from_size_align"
-    }
-}
-
-#[unstable(feature = "allocator_api",
-           reason = "the precise API and guarantees it provides may be tweaked.",
-           issue = "32838")]
-impl Error for CannotReallocInPlace {
-    fn description(&self) -> &str {
-        CannotReallocInPlace::description(self)
-    }
-}
+impl Error for ! {}
+
+#[unstable(
+    feature = "allocator_api",
+    reason = "the precise API and guarantees it provides may be tweaked.",
+    issue = "32838"
+)]
+impl Error for AllocErr {}
+
+#[unstable(
+    feature = "allocator_api",
+    reason = "the precise API and guarantees it provides may be tweaked.",
+    issue = "32838"
+)]
+impl Error for LayoutErr {}
+
+#[unstable(
+    feature = "allocator_api",
+    reason = "the precise API and guarantees it provides may be tweaked.",
+    issue = "32838"
+)]
+impl Error for CannotReallocInPlace {}
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for str::ParseBoolError {
-    fn description(&self) -> &str { "failed to parse bool" }
+    #[allow(deprecated)]
+    fn description(&self) -> &str {
+        "failed to parse bool"
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for str::Utf8Error {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "invalid utf-8: corrupt contents"
     }
@@ -487,6 +434,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for num::ParseIntError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         self.__description()
     }
@@ -494,6 +442,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "try_from", since = "1.34.0")]
 impl Error for num::TryFromIntError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         self.__description()
     }
@@ -501,6 +450,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "try_from", since = "1.34.0")]
 impl Error for array::TryFromSliceError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         self.__description()
     }
@@ -508,6 +458,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for num::ParseFloatError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         self.__description()
     }
@@ -515,6 +466,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for string::FromUtf8Error {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "invalid utf-8"
     }
@@ -522,6 +474,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Error for string::FromUtf16Error {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "invalid utf-16"
     }
@@ -536,6 +489,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "decode_utf16", since = "1.9.0")]
 impl Error for char::DecodeUtf16Error {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "unpaired surrogate found"
     }
@@ -543,6 +497,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "box_error", since = "1.8.0")]
 impl<T: Error> Error for Box<T> {
+    #[allow(deprecated, deprecated_in_future)]
     fn description(&self) -> &str {
         Error::description(&**self)
     }
@@ -559,6 +514,7 @@ fn source(&self) -> Option<&(dyn Error + 'static)> {
 
 #[stable(feature = "fmt_error", since = "1.11.0")]
 impl Error for fmt::Error {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "an error occurred when formatting an argument"
     }
@@ -566,6 +522,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "try_borrow", since = "1.13.0")]
 impl Error for cell::BorrowError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "already mutably borrowed"
     }
@@ -573,6 +530,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "try_borrow", since = "1.13.0")]
 impl Error for cell::BorrowMutError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "already borrowed"
     }
@@ -580,6 +538,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "try_from", since = "1.34.0")]
 impl Error for char::CharTryFromError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         "converted integer out of range for `char`"
     }
@@ -587,6 +546,7 @@ fn description(&self) -> &str {
 
 #[stable(feature = "char_from_str", since = "1.20.0")]
 impl Error for char::ParseCharError {
+    #[allow(deprecated)]
     fn description(&self) -> &str {
         self.__description()
     }
@@ -614,9 +574,7 @@ pub fn is<T: Error + 'static>(&self) -> bool {
     #[inline]
     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
         if self.is::<T>() {
-            unsafe {
-                Some(&*(self as *const dyn Error as *const T))
-            }
+            unsafe { Some(&*(self as *const dyn Error as *const T)) }
         } else {
             None
         }
@@ -628,9 +586,7 @@ pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
     #[inline]
     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
         if self.is::<T>() {
-            unsafe {
-                Some(&mut *(self as *mut dyn Error as *mut T))
-            }
+            unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
         } else {
             None
         }
@@ -754,9 +710,7 @@ pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn E
     #[unstable(feature = "error_iter", issue = "58520")]
     #[inline]
     pub fn chain(&self) -> Chain<'_> {
-        Chain {
-            current: Some(self),
-        }
+        Chain { current: Some(self) }
     }
 }
 
@@ -787,8 +741,7 @@ impl dyn Error + Send {
     #[inline]
     #[stable(feature = "error_downcast", since = "1.3.0")]
     /// Attempts to downcast the box to a concrete type.
-    pub fn downcast<T: Error + 'static>(self: Box<Self>)
-                                        -> Result<Box<T>, Box<dyn Error + Send>> {
+    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
         let err: Box<dyn Error> = self;
         <dyn Error>::downcast(err).map_err(|s| unsafe {
             // Reapply the `Send` marker.
@@ -801,8 +754,7 @@ impl dyn Error + Send + Sync {
     #[inline]
     #[stable(feature = "error_downcast", since = "1.3.0")]
     /// Attempts to downcast the box to a concrete type.
-    pub fn downcast<T: Error + 'static>(self: Box<Self>)
-                                        -> Result<Box<T>, Box<Self>> {
+    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
         let err: Box<dyn Error> = self;
         <dyn Error>::downcast(err).map_err(|s| unsafe {
             // Reapply the `Send + Sync` marker.
@@ -832,12 +784,8 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         }
     }
 
-    impl Error for A {
-        fn description(&self) -> &str { "A-desc" }
-    }
-    impl Error for B {
-        fn description(&self) -> &str { "A-desc" }
-    }
+    impl Error for A {}
+    impl Error for B {}
 
     #[test]
     fn downcasting() {