Skip to content
Myr

error.rs

This file

Path

src/error.rs

956 lines · 32.9 KiB · Rust

Last changed by

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

History of this file

Take it

1use crate::alloc::Box;2use crate::backtrace::Backtrace;3use crate::chain::Chain;4#[cfg(any(feature = "std", anyhow_no_ptr_addr_of))]5use crate::ptr::Mut;6use crate::ptr::{Own, Ref};7use crate::{Error, StdError};8use core::any::TypeId;9use core::fmt::{self, Debug, Display};10use core::mem::ManuallyDrop;11#[cfg(not(anyhow_no_ptr_addr_of))]12use core::ptr;13use core::ptr::NonNull;1415#[cfg(feature = "std")]16use core::ops::{Deref, DerefMut};1718impl Error {19    /// Create a new error object from any error type.20    ///21    /// The error type must be threadsafe and `'static`, so that the `Error`22    /// will be as well.23    ///24    /// If the error type does not provide a backtrace, a backtrace will be25    /// created here to ensure that a backtrace exists.26    #[cfg(feature = "std")]27    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]28    pub fn new<E>(error: E) -> Self29    where30        E: StdError + Send + Sync + 'static,31    {32        let backtrace = backtrace_if_absent!(error);33        Error::from_std(error, backtrace)34    }3536    /// Create a new error object from a printable error message.37    ///38    /// If the argument implements std::error::Error, prefer `Error::new`39    /// instead which preserves the underlying error's cause chain and40    /// backtrace. If the argument may or may not implement std::error::Error41    /// now or in the future, use `anyhow!(err)` which handles either way42    /// correctly.43    ///44    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally45    /// convenient in places where a function is preferable over a macro, such46    /// as iterator or stream combinators:47    ///48    /// ```49    /// # mod ffi {50    /// #     pub struct Input;51    /// #     pub struct Output;52    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {53    /// #         unimplemented!()54    /// #     }55    /// # }56    /// #57    /// # use ffi::{Input, Output};58    /// #59    /// use anyhow::{Error, Result};60    /// use futures::stream::{Stream, StreamExt, TryStreamExt};61    ///62    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>63    /// where64    ///     S: Stream<Item = Input>,65    /// {66    ///     stream67    ///         .then(ffi::do_some_work) // returns Result<Output, &str>68    ///         .map_err(Error::msg)69    ///         .try_collect()70    ///         .await71    /// }72    /// ```73    pub fn msg<M>(message: M) -> Self74    where75        M: Display + Debug + Send + Sync + 'static,76    {77        Error::from_adhoc(message, backtrace!())78    }7980    #[cfg(feature = "std")]81    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self82    where83        E: StdError + Send + Sync + 'static,84    {85        let vtable = &ErrorVTable {86            object_drop: object_drop::<E>,87            object_ref: object_ref::<E>,88            #[cfg(anyhow_no_ptr_addr_of)]89            object_mut: object_mut::<E>,90            object_boxed: object_boxed::<E>,91            object_downcast: object_downcast::<E>,92            #[cfg(anyhow_no_ptr_addr_of)]93            object_downcast_mut: object_downcast_mut::<E>,94            object_drop_rest: object_drop_front::<E>,95            #[cfg(all(not(backtrace), feature = "backtrace"))]96            object_backtrace: no_backtrace,97        };9899        // Safety: passing vtable that operates on the right type E.100        unsafe { Error::construct(error, vtable, backtrace) }101    }102103    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self104    where105        M: Display + Debug + Send + Sync + 'static,106    {107        use crate::wrapper::MessageError;108        let error: MessageError<M> = MessageError(message);109        let vtable = &ErrorVTable {110            object_drop: object_drop::<MessageError<M>>,111            object_ref: object_ref::<MessageError<M>>,112            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]113            object_mut: object_mut::<MessageError<M>>,114            object_boxed: object_boxed::<MessageError<M>>,115            object_downcast: object_downcast::<M>,116            #[cfg(anyhow_no_ptr_addr_of)]117            object_downcast_mut: object_downcast_mut::<M>,118            object_drop_rest: object_drop_front::<M>,119            #[cfg(all(not(backtrace), feature = "backtrace"))]120            object_backtrace: no_backtrace,121        };122123        // Safety: MessageError is repr(transparent) so it is okay for the124        // vtable to allow casting the MessageError<M> to M.125        unsafe { Error::construct(error, vtable, backtrace) }126    }127128    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self129    where130        M: Display + Send + Sync + 'static,131    {132        use crate::wrapper::DisplayError;133        let error: DisplayError<M> = DisplayError(message);134        let vtable = &ErrorVTable {135            object_drop: object_drop::<DisplayError<M>>,136            object_ref: object_ref::<DisplayError<M>>,137            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]138            object_mut: object_mut::<DisplayError<M>>,139            object_boxed: object_boxed::<DisplayError<M>>,140            object_downcast: object_downcast::<M>,141            #[cfg(anyhow_no_ptr_addr_of)]142            object_downcast_mut: object_downcast_mut::<M>,143            object_drop_rest: object_drop_front::<M>,144            #[cfg(all(not(backtrace), feature = "backtrace"))]145            object_backtrace: no_backtrace,146        };147148        // Safety: DisplayError is repr(transparent) so it is okay for the149        // vtable to allow casting the DisplayError<M> to M.150        unsafe { Error::construct(error, vtable, backtrace) }151    }152153    #[cfg(feature = "std")]154    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self155    where156        C: Display + Send + Sync + 'static,157        E: StdError + Send + Sync + 'static,158    {159        let error: ContextError<C, E> = ContextError { context, error };160161        let vtable = &ErrorVTable {162            object_drop: object_drop::<ContextError<C, E>>,163            object_ref: object_ref::<ContextError<C, E>>,164            #[cfg(anyhow_no_ptr_addr_of)]165            object_mut: object_mut::<ContextError<C, E>>,166            object_boxed: object_boxed::<ContextError<C, E>>,167            object_downcast: context_downcast::<C, E>,168            #[cfg(anyhow_no_ptr_addr_of)]169            object_downcast_mut: context_downcast_mut::<C, E>,170            object_drop_rest: context_drop_rest::<C, E>,171            #[cfg(all(not(backtrace), feature = "backtrace"))]172            object_backtrace: no_backtrace,173        };174175        // Safety: passing vtable that operates on the right type.176        unsafe { Error::construct(error, vtable, backtrace) }177    }178179    #[cfg(feature = "std")]180    pub(crate) fn from_boxed(181        error: Box<dyn StdError + Send + Sync>,182        backtrace: Option<Backtrace>,183    ) -> Self {184        use crate::wrapper::BoxedError;185        let error = BoxedError(error);186        let vtable = &ErrorVTable {187            object_drop: object_drop::<BoxedError>,188            object_ref: object_ref::<BoxedError>,189            #[cfg(anyhow_no_ptr_addr_of)]190            object_mut: object_mut::<BoxedError>,191            object_boxed: object_boxed::<BoxedError>,192            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,193            #[cfg(anyhow_no_ptr_addr_of)]194            object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,195            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,196            #[cfg(all(not(backtrace), feature = "backtrace"))]197            object_backtrace: no_backtrace,198        };199200        // Safety: BoxedError is repr(transparent) so it is okay for the vtable201        // to allow casting to Box<dyn StdError + Send + Sync>.202        unsafe { Error::construct(error, vtable, backtrace) }203    }204205    // Takes backtrace as argument rather than capturing it here so that the206    // user sees one fewer layer of wrapping noise in the backtrace.207    //208    // Unsafe because the given vtable must have sensible behavior on the error209    // value of type E.210    unsafe fn construct<E>(211        error: E,212        vtable: &'static ErrorVTable,213        backtrace: Option<Backtrace>,214    ) -> Self215    where216        E: StdError + Send + Sync + 'static,217    {218        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {219            vtable,220            backtrace,221            _object: error,222        });223        // Erase the concrete type of E from the compile-time type system. This224        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to225        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the226        // result is a thin pointer. The necessary behavior for manipulating the227        // underlying ErrorImpl<E> is preserved in the vtable provided by the228        // caller rather than a builtin fat pointer vtable.229        let inner = Own::new(inner).cast::<ErrorImpl>();230        Error { inner }231    }232233    /// Wrap the error value with additional context.234    ///235    /// For attaching context to a `Result` as it is propagated, the236    /// [`Context`][crate::Context] extension trait may be more convenient than237    /// this function.238    ///239    /// The primary reason to use `error.context(...)` instead of240    /// `result.context(...)` via the `Context` trait would be if the context241    /// needs to depend on some data held by the underlying error:242    ///243    /// ```244    /// # use std::fmt::{self, Debug, Display};245    /// #246    /// # type T = ();247    /// #248    /// # impl std::error::Error for ParseError {}249    /// # impl Debug for ParseError {250    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {251    /// #         unimplemented!()252    /// #     }253    /// # }254    /// # impl Display for ParseError {255    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {256    /// #         unimplemented!()257    /// #     }258    /// # }259    /// #260    /// use anyhow::Result;261    /// use std::fs::File;262    /// use std::path::Path;263    ///264    /// struct ParseError {265    ///     line: usize,266    ///     column: usize,267    /// }268    ///269    /// fn parse_impl(file: File) -> Result<T, ParseError> {270    ///     # const IGNORE: &str = stringify! {271    ///     ...272    ///     # };273    ///     # unimplemented!()274    /// }275    ///276    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {277    ///     let file = File::open(&path)?;278    ///     parse_impl(file).map_err(|error| {279    ///         let context = format!(280    ///             "only the first {} lines of {} are valid",281    ///             error.line, path.as_ref().display(),282    ///         );283    ///         anyhow::Error::new(error).context(context)284    ///     })285    /// }286    /// ```287    pub fn context<C>(self, context: C) -> Self288    where289        C: Display + Send + Sync + 'static,290    {291        let error: ContextError<C, Error> = ContextError {292            context,293            error: self,294        };295296        let vtable = &ErrorVTable {297            object_drop: object_drop::<ContextError<C, Error>>,298            object_ref: object_ref::<ContextError<C, Error>>,299            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]300            object_mut: object_mut::<ContextError<C, Error>>,301            object_boxed: object_boxed::<ContextError<C, Error>>,302            object_downcast: context_chain_downcast::<C>,303            #[cfg(anyhow_no_ptr_addr_of)]304            object_downcast_mut: context_chain_downcast_mut::<C>,305            object_drop_rest: context_chain_drop_rest::<C>,306            #[cfg(all(not(backtrace), feature = "backtrace"))]307            object_backtrace: context_backtrace::<C>,308        };309310        // As the cause is anyhow::Error, we already have a backtrace for it.311        let backtrace = None;312313        // Safety: passing vtable that operates on the right type.314        unsafe { Error::construct(error, vtable, backtrace) }315    }316317    /// Get the backtrace for this Error.318    ///319    /// In order for the backtrace to be meaningful, one of the two environment320    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined321    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat322    /// expensive to capture in Rust, so we don't necessarily want to be323    /// capturing them all over the place all the time.324    ///325    /// - If you want panics and errors to both have backtraces, set326    ///   `RUST_BACKTRACE=1`;327    /// - If you want only errors to have backtraces, set328    ///   `RUST_LIB_BACKTRACE=1`;329    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and330    ///   `RUST_LIB_BACKTRACE=0`.331    ///332    /// # Stability333    ///334    /// Standard library backtraces are only available on the nightly channel.335    /// Tracking issue: [rust-lang/rust#53487][tracking].336    ///337    /// On stable compilers, this function is only available if the crate's338    /// "backtrace" feature is enabled, and will use the `backtrace` crate as339    /// the underlying backtrace implementation.340    ///341    /// ```toml342    /// [dependencies]343    /// anyhow = { version = "1.0", features = ["backtrace"] }344    /// ```345    ///346    /// [tracking]: https://github.com/rust-lang/rust/issues/53487347    #[cfg(any(backtrace, feature = "backtrace"))]348    #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]349    pub fn backtrace(&self) -> &impl_backtrace!() {350        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }351    }352353    /// An iterator of the chain of source errors contained by this Error.354    ///355    /// This iterator will visit every error in the cause chain of this error356    /// object, beginning with the error that this error object was created357    /// from.358    ///359    /// # Example360    ///361    /// ```362    /// use anyhow::Error;363    /// use std::io;364    ///365    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {366    ///     for cause in error.chain() {367    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {368    ///             return Some(io_error.kind());369    ///         }370    ///     }371    ///     None372    /// }373    /// ```374    #[cfg(feature = "std")]375    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]376    pub fn chain(&self) -> Chain {377        unsafe { ErrorImpl::chain(self.inner.by_ref()) }378    }379380    /// The lowest level cause of this error &mdash; this error's cause's381    /// cause's cause etc.382    ///383    /// The root cause is the last error in the iterator produced by384    /// [`chain()`][Error::chain].385    #[cfg(feature = "std")]386    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]387    pub fn root_cause(&self) -> &(dyn StdError + 'static) {388        self.chain().last().unwrap()389    }390391    /// Returns true if `E` is the type held by this error object.392    ///393    /// For errors with context, this method returns true if `E` matches the394    /// type of the context `C` **or** the type of the error on which the395    /// context has been attached. For details about the interaction between396    /// context and downcasting, [see here].397    ///398    /// [see here]: trait.Context.html#effect-on-downcasting399    pub fn is<E>(&self) -> bool400    where401        E: Display + Debug + Send + Sync + 'static,402    {403        self.downcast_ref::<E>().is_some()404    }405406    /// Attempt to downcast the error object to a concrete type.407    pub fn downcast<E>(mut self) -> Result<E, Self>408    where409        E: Display + Debug + Send + Sync + 'static,410    {411        let target = TypeId::of::<E>();412        let inner = self.inner.by_mut();413        unsafe {414            // Use vtable to find NonNull<()> which points to a value of type E415            // somewhere inside the data structure.416            #[cfg(not(anyhow_no_ptr_addr_of))]417            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {418                Some(addr) => addr.by_mut().extend(),419                None => return Err(self),420            };421            #[cfg(anyhow_no_ptr_addr_of)]422            let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {423                Some(addr) => addr.extend(),424                None => return Err(self),425            };426427            // Prepare to read E out of the data structure. We'll drop the rest428            // of the data structure separately so that E is not dropped.429            let outer = ManuallyDrop::new(self);430431            // Read E from where the vtable found it.432            let error = addr.cast::<E>().read();433434            // Drop rest of the data structure outside of E.435            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);436437            Ok(error)438        }439    }440441    /// Downcast this error object by reference.442    ///443    /// # Example444    ///445    /// ```446    /// # use anyhow::anyhow;447    /// # use std::fmt::{self, Display};448    /// # use std::task::Poll;449    /// #450    /// # #[derive(Debug)]451    /// # enum DataStoreError {452    /// #     Censored(()),453    /// # }454    /// #455    /// # impl Display for DataStoreError {456    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {457    /// #         unimplemented!()458    /// #     }459    /// # }460    /// #461    /// # impl std::error::Error for DataStoreError {}462    /// #463    /// # const REDACTED_CONTENT: () = ();464    /// #465    /// # let error = anyhow!("...");466    /// # let root_cause = &error;467    /// #468    /// # let ret =469    /// // If the error was caused by redaction, then return a tombstone instead470    /// // of the content.471    /// match root_cause.downcast_ref::<DataStoreError>() {472    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),473    ///     None => Err(error),474    /// }475    /// # ;476    /// ```477    pub fn downcast_ref<E>(&self) -> Option<&E>478    where479        E: Display + Debug + Send + Sync + 'static,480    {481        let target = TypeId::of::<E>();482        unsafe {483            // Use vtable to find NonNull<()> which points to a value of type E484            // somewhere inside the data structure.485            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;486            Some(addr.cast::<E>().deref())487        }488    }489490    /// Downcast this error object by mutable reference.491    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>492    where493        E: Display + Debug + Send + Sync + 'static,494    {495        let target = TypeId::of::<E>();496        unsafe {497            // Use vtable to find NonNull<()> which points to a value of type E498            // somewhere inside the data structure.499500            #[cfg(not(anyhow_no_ptr_addr_of))]501            let addr =502                (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();503504            #[cfg(anyhow_no_ptr_addr_of)]505            let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;506507            Some(addr.cast::<E>().deref_mut())508        }509    }510}511512#[cfg(feature = "std")]513#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]514impl<E> From<E> for Error515where516    E: StdError + Send + Sync + 'static,517{518    fn from(error: E) -> Self {519        let backtrace = backtrace_if_absent!(error);520        Error::from_std(error, backtrace)521    }522}523524#[cfg(feature = "std")]525#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]526impl Deref for Error {527    type Target = dyn StdError + Send + Sync + 'static;528529    fn deref(&self) -> &Self::Target {530        unsafe { ErrorImpl::error(self.inner.by_ref()) }531    }532}533534#[cfg(feature = "std")]535#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]536impl DerefMut for Error {537    fn deref_mut(&mut self) -> &mut Self::Target {538        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }539    }540}541542impl Display for Error {543    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {544        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }545    }546}547548impl Debug for Error {549    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {550        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }551    }552}553554impl Drop for Error {555    fn drop(&mut self) {556        unsafe {557            // Invoke the vtable's drop behavior.558            (vtable(self.inner.ptr).object_drop)(self.inner);559        }560    }561}562563struct ErrorVTable {564    object_drop: unsafe fn(Own<ErrorImpl>),565    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,566    #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]567    object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),568    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,569    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,570    #[cfg(anyhow_no_ptr_addr_of)]571    object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,572    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),573    #[cfg(all(not(backtrace), feature = "backtrace"))]574    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,575}576577// Safety: requires layout of *e to match ErrorImpl<E>.578unsafe fn object_drop<E>(e: Own<ErrorImpl>) {579    // Cast back to ErrorImpl<E> so that the allocator receives the correct580    // Layout to deallocate the Box's memory.581    let unerased = e.cast::<ErrorImpl<E>>().boxed();582    drop(unerased);583}584585// Safety: requires layout of *e to match ErrorImpl<E>.586unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {587    // Drop the fields of ErrorImpl other than E as well as the Box allocation,588    // without dropping E itself. This is used by downcast after doing a589    // ptr::read to take ownership of the E.590    let _ = target;591    let unerased = e.cast::<ErrorImpl<ManuallyDrop<E>>>().boxed();592    drop(unerased);593}594595// Safety: requires layout of *e to match ErrorImpl<E>.596unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>597where598    E: StdError + Send + Sync + 'static,599{600    // Attach E's native StdError vtable onto a pointer to self._object.601602    let unerased = e.cast::<ErrorImpl<E>>();603604    #[cfg(not(anyhow_no_ptr_addr_of))]605    return Ref::from_raw(NonNull::new_unchecked(606        ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,607    ));608609    #[cfg(anyhow_no_ptr_addr_of)]610    return Ref::new(&unerased.deref()._object);611}612613// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived614// from a `&mut`615#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]616unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)617where618    E: StdError + Send + Sync + 'static,619{620    // Attach E's native StdError vtable onto a pointer to self._object.621    &mut e.cast::<ErrorImpl<E>>().deref_mut()._object622}623624// Safety: requires layout of *e to match ErrorImpl<E>.625unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>626where627    E: StdError + Send + Sync + 'static,628{629    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.630    e.cast::<ErrorImpl<E>>().boxed()631}632633// Safety: requires layout of *e to match ErrorImpl<E>.634unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>635where636    E: 'static,637{638    if TypeId::of::<E>() == target {639        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a640        // pointer to its E field.641642        let unerased = e.cast::<ErrorImpl<E>>();643644        #[cfg(not(anyhow_no_ptr_addr_of))]645        return Some(646            Ref::from_raw(NonNull::new_unchecked(647                ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,648            ))649            .cast::<()>(),650        );651652        #[cfg(anyhow_no_ptr_addr_of)]653        return Some(Ref::new(&unerased.deref()._object).cast::<()>());654    } else {655        None656    }657}658659// Safety: requires layout of *e to match ErrorImpl<E>.660#[cfg(anyhow_no_ptr_addr_of)]661unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>662where663    E: 'static,664{665    if TypeId::of::<E>() == target {666        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a667        // pointer to its E field.668        let unerased = e.cast::<ErrorImpl<E>>().deref_mut();669        Some(Mut::new(&mut unerased._object).cast::<()>())670    } else {671        None672    }673}674675#[cfg(all(not(backtrace), feature = "backtrace"))]676fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {677    let _ = e;678    None679}680681// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.682#[cfg(feature = "std")]683unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>684where685    C: 'static,686    E: 'static,687{688    if TypeId::of::<C>() == target {689        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();690        Some(Ref::new(&unerased._object.context).cast::<()>())691    } else if TypeId::of::<E>() == target {692        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();693        Some(Ref::new(&unerased._object.error).cast::<()>())694    } else {695        None696    }697}698699// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.700#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]701unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>702where703    C: 'static,704    E: 'static,705{706    if TypeId::of::<C>() == target {707        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();708        Some(Mut::new(&mut unerased._object.context).cast::<()>())709    } else if TypeId::of::<E>() == target {710        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();711        Some(Mut::new(&mut unerased._object.error).cast::<()>())712    } else {713        None714    }715}716717// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.718#[cfg(feature = "std")]719unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)720where721    C: 'static,722    E: 'static,723{724    // Called after downcasting by value to either the C or the E and doing a725    // ptr::read to take ownership of that value.726    if TypeId::of::<C>() == target {727        let unerased = e728            .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>()729            .boxed();730        drop(unerased);731    } else {732        let unerased = e733            .cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>()734            .boxed();735        drop(unerased);736    }737}738739// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.740unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>741where742    C: 'static,743{744    if TypeId::of::<C>() == target {745        let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();746        Some(Ref::new(&unerased._object.context).cast::<()>())747    } else {748        // Recurse down the context chain per the inner error's vtable.749        let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();750        let source = &unerased._object.error;751        (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target)752    }753}754755// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.756#[cfg(anyhow_no_ptr_addr_of)]757unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>758where759    C: 'static,760{761    if TypeId::of::<C>() == target {762        let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();763        Some(Mut::new(&mut unerased._object.context).cast::<()>())764    } else {765        // Recurse down the context chain per the inner error's vtable.766        let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();767        let source = &mut unerased._object.error;768        (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target)769    }770}771772// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.773unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)774where775    C: 'static,776{777    // Called after downcasting by value to either the C or one of the causes778    // and doing a ptr::read to take ownership of that value.779    if TypeId::of::<C>() == target {780        let unerased = e781            .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>()782            .boxed();783        // Drop the entire rest of the data structure rooted in the next Error.784        drop(unerased);785    } else {786        let unerased = e787            .cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>()788            .boxed();789        // Read the Own<ErrorImpl> from the next error.790        let inner = unerased._object.error.inner;791        drop(unerased);792        let vtable = vtable(inner.ptr);793        // Recursively drop the next error using the same target typeid.794        (vtable.object_drop_rest)(inner, target);795    }796}797798// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.799#[cfg(all(not(backtrace), feature = "backtrace"))]800#[allow(clippy::unnecessary_wraps)]801unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>802where803    C: 'static,804{805    let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();806    let backtrace = ErrorImpl::backtrace(unerased._object.error.inner.by_ref());807    Some(backtrace)808}809810// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor811// of raw pointers and `NonNull`.812// repr C to ensure that E remains in the final position.813#[repr(C)]814pub(crate) struct ErrorImpl<E = ()> {815    vtable: &'static ErrorVTable,816    backtrace: Option<Backtrace>,817    // NOTE: Don't use directly. Use only through vtable. Erased type may have818    // different alignment.819    _object: E,820}821822// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but823// avoids converting `p` into a reference.824unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {825    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.826    *(p.as_ptr() as *const &'static ErrorVTable)827}828829// repr C to ensure that ContextError<C, E> has the same layout as830// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.831#[repr(C)]832pub(crate) struct ContextError<C, E> {833    pub context: C,834    pub error: E,835}836837impl<E> ErrorImpl<E> {838    fn erase(&self) -> Ref<ErrorImpl> {839        // Erase the concrete type of E but preserve the vtable in self.vtable840        // for manipulating the resulting thin pointer. This is analogous to an841        // unsize coercion.842        Ref::new(self).cast::<ErrorImpl>()843    }844}845846impl ErrorImpl {847    pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {848        // Use vtable to attach E's native StdError vtable for the right849        // original type E.850        (vtable(this.ptr).object_ref)(this).deref()851    }852853    #[cfg(feature = "std")]854    pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {855        // Use vtable to attach E's native StdError vtable for the right856        // original type E.857858        #[cfg(not(anyhow_no_ptr_addr_of))]859        return (vtable(this.ptr).object_ref)(this.by_ref())860            .by_mut()861            .deref_mut();862863        #[cfg(anyhow_no_ptr_addr_of)]864        return (vtable(this.ptr).object_mut)(this);865    }866867    #[cfg(any(backtrace, feature = "backtrace"))]868    pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {869        // This unwrap can only panic if the underlying error's backtrace method870        // is nondeterministic, which would only happen in maliciously871        // constructed code.872        this.deref()873            .backtrace874            .as_ref()875            .or_else(|| {876                #[cfg(backtrace)]877                return Self::error(this).backtrace();878                #[cfg(all(not(backtrace), feature = "backtrace"))]879                return (vtable(this.ptr).object_backtrace)(this);880            })881            .expect("backtrace capture failed")882    }883884    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {885        Chain::new(Self::error(this))886    }887}888889impl<E> StdError for ErrorImpl<E>890where891    E: StdError,892{893    #[cfg(backtrace)]894    fn backtrace(&self) -> Option<&Backtrace> {895        Some(unsafe { ErrorImpl::backtrace(self.erase()) })896    }897898    fn source(&self) -> Option<&(dyn StdError + 'static)> {899        unsafe { ErrorImpl::error(self.erase()).source() }900    }901}902903impl<E> Debug for ErrorImpl<E>904where905    E: Debug,906{907    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {908        unsafe { ErrorImpl::debug(self.erase(), formatter) }909    }910}911912impl<E> Display for ErrorImpl<E>913where914    E: Display,915{916    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {917        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }918    }919}920921impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {922    fn from(error: Error) -> Self {923        let outer = ManuallyDrop::new(error);924        unsafe {925            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for926            // the right original type E.927            (vtable(outer.inner.ptr).object_boxed)(outer.inner)928        }929    }930}931932impl From<Error> for Box<dyn StdError + Send + 'static> {933    fn from(error: Error) -> Self {934        Box::<dyn StdError + Send + Sync>::from(error)935    }936}937938impl From<Error> for Box<dyn StdError + 'static> {939    fn from(error: Error) -> Self {940        Box::<dyn StdError + Send + Sync>::from(error)941    }942}943944#[cfg(feature = "std")]945impl AsRef<dyn StdError + Send + Sync> for Error {946    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {947        &**self948    }949}950951#[cfg(feature = "std")]952impl AsRef<dyn StdError> for Error {953    fn as_ref(&self) -> &(dyn StdError + 'static) {954        &**self955    }956}