Skip to content
Myr

error.rs

This file

Path

src/error.rs

1,218 lines · 44.1 KiB · Rust

Last changed by

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

History of this file

Take it

1use crate::backtrace::Backtrace;2use crate::chain::Chain;3#[cfg(error_generic_member_access)]4use crate::nightly::{self, Request};5#[cfg(any(feature = "std", not(anyhow_no_core_error), anyhow_no_ptr_addr_of))]6use crate::ptr::Mut;7use crate::ptr::{Own, Ref};8use crate::{Error, StdError};9use alloc::boxed::Box;10use core::any::TypeId;11use core::fmt::{self, Debug, Display};12use core::mem::ManuallyDrop;13#[cfg(any(feature = "std", not(anyhow_no_core_error)))]14use core::ops::{Deref, DerefMut};15#[cfg(not(anyhow_no_core_unwind_safe))]16use core::panic::{RefUnwindSafe, UnwindSafe};17#[cfg(not(anyhow_no_ptr_addr_of))]18use core::ptr;19use core::ptr::NonNull;20#[cfg(all(feature = "std", anyhow_no_core_unwind_safe))]21use std::panic::{RefUnwindSafe, UnwindSafe};2223impl Error {24    /// Create a new error object from any error type.25    ///26    /// The error type must be threadsafe and `'static`, so that the `Error`27    /// will be as well.28    ///29    /// If the error type does not provide a backtrace, a backtrace will be30    /// created here to ensure that a backtrace exists.31    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]32    #[cold]33    #[must_use]34    pub fn new<E>(error: E) -> Self35    where36        E: StdError + Send + Sync + 'static,37    {38        let backtrace = backtrace_if_absent!(&error);39        Error::construct_from_std(error, backtrace)40    }4142    /// Create a new error object from a printable error message.43    ///44    /// If the argument implements std::error::Error, prefer `Error::new`45    /// instead which preserves the underlying error's cause chain and46    /// backtrace. If the argument may or may not implement std::error::Error47    /// now or in the future, use `anyhow!(err)` which handles either way48    /// correctly.49    ///50    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally51    /// convenient in places where a function is preferable over a macro, such52    /// as iterator or stream combinators:53    ///54    /// ```55    /// # mod ffi {56    /// #     pub struct Input;57    /// #     pub struct Output;58    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {59    /// #         unimplemented!()60    /// #     }61    /// # }62    /// #63    /// # use ffi::{Input, Output};64    /// #65    /// use anyhow::{Error, Result};66    /// use futures::stream::{Stream, StreamExt, TryStreamExt};67    ///68    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>69    /// where70    ///     S: Stream<Item = Input>,71    /// {72    ///     stream73    ///         .then(ffi::do_some_work) // returns Result<Output, &str>74    ///         .map_err(Error::msg)75    ///         .try_collect()76    ///         .await77    /// }78    /// ```79    #[cold]80    #[must_use]81    pub fn msg<M>(message: M) -> Self82    where83        M: Display + Debug + Send + Sync + 'static,84    {85        Error::construct_from_adhoc(message, backtrace!())86    }8788    /// Construct an error object from a type-erased standard library error.89    ///90    /// This is mostly useful for interop with other error libraries.91    ///92    /// # Example93    ///94    /// Here is a skeleton of a library that provides its own error abstraction.95    /// The pair of `From` impls provide bidirectional support for `?`96    /// conversion between `Report` and `anyhow::Error`.97    ///98    /// ```99    /// use std::error::Error as StdError;100    ///101    /// pub struct Report {/* ... */}102    ///103    /// impl<E> From<E> for Report104    /// where105    ///     E: Into<anyhow::Error>,106    ///     Result<(), E>: anyhow::Context<(), E>,107    /// {108    ///     fn from(error: E) -> Self {109    ///         let anyhow_error: anyhow::Error = error.into();110    ///         let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();111    ///         Report::from_boxed(boxed_error)112    ///     }113    /// }114    ///115    /// impl From<Report> for anyhow::Error {116    ///     fn from(report: Report) -> Self {117    ///         let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();118    ///         anyhow::Error::from_boxed(boxed_error)119    ///     }120    /// }121    ///122    /// impl Report {123    ///     fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {124    ///         todo!()125    ///     }126    ///     fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {127    ///         todo!()128    ///     }129    /// }130    ///131    /// // Example usage: can use `?` in both directions.132    /// fn a() -> anyhow::Result<()> {133    ///     b()?;134    ///     Ok(())135    /// }136    /// fn b() -> Result<(), Report> {137    ///     a()?;138    ///     Ok(())139    /// }140    /// ```141    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]142    #[cold]143    #[must_use]144    pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {145        let backtrace = backtrace_if_absent!(&*boxed_error);146        Error::construct_from_boxed(boxed_error, backtrace)147    }148149    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]150    #[cold]151    pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self152    where153        E: StdError + Send + Sync + 'static,154    {155        let vtable = &ErrorVTable {156            object_drop: object_drop::<E>,157            object_ref: object_ref::<E>,158            #[cfg(anyhow_no_ptr_addr_of)]159            object_mut: object_mut::<E>,160            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]161            object_boxed: object_boxed::<E>,162            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]163            object_reallocate_boxed: object_reallocate_boxed::<E>,164            object_downcast: object_downcast::<E>,165            #[cfg(anyhow_no_ptr_addr_of)]166            object_downcast_mut: object_downcast_mut::<E>,167            object_drop_rest: object_drop_front::<E>,168            #[cfg(all(169                not(error_generic_member_access),170                any(std_backtrace, feature = "backtrace")171            ))]172            object_backtrace: no_backtrace,173        };174175        // Safety: passing vtable that operates on the right type E.176        unsafe { Error::construct(error, vtable, backtrace) }177    }178179    #[cold]180    pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self181    where182        M: Display + Debug + Send + Sync + 'static,183    {184        use crate::wrapper::MessageError;185        let error: MessageError<M> = MessageError(message);186        let vtable = &ErrorVTable {187            object_drop: object_drop::<MessageError<M>>,188            object_ref: object_ref::<MessageError<M>>,189            #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]190            object_mut: object_mut::<MessageError<M>>,191            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]192            object_boxed: object_boxed::<MessageError<M>>,193            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]194            object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,195            object_downcast: object_downcast::<M>,196            #[cfg(anyhow_no_ptr_addr_of)]197            object_downcast_mut: object_downcast_mut::<M>,198            object_drop_rest: object_drop_front::<M>,199            #[cfg(all(200                not(error_generic_member_access),201                any(std_backtrace, feature = "backtrace")202            ))]203            object_backtrace: no_backtrace,204        };205206        // Safety: MessageError is repr(transparent) so it is okay for the207        // vtable to allow casting the MessageError<M> to M.208        unsafe { Error::construct(error, vtable, backtrace) }209    }210211    #[cold]212    pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self213    where214        M: Display + Send + Sync + 'static,215    {216        use crate::wrapper::DisplayError;217        let error: DisplayError<M> = DisplayError(message);218        let vtable = &ErrorVTable {219            object_drop: object_drop::<DisplayError<M>>,220            object_ref: object_ref::<DisplayError<M>>,221            #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]222            object_mut: object_mut::<DisplayError<M>>,223            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]224            object_boxed: object_boxed::<DisplayError<M>>,225            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]226            object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,227            object_downcast: object_downcast::<M>,228            #[cfg(anyhow_no_ptr_addr_of)]229            object_downcast_mut: object_downcast_mut::<M>,230            object_drop_rest: object_drop_front::<M>,231            #[cfg(all(232                not(error_generic_member_access),233                any(std_backtrace, feature = "backtrace")234            ))]235            object_backtrace: no_backtrace,236        };237238        // Safety: DisplayError is repr(transparent) so it is okay for the239        // vtable to allow casting the DisplayError<M> to M.240        unsafe { Error::construct(error, vtable, backtrace) }241    }242243    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]244    #[cold]245    pub(crate) fn construct_from_context<C, E>(246        context: C,247        error: E,248        backtrace: Option<Backtrace>,249    ) -> Self250    where251        C: Display + Send + Sync + 'static,252        E: StdError + Send + Sync + 'static,253    {254        let error: ContextError<C, E> = ContextError { context, error };255256        let vtable = &ErrorVTable {257            object_drop: object_drop::<ContextError<C, E>>,258            object_ref: object_ref::<ContextError<C, E>>,259            #[cfg(anyhow_no_ptr_addr_of)]260            object_mut: object_mut::<ContextError<C, E>>,261            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]262            object_boxed: object_boxed::<ContextError<C, E>>,263            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]264            object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,265            object_downcast: context_downcast::<C, E>,266            #[cfg(anyhow_no_ptr_addr_of)]267            object_downcast_mut: context_downcast_mut::<C, E>,268            object_drop_rest: context_drop_rest::<C, E>,269            #[cfg(all(270                not(error_generic_member_access),271                any(std_backtrace, feature = "backtrace")272            ))]273            object_backtrace: no_backtrace,274        };275276        // Safety: passing vtable that operates on the right type.277        unsafe { Error::construct(error, vtable, backtrace) }278    }279280    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]281    #[cold]282    pub(crate) fn construct_from_boxed(283        error: Box<dyn StdError + Send + Sync>,284        backtrace: Option<Backtrace>,285    ) -> Self {286        use crate::wrapper::BoxedError;287        let error = BoxedError(error);288        let vtable = &ErrorVTable {289            object_drop: object_drop::<BoxedError>,290            object_ref: object_ref::<BoxedError>,291            #[cfg(anyhow_no_ptr_addr_of)]292            object_mut: object_mut::<BoxedError>,293            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]294            object_boxed: object_boxed::<BoxedError>,295            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]296            object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,297            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,298            #[cfg(anyhow_no_ptr_addr_of)]299            object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,300            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,301            #[cfg(all(302                not(error_generic_member_access),303                any(std_backtrace, feature = "backtrace")304            ))]305            object_backtrace: no_backtrace,306        };307308        // Safety: BoxedError is repr(transparent) so it is okay for the vtable309        // to allow casting to Box<dyn StdError + Send + Sync>.310        unsafe { Error::construct(error, vtable, backtrace) }311    }312313    // Takes backtrace as argument rather than capturing it here so that the314    // user sees one fewer layer of wrapping noise in the backtrace.315    //316    // Unsafe because the given vtable must have sensible behavior on the error317    // value of type E.318    #[cold]319    unsafe fn construct<E>(320        error: E,321        vtable: &'static ErrorVTable,322        backtrace: Option<Backtrace>,323    ) -> Self324    where325        E: StdError + Send + Sync + 'static,326    {327        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {328            vtable,329            backtrace,330            _object: error,331        });332        // Erase the concrete type of E from the compile-time type system. This333        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to334        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the335        // result is a thin pointer. The necessary behavior for manipulating the336        // underlying ErrorImpl<E> is preserved in the vtable provided by the337        // caller rather than a builtin fat pointer vtable.338        let inner = Own::new(inner).cast::<ErrorImpl>();339        Error { inner }340    }341342    /// Wrap the error value with additional context.343    ///344    /// For attaching context to a `Result` as it is propagated, the345    /// [`Context`][crate::Context] extension trait may be more convenient than346    /// this function.347    ///348    /// The primary reason to use `error.context(...)` instead of349    /// `result.context(...)` via the `Context` trait would be if the context350    /// needs to depend on some data held by the underlying error:351    ///352    /// ```353    /// # use std::fmt::{self, Debug, Display};354    /// #355    /// # type T = ();356    /// #357    /// # impl std::error::Error for ParseError {}358    /// # impl Debug for ParseError {359    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {360    /// #         unimplemented!()361    /// #     }362    /// # }363    /// # impl Display for ParseError {364    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {365    /// #         unimplemented!()366    /// #     }367    /// # }368    /// #369    /// use anyhow::Result;370    /// use std::fs::File;371    /// use std::path::Path;372    ///373    /// struct ParseError {374    ///     line: usize,375    ///     column: usize,376    /// }377    ///378    /// fn parse_impl(file: File) -> Result<T, ParseError> {379    ///     # const IGNORE: &str = stringify! {380    ///     ...381    ///     # };382    ///     # unimplemented!()383    /// }384    ///385    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {386    ///     let file = File::open(&path)?;387    ///     parse_impl(file).map_err(|error| {388    ///         let context = format!(389    ///             "only the first {} lines of {} are valid",390    ///             error.line, path.as_ref().display(),391    ///         );392    ///         anyhow::Error::new(error).context(context)393    ///     })394    /// }395    /// ```396    #[cold]397    #[must_use]398    pub fn context<C>(self, context: C) -> Self399    where400        C: Display + Send + Sync + 'static,401    {402        let error: ContextError<C, Error> = ContextError {403            context,404            error: self,405        };406407        let vtable = &ErrorVTable {408            object_drop: object_drop::<ContextError<C, Error>>,409            object_ref: object_ref::<ContextError<C, Error>>,410            #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]411            object_mut: object_mut::<ContextError<C, Error>>,412            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]413            object_boxed: object_boxed::<ContextError<C, Error>>,414            #[cfg(any(feature = "std", not(anyhow_no_core_error)))]415            object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,416            object_downcast: context_chain_downcast::<C>,417            #[cfg(anyhow_no_ptr_addr_of)]418            object_downcast_mut: context_chain_downcast_mut::<C>,419            object_drop_rest: context_chain_drop_rest::<C>,420            #[cfg(all(421                not(error_generic_member_access),422                any(std_backtrace, feature = "backtrace")423            ))]424            object_backtrace: context_backtrace::<C>,425        };426427        // As the cause is anyhow::Error, we already have a backtrace for it.428        let backtrace = None;429430        // Safety: passing vtable that operates on the right type.431        unsafe { Error::construct(error, vtable, backtrace) }432    }433434    /// Get the backtrace for this Error.435    ///436    /// In order for the backtrace to be meaningful, one of the two environment437    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined438    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat439    /// expensive to capture in Rust, so we don't necessarily want to be440    /// capturing them all over the place all the time.441    ///442    /// - If you want panics and errors to both have backtraces, set443    ///   `RUST_BACKTRACE=1`;444    /// - If you want only errors to have backtraces, set445    ///   `RUST_LIB_BACKTRACE=1`;446    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and447    ///   `RUST_LIB_BACKTRACE=0`.448    ///449    /// # Stability450    ///451    /// Standard library backtraces are only available when using Rust &ge;452    /// 1.65. On older compilers, this function is only available if the crate's453    /// "backtrace" feature is enabled, and will use the `backtrace` crate as454    /// the underlying backtrace implementation. The return type of this455    /// function on old compilers is `&(impl Debug + Display)`.456    ///457    /// ```toml458    /// [dependencies]459    /// anyhow = { version = "1.0", features = ["backtrace"] }460    /// ```461    #[cfg(any(std_backtrace, feature = "backtrace"))]462    pub fn backtrace(&self) -> &impl_backtrace!() {463        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }464    }465466    /// An iterator of the chain of source errors contained by this Error.467    ///468    /// This iterator will visit every error in the cause chain of this error469    /// object, beginning with the error that this error object was created470    /// from.471    ///472    /// # Example473    ///474    /// ```475    /// use anyhow::Error;476    /// use std::io;477    ///478    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {479    ///     for cause in error.chain() {480    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {481    ///             return Some(io_error.kind());482    ///         }483    ///     }484    ///     None485    /// }486    /// ```487    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]488    #[cold]489    pub fn chain(&self) -> Chain {490        unsafe { ErrorImpl::chain(self.inner.by_ref()) }491    }492493    /// The lowest level cause of this error &mdash; this error's cause's494    /// cause's cause etc.495    ///496    /// The root cause is the last error in the iterator produced by497    /// [`chain()`][Error::chain].498    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]499    #[allow(clippy::double_ended_iterator_last)]500    pub fn root_cause(&self) -> &(dyn StdError + 'static) {501        self.chain().last().unwrap()502    }503504    /// Returns true if `E` is the type held by this error object.505    ///506    /// For errors with context, this method returns true if `E` matches the507    /// type of the context `C` **or** the type of the error on which the508    /// context has been attached. For details about the interaction between509    /// context and downcasting, [see here].510    ///511    /// [see here]: crate::Context#effect-on-downcasting512    pub fn is<E>(&self) -> bool513    where514        E: Display + Debug + Send + Sync + 'static,515    {516        self.downcast_ref::<E>().is_some()517    }518519    /// Attempt to downcast the error object to a concrete type.520    pub fn downcast<E>(mut self) -> Result<E, Self>521    where522        E: Display + Debug + Send + Sync + 'static,523    {524        let target = TypeId::of::<E>();525        let inner = self.inner.by_mut();526        unsafe {527            // Use vtable to find NonNull<()> which points to a value of type E528            // somewhere inside the data structure.529            #[cfg(not(anyhow_no_ptr_addr_of))]530            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {531                Some(addr) => addr.by_mut().extend(),532                None => return Err(self),533            };534            #[cfg(anyhow_no_ptr_addr_of)]535            let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {536                Some(addr) => addr.extend(),537                None => return Err(self),538            };539540            // Prepare to read E out of the data structure. We'll drop the rest541            // of the data structure separately so that E is not dropped.542            let outer = ManuallyDrop::new(self);543544            // Read E from where the vtable found it.545            let error = addr.cast::<E>().read();546547            // Drop rest of the data structure outside of E.548            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);549550            Ok(error)551        }552    }553554    /// Downcast this error object by reference.555    ///556    /// # Example557    ///558    /// ```559    /// # use anyhow::anyhow;560    /// # use std::fmt::{self, Display};561    /// # use std::task::Poll;562    /// #563    /// # #[derive(Debug)]564    /// # enum DataStoreError {565    /// #     Censored(()),566    /// # }567    /// #568    /// # impl Display for DataStoreError {569    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {570    /// #         unimplemented!()571    /// #     }572    /// # }573    /// #574    /// # impl std::error::Error for DataStoreError {}575    /// #576    /// # const REDACTED_CONTENT: () = ();577    /// #578    /// # let error = anyhow!("...");579    /// # let root_cause = &error;580    /// #581    /// # let ret =582    /// // If the error was caused by redaction, then return a tombstone instead583    /// // of the content.584    /// match root_cause.downcast_ref::<DataStoreError>() {585    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),586    ///     None => Err(error),587    /// }588    /// # ;589    /// ```590    pub fn downcast_ref<E>(&self) -> Option<&E>591    where592        E: Display + Debug + Send + Sync + 'static,593    {594        let target = TypeId::of::<E>();595        unsafe {596            // Use vtable to find NonNull<()> which points to a value of type E597            // somewhere inside the data structure.598            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;599            Some(addr.cast::<E>().deref())600        }601    }602603    /// Downcast this error object by mutable reference.604    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>605    where606        E: Display + Debug + Send + Sync + 'static,607    {608        let target = TypeId::of::<E>();609        unsafe {610            // Use vtable to find NonNull<()> which points to a value of type E611            // somewhere inside the data structure.612613            #[cfg(not(anyhow_no_ptr_addr_of))]614            let addr =615                (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();616617            #[cfg(anyhow_no_ptr_addr_of)]618            let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;619620            Some(addr.cast::<E>().deref_mut())621        }622    }623624    /// Convert to a standard library error trait object.625    ///626    /// This is implemented as a cheap pointer cast that does not allocate or627    /// deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for628    /// interop with other error libraries.629    ///630    /// The same conversion is also available as631    /// <code style="display:inline;white-space:normal;">impl From&lt;anyhow::Error&gt;632    /// for Box&lt;dyn Error + Send + Sync + &apos;static&gt;</code>.633    ///634    /// If a backtrace was collected during construction of the `anyhow::Error`,635    /// that backtrace remains accessible using the standard library `Error`636    /// trait's provider API, but as a consequence, the resulting boxed error637    /// can no longer be downcast to its original underlying type.638    ///639    /// ```640    #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify! {")]641    /// #![feature(error_generic_member_access)]642    ///643    /// use anyhow::anyhow;644    /// use std::backtrace::Backtrace;645    /// use thiserror::Error;646    ///647    /// #[derive(Error, Debug)]648    /// #[error("...")]649    /// struct MyError;650    ///651    /// let anyhow_error = anyhow!(MyError);652    /// println!("{}", anyhow_error.backtrace());  // has Backtrace653    /// assert!(anyhow_error.downcast_ref::<MyError>().is_some());  // can downcast654    ///655    /// let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();656    /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some());  // has Backtrace657    /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none());  // can no longer downcast658    #[cfg_attr(not(error_generic_member_access), doc = "# };")]659    /// ```660    ///661    /// [`anyhow::Error::from_boxed`]: Self::from_boxed662    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]663    #[must_use]664    pub fn into_boxed_dyn_error(self) -> Box<dyn StdError + Send + Sync + 'static> {665        let outer = ManuallyDrop::new(self);666        unsafe {667            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for668            // the right original type E.669            (vtable(outer.inner.ptr).object_boxed)(outer.inner)670        }671    }672673    /// Convert to a standard library error trait object.674    ///675    /// Unlike `self.into_boxed_dyn_error()`, this method relocates the676    /// underlying error into a new allocation in order to make it downcastable677    /// to `&E` or `Box<E>` for its original underlying error type. Any678    /// backtrace collected during construction of the `anyhow::Error` is679    /// discarded.680    ///681    /// ```682    #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify!{")]683    /// #![feature(error_generic_member_access)]684    ///685    /// use anyhow::anyhow;686    /// use std::backtrace::Backtrace;687    /// use thiserror::Error;688    ///689    /// #[derive(Error, Debug)]690    /// #[error("...")]691    /// struct MyError;692    ///693    /// let anyhow_error = anyhow!(MyError);694    /// println!("{}", anyhow_error.backtrace());  // has Backtrace695    /// assert!(anyhow_error.downcast_ref::<MyError>().is_some());  // can downcast696    ///697    /// let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();698    /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none());  // Backtrace lost699    /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some());  // can downcast to &MyError700    /// assert!(boxed_dyn_error.downcast::<MyError>().is_ok());  // can downcast to Box<MyError>701    #[cfg_attr(not(error_generic_member_access), doc = "# };")]702    /// ```703    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]704    #[must_use]705    pub fn reallocate_into_boxed_dyn_error_without_backtrace(706        self,707    ) -> Box<dyn StdError + Send + Sync + 'static> {708        let outer = ManuallyDrop::new(self);709        unsafe {710            // Use vtable to attach E's native StdError vtable for the right711            // original type E.712            (vtable(outer.inner.ptr).object_reallocate_boxed)(outer.inner)713        }714    }715716    #[cfg(error_generic_member_access)]717    pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {718        unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }719    }720721    // Called by thiserror when you have `#[source] anyhow::Error`. This provide722    // implementation includes the anyhow::Error's Backtrace if any, unlike723    // deref'ing to dyn Error where the provide implementation would include724    // only the original error's Backtrace from before it got wrapped into an725    // anyhow::Error.726    #[cfg(error_generic_member_access)]727    #[doc(hidden)]728    pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {729        Self::provide(self, request);730    }731}732733#[cfg(any(feature = "std", not(anyhow_no_core_error)))]734impl<E> From<E> for Error735where736    E: StdError + Send + Sync + 'static,737{738    #[cold]739    fn from(error: E) -> Self {740        let backtrace = backtrace_if_absent!(&error);741        Error::construct_from_std(error, backtrace)742    }743}744745#[cfg(any(feature = "std", not(anyhow_no_core_error)))]746impl Deref for Error {747    type Target = dyn StdError + Send + Sync + 'static;748749    fn deref(&self) -> &Self::Target {750        unsafe { ErrorImpl::error(self.inner.by_ref()) }751    }752}753754#[cfg(any(feature = "std", not(anyhow_no_core_error)))]755impl DerefMut for Error {756    fn deref_mut(&mut self) -> &mut Self::Target {757        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }758    }759}760761impl Display for Error {762    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {763        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }764    }765}766767impl Debug for Error {768    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {769        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }770    }771}772773impl Drop for Error {774    fn drop(&mut self) {775        unsafe {776            // Invoke the vtable's drop behavior.777            (vtable(self.inner.ptr).object_drop)(self.inner);778        }779    }780}781782struct ErrorVTable {783    object_drop: unsafe fn(Own<ErrorImpl>),784    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,785    #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]786    object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),787    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]788    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,789    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]790    object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,791    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,792    #[cfg(anyhow_no_ptr_addr_of)]793    object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,794    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),795    #[cfg(all(796        not(error_generic_member_access),797        any(std_backtrace, feature = "backtrace")798    ))]799    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,800}801802// Safety: requires layout of *e to match ErrorImpl<E>.803unsafe fn object_drop<E>(e: Own<ErrorImpl>) {804    // Cast back to ErrorImpl<E> so that the allocator receives the correct805    // Layout to deallocate the Box's memory.806    let unerased_own = e.cast::<ErrorImpl<E>>();807    drop(unsafe { unerased_own.boxed() });808}809810// Safety: requires layout of *e to match ErrorImpl<E>.811unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {812    // Drop the fields of ErrorImpl other than E as well as the Box allocation,813    // without dropping E itself. This is used by downcast after doing a814    // ptr::read to take ownership of the E.815    let _ = target;816    let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();817    drop(unsafe { unerased_own.boxed() });818}819820// Safety: requires layout of *e to match ErrorImpl<E>.821unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>822where823    E: StdError + Send + Sync + 'static,824{825    // Attach E's native StdError vtable onto a pointer to self._object.826827    let unerased_ref = e.cast::<ErrorImpl<E>>();828829    #[cfg(not(anyhow_no_ptr_addr_of))]830    return Ref::from_raw(unsafe {831        NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)832    });833834    #[cfg(anyhow_no_ptr_addr_of)]835    return Ref::new(unsafe { &unerased_ref.deref()._object });836}837838// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived839// from a `&mut`840#[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]841unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)842where843    E: StdError + Send + Sync + 'static,844{845    // Attach E's native StdError vtable onto a pointer to self._object.846    let unerased_mut = e.cast::<ErrorImpl<E>>();847    unsafe { &mut unerased_mut.deref_mut()._object }848}849850// Safety: requires layout of *e to match ErrorImpl<E>.851#[cfg(any(feature = "std", not(anyhow_no_core_error)))]852unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>853where854    E: StdError + Send + Sync + 'static,855{856    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.857    let unerased_own = e.cast::<ErrorImpl<E>>();858    unsafe { unerased_own.boxed() }859}860861// Safety: requires layout of *e to match ErrorImpl<E>.862#[cfg(any(feature = "std", not(anyhow_no_core_error)))]863unsafe fn object_reallocate_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>864where865    E: StdError + Send + Sync + 'static,866{867    // Attach E's native StdError vtable.868    let unerased_own = e.cast::<ErrorImpl<E>>();869    Box::new(unsafe { unerased_own.boxed() }._object)870}871872// Safety: requires layout of *e to match ErrorImpl<E>.873unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>874where875    E: 'static,876{877    if TypeId::of::<E>() == target {878        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a879        // pointer to its E field.880881        let unerased_ref = e.cast::<ErrorImpl<E>>();882883        #[cfg(not(anyhow_no_ptr_addr_of))]884        return Some(885            Ref::from_raw(unsafe {886                NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)887            })888            .cast::<()>(),889        );890891        #[cfg(anyhow_no_ptr_addr_of)]892        return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());893    } else {894        None895    }896}897898// Safety: requires layout of *e to match ErrorImpl<E>.899#[cfg(anyhow_no_ptr_addr_of)]900unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>901where902    E: 'static,903{904    if TypeId::of::<E>() == target {905        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a906        // pointer to its E field.907        let unerased_mut = e.cast::<ErrorImpl<E>>();908        let unerased = unsafe { unerased_mut.deref_mut() };909        Some(Mut::new(&mut unerased._object).cast::<()>())910    } else {911        None912    }913}914915#[cfg(all(916    not(error_generic_member_access),917    any(std_backtrace, feature = "backtrace")918))]919fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {920    let _ = e;921    None922}923924// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.925#[cfg(any(feature = "std", not(anyhow_no_core_error)))]926unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>927where928    C: 'static,929    E: 'static,930{931    if TypeId::of::<C>() == target {932        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();933        let unerased = unsafe { unerased_ref.deref() };934        Some(Ref::new(&unerased._object.context).cast::<()>())935    } else if TypeId::of::<E>() == target {936        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();937        let unerased = unsafe { unerased_ref.deref() };938        Some(Ref::new(&unerased._object.error).cast::<()>())939    } else {940        None941    }942}943944// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.945#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]946unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>947where948    C: 'static,949    E: 'static,950{951    if TypeId::of::<C>() == target {952        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();953        let unerased = unsafe { unerased_mut.deref_mut() };954        Some(Mut::new(&mut unerased._object.context).cast::<()>())955    } else if TypeId::of::<E>() == target {956        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();957        let unerased = unsafe { unerased_mut.deref_mut() };958        Some(Mut::new(&mut unerased._object.error).cast::<()>())959    } else {960        None961    }962}963964// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.965#[cfg(any(feature = "std", not(anyhow_no_core_error)))]966unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)967where968    C: 'static,969    E: 'static,970{971    // Called after downcasting by value to either the C or the E and doing a972    // ptr::read to take ownership of that value.973    if TypeId::of::<C>() == target {974        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();975        drop(unsafe { unerased_own.boxed() });976    } else {977        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();978        drop(unsafe { unerased_own.boxed() });979    }980}981982// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.983unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>984where985    C: 'static,986{987    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();988    let unerased = unsafe { unerased_ref.deref() };989    if TypeId::of::<C>() == target {990        Some(Ref::new(&unerased._object.context).cast::<()>())991    } else {992        // Recurse down the context chain per the inner error's vtable.993        let source = &unerased._object.error;994        unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }995    }996}997998// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.999#[cfg(anyhow_no_ptr_addr_of)]1000unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>1001where1002    C: 'static,1003{1004    let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();1005    let unerased = unsafe { unerased_mut.deref_mut() };1006    if TypeId::of::<C>() == target {1007        Some(Mut::new(&mut unerased._object.context).cast::<()>())1008    } else {1009        // Recurse down the context chain per the inner error's vtable.1010        let source = &mut unerased._object.error;1011        unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }1012    }1013}10141015// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.1016unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)1017where1018    C: 'static,1019{1020    // Called after downcasting by value to either the C or one of the causes1021    // and doing a ptr::read to take ownership of that value.1022    if TypeId::of::<C>() == target {1023        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();1024        // Drop the entire rest of the data structure rooted in the next Error.1025        drop(unsafe { unerased_own.boxed() });1026    } else {1027        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();1028        let unerased = unsafe { unerased_own.boxed() };1029        // Read the Own<ErrorImpl> from the next error.1030        let inner = unerased._object.error.inner;1031        drop(unerased);1032        let vtable = unsafe { vtable(inner.ptr) };1033        // Recursively drop the next error using the same target typeid.1034        unsafe { (vtable.object_drop_rest)(inner, target) };1035    }1036}10371038// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.1039#[cfg(all(1040    not(error_generic_member_access),1041    any(std_backtrace, feature = "backtrace")1042))]1043#[allow(clippy::unnecessary_wraps)]1044unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>1045where1046    C: 'static,1047{1048    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();1049    let unerased = unsafe { unerased_ref.deref() };1050    let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };1051    Some(backtrace)1052}10531054// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor1055// of raw pointers and `NonNull`.1056// repr C to ensure that E remains in the final position.1057#[repr(C)]1058pub(crate) struct ErrorImpl<E = ()> {1059    vtable: &'static ErrorVTable,1060    backtrace: Option<Backtrace>,1061    // NOTE: Don't use directly. Use only through vtable. Erased type may have1062    // different alignment.1063    _object: E,1064}10651066// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but1067// avoids converting `p` into a reference.1068unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {1069    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.1070    unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }1071}10721073// repr C to ensure that ContextError<C, E> has the same layout as1074// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.1075#[repr(C)]1076pub(crate) struct ContextError<C, E> {1077    pub context: C,1078    pub error: E,1079}10801081impl<E> ErrorImpl<E> {1082    fn erase(&self) -> Ref<ErrorImpl> {1083        // Erase the concrete type of E but preserve the vtable in self.vtable1084        // for manipulating the resulting thin pointer. This is analogous to an1085        // unsize coercion.1086        Ref::new(self).cast::<ErrorImpl>()1087    }1088}10891090impl ErrorImpl {1091    pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {1092        // Use vtable to attach E's native StdError vtable for the right1093        // original type E.1094        unsafe { (vtable(this.ptr).object_ref)(this).deref() }1095    }10961097    #[cfg(any(feature = "std", not(anyhow_no_core_error)))]1098    pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {1099        // Use vtable to attach E's native StdError vtable for the right1100        // original type E.11011102        #[cfg(not(anyhow_no_ptr_addr_of))]1103        return unsafe {1104            (vtable(this.ptr).object_ref)(this.by_ref())1105                .by_mut()1106                .deref_mut()1107        };11081109        #[cfg(anyhow_no_ptr_addr_of)]1110        return unsafe { (vtable(this.ptr).object_mut)(this) };1111    }11121113    #[cfg(any(std_backtrace, feature = "backtrace"))]1114    pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {1115        // This unwrap can only panic if the underlying error's backtrace method1116        // is nondeterministic, which would only happen in maliciously1117        // constructed code.1118        unsafe { this.deref() }1119            .backtrace1120            .as_ref()1121            .or_else(|| {1122                #[cfg(error_generic_member_access)]1123                return nightly::request_ref_backtrace(unsafe { Self::error(this) });1124                #[cfg(not(error_generic_member_access))]1125                return unsafe { (vtable(this.ptr).object_backtrace)(this) };1126            })1127            .expect("backtrace capture failed")1128    }11291130    #[cfg(error_generic_member_access)]1131    unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {1132        if let Some(backtrace) = unsafe { &this.deref().backtrace } {1133            nightly::provide_ref_backtrace(request, backtrace);1134        }1135        nightly::provide(unsafe { Self::error(this) }, request);1136    }11371138    #[cold]1139    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {1140        Chain::new(unsafe { Self::error(this) })1141    }1142}11431144impl<E> StdError for ErrorImpl<E>1145where1146    E: StdError,1147{1148    fn source(&self) -> Option<&(dyn StdError + 'static)> {1149        unsafe { ErrorImpl::error(self.erase()).source() }1150    }11511152    #[cfg(error_generic_member_access)]1153    fn provide<'a>(&'a self, request: &mut Request<'a>) {1154        unsafe { ErrorImpl::provide(self.erase(), request) }1155    }1156}11571158impl<E> Debug for ErrorImpl<E>1159where1160    E: Debug,1161{1162    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1163        unsafe { ErrorImpl::debug(self.erase(), formatter) }1164    }1165}11661167impl<E> Display for ErrorImpl<E>1168where1169    E: Display,1170{1171    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1172        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }1173    }1174}11751176#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1177impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {1178    #[cold]1179    fn from(error: Error) -> Self {1180        error.into_boxed_dyn_error()1181    }1182}11831184#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1185impl From<Error> for Box<dyn StdError + Send + 'static> {1186    #[cold]1187    fn from(error: Error) -> Self {1188        error.into_boxed_dyn_error()1189    }1190}11911192#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1193impl From<Error> for Box<dyn StdError + 'static> {1194    #[cold]1195    fn from(error: Error) -> Self {1196        error.into_boxed_dyn_error()1197    }1198}11991200#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1201impl AsRef<dyn StdError + Send + Sync> for Error {1202    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1203        &**self1204    }1205}12061207#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1208impl AsRef<dyn StdError> for Error {1209    fn as_ref(&self) -> &(dyn StdError + 'static) {1210        &**self1211    }1212}12131214#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1215impl UnwindSafe for Error {}12161217#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1218impl RefUnwindSafe for Error {}