Skip to content
Myr

error.rs

This file

Path

src/error.rs

970 lines · 33.0 KiB · Rust

Last changed by

Merge pull request #229 from dtolnay/must_useDavid Tolnaybefore adoptionc8a3e42

History of this file

Take it

1use crate::backtrace::Backtrace;2use crate::chain::Chain;3#[cfg(any(feature = "std", anyhow_no_ptr_addr_of))]4use crate::ptr::Mut;5use crate::ptr::{Own, Ref};6use crate::{Error, StdError};7use alloc::boxed::Box;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    #[cold]29    #[must_use]30    pub fn new<E>(error: E) -> Self31    where32        E: StdError + Send + Sync + 'static,33    {34        let backtrace = backtrace_if_absent!(error);35        Error::from_std(error, backtrace)36    }3738    /// Create a new error object from a printable error message.39    ///40    /// If the argument implements std::error::Error, prefer `Error::new`41    /// instead which preserves the underlying error's cause chain and42    /// backtrace. If the argument may or may not implement std::error::Error43    /// now or in the future, use `anyhow!(err)` which handles either way44    /// correctly.45    ///46    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally47    /// convenient in places where a function is preferable over a macro, such48    /// as iterator or stream combinators:49    ///50    /// ```51    /// # mod ffi {52    /// #     pub struct Input;53    /// #     pub struct Output;54    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {55    /// #         unimplemented!()56    /// #     }57    /// # }58    /// #59    /// # use ffi::{Input, Output};60    /// #61    /// use anyhow::{Error, Result};62    /// use futures::stream::{Stream, StreamExt, TryStreamExt};63    ///64    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>65    /// where66    ///     S: Stream<Item = Input>,67    /// {68    ///     stream69    ///         .then(ffi::do_some_work) // returns Result<Output, &str>70    ///         .map_err(Error::msg)71    ///         .try_collect()72    ///         .await73    /// }74    /// ```75    #[cold]76    #[must_use]77    pub fn msg<M>(message: M) -> Self78    where79        M: Display + Debug + Send + Sync + 'static,80    {81        Error::from_adhoc(message, backtrace!())82    }8384    #[cfg(feature = "std")]85    #[cold]86    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self87    where88        E: StdError + Send + Sync + 'static,89    {90        let vtable = &ErrorVTable {91            object_drop: object_drop::<E>,92            object_ref: object_ref::<E>,93            #[cfg(anyhow_no_ptr_addr_of)]94            object_mut: object_mut::<E>,95            object_boxed: object_boxed::<E>,96            object_downcast: object_downcast::<E>,97            #[cfg(anyhow_no_ptr_addr_of)]98            object_downcast_mut: object_downcast_mut::<E>,99            object_drop_rest: object_drop_front::<E>,100            #[cfg(all(not(backtrace), feature = "backtrace"))]101            object_backtrace: no_backtrace,102        };103104        // Safety: passing vtable that operates on the right type E.105        unsafe { Error::construct(error, vtable, backtrace) }106    }107108    #[cold]109    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self110    where111        M: Display + Debug + Send + Sync + 'static,112    {113        use crate::wrapper::MessageError;114        let error: MessageError<M> = MessageError(message);115        let vtable = &ErrorVTable {116            object_drop: object_drop::<MessageError<M>>,117            object_ref: object_ref::<MessageError<M>>,118            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]119            object_mut: object_mut::<MessageError<M>>,120            object_boxed: object_boxed::<MessageError<M>>,121            object_downcast: object_downcast::<M>,122            #[cfg(anyhow_no_ptr_addr_of)]123            object_downcast_mut: object_downcast_mut::<M>,124            object_drop_rest: object_drop_front::<M>,125            #[cfg(all(not(backtrace), feature = "backtrace"))]126            object_backtrace: no_backtrace,127        };128129        // Safety: MessageError is repr(transparent) so it is okay for the130        // vtable to allow casting the MessageError<M> to M.131        unsafe { Error::construct(error, vtable, backtrace) }132    }133134    #[cold]135    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self136    where137        M: Display + Send + Sync + 'static,138    {139        use crate::wrapper::DisplayError;140        let error: DisplayError<M> = DisplayError(message);141        let vtable = &ErrorVTable {142            object_drop: object_drop::<DisplayError<M>>,143            object_ref: object_ref::<DisplayError<M>>,144            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]145            object_mut: object_mut::<DisplayError<M>>,146            object_boxed: object_boxed::<DisplayError<M>>,147            object_downcast: object_downcast::<M>,148            #[cfg(anyhow_no_ptr_addr_of)]149            object_downcast_mut: object_downcast_mut::<M>,150            object_drop_rest: object_drop_front::<M>,151            #[cfg(all(not(backtrace), feature = "backtrace"))]152            object_backtrace: no_backtrace,153        };154155        // Safety: DisplayError is repr(transparent) so it is okay for the156        // vtable to allow casting the DisplayError<M> to M.157        unsafe { Error::construct(error, vtable, backtrace) }158    }159160    #[cfg(feature = "std")]161    #[cold]162    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self163    where164        C: Display + Send + Sync + 'static,165        E: StdError + Send + Sync + 'static,166    {167        let error: ContextError<C, E> = ContextError { context, error };168169        let vtable = &ErrorVTable {170            object_drop: object_drop::<ContextError<C, E>>,171            object_ref: object_ref::<ContextError<C, E>>,172            #[cfg(anyhow_no_ptr_addr_of)]173            object_mut: object_mut::<ContextError<C, E>>,174            object_boxed: object_boxed::<ContextError<C, E>>,175            object_downcast: context_downcast::<C, E>,176            #[cfg(anyhow_no_ptr_addr_of)]177            object_downcast_mut: context_downcast_mut::<C, E>,178            object_drop_rest: context_drop_rest::<C, E>,179            #[cfg(all(not(backtrace), feature = "backtrace"))]180            object_backtrace: no_backtrace,181        };182183        // Safety: passing vtable that operates on the right type.184        unsafe { Error::construct(error, vtable, backtrace) }185    }186187    #[cfg(feature = "std")]188    #[cold]189    pub(crate) fn from_boxed(190        error: Box<dyn StdError + Send + Sync>,191        backtrace: Option<Backtrace>,192    ) -> Self {193        use crate::wrapper::BoxedError;194        let error = BoxedError(error);195        let vtable = &ErrorVTable {196            object_drop: object_drop::<BoxedError>,197            object_ref: object_ref::<BoxedError>,198            #[cfg(anyhow_no_ptr_addr_of)]199            object_mut: object_mut::<BoxedError>,200            object_boxed: object_boxed::<BoxedError>,201            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,202            #[cfg(anyhow_no_ptr_addr_of)]203            object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,204            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,205            #[cfg(all(not(backtrace), feature = "backtrace"))]206            object_backtrace: no_backtrace,207        };208209        // Safety: BoxedError is repr(transparent) so it is okay for the vtable210        // to allow casting to Box<dyn StdError + Send + Sync>.211        unsafe { Error::construct(error, vtable, backtrace) }212    }213214    // Takes backtrace as argument rather than capturing it here so that the215    // user sees one fewer layer of wrapping noise in the backtrace.216    //217    // Unsafe because the given vtable must have sensible behavior on the error218    // value of type E.219    #[cold]220    unsafe fn construct<E>(221        error: E,222        vtable: &'static ErrorVTable,223        backtrace: Option<Backtrace>,224    ) -> Self225    where226        E: StdError + Send + Sync + 'static,227    {228        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {229            vtable,230            backtrace,231            _object: error,232        });233        // Erase the concrete type of E from the compile-time type system. This234        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to235        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the236        // result is a thin pointer. The necessary behavior for manipulating the237        // underlying ErrorImpl<E> is preserved in the vtable provided by the238        // caller rather than a builtin fat pointer vtable.239        let inner = Own::new(inner).cast::<ErrorImpl>();240        Error { inner }241    }242243    /// Wrap the error value with additional context.244    ///245    /// For attaching context to a `Result` as it is propagated, the246    /// [`Context`][crate::Context] extension trait may be more convenient than247    /// this function.248    ///249    /// The primary reason to use `error.context(...)` instead of250    /// `result.context(...)` via the `Context` trait would be if the context251    /// needs to depend on some data held by the underlying error:252    ///253    /// ```254    /// # use std::fmt::{self, Debug, Display};255    /// #256    /// # type T = ();257    /// #258    /// # impl std::error::Error for ParseError {}259    /// # impl Debug for ParseError {260    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {261    /// #         unimplemented!()262    /// #     }263    /// # }264    /// # impl Display for ParseError {265    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {266    /// #         unimplemented!()267    /// #     }268    /// # }269    /// #270    /// use anyhow::Result;271    /// use std::fs::File;272    /// use std::path::Path;273    ///274    /// struct ParseError {275    ///     line: usize,276    ///     column: usize,277    /// }278    ///279    /// fn parse_impl(file: File) -> Result<T, ParseError> {280    ///     # const IGNORE: &str = stringify! {281    ///     ...282    ///     # };283    ///     # unimplemented!()284    /// }285    ///286    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {287    ///     let file = File::open(&path)?;288    ///     parse_impl(file).map_err(|error| {289    ///         let context = format!(290    ///             "only the first {} lines of {} are valid",291    ///             error.line, path.as_ref().display(),292    ///         );293    ///         anyhow::Error::new(error).context(context)294    ///     })295    /// }296    /// ```297    #[cold]298    #[must_use]299    pub fn context<C>(self, context: C) -> Self300    where301        C: Display + Send + Sync + 'static,302    {303        let error: ContextError<C, Error> = ContextError {304            context,305            error: self,306        };307308        let vtable = &ErrorVTable {309            object_drop: object_drop::<ContextError<C, Error>>,310            object_ref: object_ref::<ContextError<C, Error>>,311            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]312            object_mut: object_mut::<ContextError<C, Error>>,313            object_boxed: object_boxed::<ContextError<C, Error>>,314            object_downcast: context_chain_downcast::<C>,315            #[cfg(anyhow_no_ptr_addr_of)]316            object_downcast_mut: context_chain_downcast_mut::<C>,317            object_drop_rest: context_chain_drop_rest::<C>,318            #[cfg(all(not(backtrace), feature = "backtrace"))]319            object_backtrace: context_backtrace::<C>,320        };321322        // As the cause is anyhow::Error, we already have a backtrace for it.323        let backtrace = None;324325        // Safety: passing vtable that operates on the right type.326        unsafe { Error::construct(error, vtable, backtrace) }327    }328329    /// Get the backtrace for this Error.330    ///331    /// In order for the backtrace to be meaningful, one of the two environment332    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined333    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat334    /// expensive to capture in Rust, so we don't necessarily want to be335    /// capturing them all over the place all the time.336    ///337    /// - If you want panics and errors to both have backtraces, set338    ///   `RUST_BACKTRACE=1`;339    /// - If you want only errors to have backtraces, set340    ///   `RUST_LIB_BACKTRACE=1`;341    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and342    ///   `RUST_LIB_BACKTRACE=0`.343    ///344    /// # Stability345    ///346    /// Standard library backtraces are only available on the nightly channel.347    /// Tracking issue: [rust-lang/rust#53487][tracking].348    ///349    /// On stable compilers, this function is only available if the crate's350    /// "backtrace" feature is enabled, and will use the `backtrace` crate as351    /// the underlying backtrace implementation.352    ///353    /// ```toml354    /// [dependencies]355    /// anyhow = { version = "1.0", features = ["backtrace"] }356    /// ```357    ///358    /// [tracking]: https://github.com/rust-lang/rust/issues/53487359    #[cfg(any(backtrace, feature = "backtrace"))]360    #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]361    pub fn backtrace(&self) -> &impl_backtrace!() {362        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }363    }364365    /// An iterator of the chain of source errors contained by this Error.366    ///367    /// This iterator will visit every error in the cause chain of this error368    /// object, beginning with the error that this error object was created369    /// from.370    ///371    /// # Example372    ///373    /// ```374    /// use anyhow::Error;375    /// use std::io;376    ///377    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {378    ///     for cause in error.chain() {379    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {380    ///             return Some(io_error.kind());381    ///         }382    ///     }383    ///     None384    /// }385    /// ```386    #[cfg(feature = "std")]387    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]388    #[cold]389    pub fn chain(&self) -> Chain {390        unsafe { ErrorImpl::chain(self.inner.by_ref()) }391    }392393    /// The lowest level cause of this error &mdash; this error's cause's394    /// cause's cause etc.395    ///396    /// The root cause is the last error in the iterator produced by397    /// [`chain()`][Error::chain].398    #[cfg(feature = "std")]399    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]400    pub fn root_cause(&self) -> &(dyn StdError + 'static) {401        self.chain().last().unwrap()402    }403404    /// Returns true if `E` is the type held by this error object.405    ///406    /// For errors with context, this method returns true if `E` matches the407    /// type of the context `C` **or** the type of the error on which the408    /// context has been attached. For details about the interaction between409    /// context and downcasting, [see here].410    ///411    /// [see here]: trait.Context.html#effect-on-downcasting412    pub fn is<E>(&self) -> bool413    where414        E: Display + Debug + Send + Sync + 'static,415    {416        self.downcast_ref::<E>().is_some()417    }418419    /// Attempt to downcast the error object to a concrete type.420    pub fn downcast<E>(mut self) -> Result<E, Self>421    where422        E: Display + Debug + Send + Sync + 'static,423    {424        let target = TypeId::of::<E>();425        let inner = self.inner.by_mut();426        unsafe {427            // Use vtable to find NonNull<()> which points to a value of type E428            // somewhere inside the data structure.429            #[cfg(not(anyhow_no_ptr_addr_of))]430            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {431                Some(addr) => addr.by_mut().extend(),432                None => return Err(self),433            };434            #[cfg(anyhow_no_ptr_addr_of)]435            let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {436                Some(addr) => addr.extend(),437                None => return Err(self),438            };439440            // Prepare to read E out of the data structure. We'll drop the rest441            // of the data structure separately so that E is not dropped.442            let outer = ManuallyDrop::new(self);443444            // Read E from where the vtable found it.445            let error = addr.cast::<E>().read();446447            // Drop rest of the data structure outside of E.448            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);449450            Ok(error)451        }452    }453454    /// Downcast this error object by reference.455    ///456    /// # Example457    ///458    /// ```459    /// # use anyhow::anyhow;460    /// # use std::fmt::{self, Display};461    /// # use std::task::Poll;462    /// #463    /// # #[derive(Debug)]464    /// # enum DataStoreError {465    /// #     Censored(()),466    /// # }467    /// #468    /// # impl Display for DataStoreError {469    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {470    /// #         unimplemented!()471    /// #     }472    /// # }473    /// #474    /// # impl std::error::Error for DataStoreError {}475    /// #476    /// # const REDACTED_CONTENT: () = ();477    /// #478    /// # let error = anyhow!("...");479    /// # let root_cause = &error;480    /// #481    /// # let ret =482    /// // If the error was caused by redaction, then return a tombstone instead483    /// // of the content.484    /// match root_cause.downcast_ref::<DataStoreError>() {485    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),486    ///     None => Err(error),487    /// }488    /// # ;489    /// ```490    pub fn downcast_ref<E>(&self) -> Option<&E>491    where492        E: Display + Debug + Send + Sync + 'static,493    {494        let target = TypeId::of::<E>();495        unsafe {496            // Use vtable to find NonNull<()> which points to a value of type E497            // somewhere inside the data structure.498            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;499            Some(addr.cast::<E>().deref())500        }501    }502503    /// Downcast this error object by mutable reference.504    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>505    where506        E: Display + Debug + Send + Sync + 'static,507    {508        let target = TypeId::of::<E>();509        unsafe {510            // Use vtable to find NonNull<()> which points to a value of type E511            // somewhere inside the data structure.512513            #[cfg(not(anyhow_no_ptr_addr_of))]514            let addr =515                (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();516517            #[cfg(anyhow_no_ptr_addr_of)]518            let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;519520            Some(addr.cast::<E>().deref_mut())521        }522    }523}524525#[cfg(feature = "std")]526#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]527impl<E> From<E> for Error528where529    E: StdError + Send + Sync + 'static,530{531    #[cold]532    fn from(error: E) -> Self {533        let backtrace = backtrace_if_absent!(error);534        Error::from_std(error, backtrace)535    }536}537538#[cfg(feature = "std")]539#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]540impl Deref for Error {541    type Target = dyn StdError + Send + Sync + 'static;542543    fn deref(&self) -> &Self::Target {544        unsafe { ErrorImpl::error(self.inner.by_ref()) }545    }546}547548#[cfg(feature = "std")]549#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]550impl DerefMut for Error {551    fn deref_mut(&mut self) -> &mut Self::Target {552        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }553    }554}555556impl Display for Error {557    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {558        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }559    }560}561562impl Debug for Error {563    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {564        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }565    }566}567568impl Drop for Error {569    fn drop(&mut self) {570        unsafe {571            // Invoke the vtable's drop behavior.572            (vtable(self.inner.ptr).object_drop)(self.inner);573        }574    }575}576577struct ErrorVTable {578    object_drop: unsafe fn(Own<ErrorImpl>),579    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,580    #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]581    object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),582    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,583    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,584    #[cfg(anyhow_no_ptr_addr_of)]585    object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,586    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),587    #[cfg(all(not(backtrace), feature = "backtrace"))]588    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,589}590591// Safety: requires layout of *e to match ErrorImpl<E>.592unsafe fn object_drop<E>(e: Own<ErrorImpl>) {593    // Cast back to ErrorImpl<E> so that the allocator receives the correct594    // Layout to deallocate the Box's memory.595    let unerased = e.cast::<ErrorImpl<E>>().boxed();596    drop(unerased);597}598599// Safety: requires layout of *e to match ErrorImpl<E>.600unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {601    // Drop the fields of ErrorImpl other than E as well as the Box allocation,602    // without dropping E itself. This is used by downcast after doing a603    // ptr::read to take ownership of the E.604    let _ = target;605    let unerased = e.cast::<ErrorImpl<ManuallyDrop<E>>>().boxed();606    drop(unerased);607}608609// Safety: requires layout of *e to match ErrorImpl<E>.610unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>611where612    E: StdError + Send + Sync + 'static,613{614    // Attach E's native StdError vtable onto a pointer to self._object.615616    let unerased = e.cast::<ErrorImpl<E>>();617618    #[cfg(not(anyhow_no_ptr_addr_of))]619    return Ref::from_raw(NonNull::new_unchecked(620        ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,621    ));622623    #[cfg(anyhow_no_ptr_addr_of)]624    return Ref::new(&unerased.deref()._object);625}626627// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived628// from a `&mut`629#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]630unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)631where632    E: StdError + Send + Sync + 'static,633{634    // Attach E's native StdError vtable onto a pointer to self._object.635    &mut e.cast::<ErrorImpl<E>>().deref_mut()._object636}637638// Safety: requires layout of *e to match ErrorImpl<E>.639unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>640where641    E: StdError + Send + Sync + 'static,642{643    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.644    e.cast::<ErrorImpl<E>>().boxed()645}646647// Safety: requires layout of *e to match ErrorImpl<E>.648unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>649where650    E: 'static,651{652    if TypeId::of::<E>() == target {653        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a654        // pointer to its E field.655656        let unerased = e.cast::<ErrorImpl<E>>();657658        #[cfg(not(anyhow_no_ptr_addr_of))]659        return Some(660            Ref::from_raw(NonNull::new_unchecked(661                ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,662            ))663            .cast::<()>(),664        );665666        #[cfg(anyhow_no_ptr_addr_of)]667        return Some(Ref::new(&unerased.deref()._object).cast::<()>());668    } else {669        None670    }671}672673// Safety: requires layout of *e to match ErrorImpl<E>.674#[cfg(anyhow_no_ptr_addr_of)]675unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>676where677    E: 'static,678{679    if TypeId::of::<E>() == target {680        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a681        // pointer to its E field.682        let unerased = e.cast::<ErrorImpl<E>>().deref_mut();683        Some(Mut::new(&mut unerased._object).cast::<()>())684    } else {685        None686    }687}688689#[cfg(all(not(backtrace), feature = "backtrace"))]690fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {691    let _ = e;692    None693}694695// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.696#[cfg(feature = "std")]697unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>698where699    C: 'static,700    E: 'static,701{702    if TypeId::of::<C>() == target {703        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();704        Some(Ref::new(&unerased._object.context).cast::<()>())705    } else if TypeId::of::<E>() == target {706        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();707        Some(Ref::new(&unerased._object.error).cast::<()>())708    } else {709        None710    }711}712713// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.714#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]715unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>716where717    C: 'static,718    E: 'static,719{720    if TypeId::of::<C>() == target {721        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();722        Some(Mut::new(&mut unerased._object.context).cast::<()>())723    } else if TypeId::of::<E>() == target {724        let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();725        Some(Mut::new(&mut unerased._object.error).cast::<()>())726    } else {727        None728    }729}730731// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.732#[cfg(feature = "std")]733unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)734where735    C: 'static,736    E: 'static,737{738    // Called after downcasting by value to either the C or the E and doing a739    // ptr::read to take ownership of that value.740    if TypeId::of::<C>() == target {741        let unerased = e742            .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>()743            .boxed();744        drop(unerased);745    } else {746        let unerased = e747            .cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>()748            .boxed();749        drop(unerased);750    }751}752753// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.754unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>755where756    C: 'static,757{758    let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();759    if TypeId::of::<C>() == target {760        Some(Ref::new(&unerased._object.context).cast::<()>())761    } else {762        // Recurse down the context chain per the inner error's vtable.763        let source = &unerased._object.error;764        (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target)765    }766}767768// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.769#[cfg(anyhow_no_ptr_addr_of)]770unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>771where772    C: 'static,773{774    let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();775    if TypeId::of::<C>() == target {776        Some(Mut::new(&mut unerased._object.context).cast::<()>())777    } else {778        // Recurse down the context chain per the inner error's vtable.779        let source = &mut unerased._object.error;780        (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target)781    }782}783784// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.785unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)786where787    C: 'static,788{789    // Called after downcasting by value to either the C or one of the causes790    // and doing a ptr::read to take ownership of that value.791    if TypeId::of::<C>() == target {792        let unerased = e793            .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>()794            .boxed();795        // Drop the entire rest of the data structure rooted in the next Error.796        drop(unerased);797    } else {798        let unerased = e799            .cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>()800            .boxed();801        // Read the Own<ErrorImpl> from the next error.802        let inner = unerased._object.error.inner;803        drop(unerased);804        let vtable = vtable(inner.ptr);805        // Recursively drop the next error using the same target typeid.806        (vtable.object_drop_rest)(inner, target);807    }808}809810// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.811#[cfg(all(not(backtrace), feature = "backtrace"))]812#[allow(clippy::unnecessary_wraps)]813unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>814where815    C: 'static,816{817    let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();818    let backtrace = ErrorImpl::backtrace(unerased._object.error.inner.by_ref());819    Some(backtrace)820}821822// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor823// of raw pointers and `NonNull`.824// repr C to ensure that E remains in the final position.825#[repr(C)]826pub(crate) struct ErrorImpl<E = ()> {827    vtable: &'static ErrorVTable,828    backtrace: Option<Backtrace>,829    // NOTE: Don't use directly. Use only through vtable. Erased type may have830    // different alignment.831    _object: E,832}833834// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but835// avoids converting `p` into a reference.836unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {837    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.838    *(p.as_ptr() as *const &'static ErrorVTable)839}840841// repr C to ensure that ContextError<C, E> has the same layout as842// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.843#[repr(C)]844pub(crate) struct ContextError<C, E> {845    pub context: C,846    pub error: E,847}848849impl<E> ErrorImpl<E> {850    fn erase(&self) -> Ref<ErrorImpl> {851        // Erase the concrete type of E but preserve the vtable in self.vtable852        // for manipulating the resulting thin pointer. This is analogous to an853        // unsize coercion.854        Ref::new(self).cast::<ErrorImpl>()855    }856}857858impl ErrorImpl {859    pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {860        // Use vtable to attach E's native StdError vtable for the right861        // original type E.862        (vtable(this.ptr).object_ref)(this).deref()863    }864865    #[cfg(feature = "std")]866    pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {867        // Use vtable to attach E's native StdError vtable for the right868        // original type E.869870        #[cfg(not(anyhow_no_ptr_addr_of))]871        return (vtable(this.ptr).object_ref)(this.by_ref())872            .by_mut()873            .deref_mut();874875        #[cfg(anyhow_no_ptr_addr_of)]876        return (vtable(this.ptr).object_mut)(this);877    }878879    #[cfg(any(backtrace, feature = "backtrace"))]880    pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {881        // This unwrap can only panic if the underlying error's backtrace method882        // is nondeterministic, which would only happen in maliciously883        // constructed code.884        this.deref()885            .backtrace886            .as_ref()887            .or_else(|| {888                #[cfg(backtrace)]889                return Self::error(this).backtrace();890                #[cfg(all(not(backtrace), feature = "backtrace"))]891                return (vtable(this.ptr).object_backtrace)(this);892            })893            .expect("backtrace capture failed")894    }895896    #[cold]897    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {898        Chain::new(Self::error(this))899    }900}901902impl<E> StdError for ErrorImpl<E>903where904    E: StdError,905{906    #[cfg(backtrace)]907    fn backtrace(&self) -> Option<&Backtrace> {908        Some(unsafe { ErrorImpl::backtrace(self.erase()) })909    }910911    fn source(&self) -> Option<&(dyn StdError + 'static)> {912        unsafe { ErrorImpl::error(self.erase()).source() }913    }914}915916impl<E> Debug for ErrorImpl<E>917where918    E: Debug,919{920    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {921        unsafe { ErrorImpl::debug(self.erase(), formatter) }922    }923}924925impl<E> Display for ErrorImpl<E>926where927    E: Display,928{929    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {930        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }931    }932}933934impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {935    #[cold]936    fn from(error: Error) -> Self {937        let outer = ManuallyDrop::new(error);938        unsafe {939            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for940            // the right original type E.941            (vtable(outer.inner.ptr).object_boxed)(outer.inner)942        }943    }944}945946impl From<Error> for Box<dyn StdError + Send + 'static> {947    fn from(error: Error) -> Self {948        Box::<dyn StdError + Send + Sync>::from(error)949    }950}951952impl From<Error> for Box<dyn StdError + 'static> {953    fn from(error: Error) -> Self {954        Box::<dyn StdError + Send + Sync>::from(error)955    }956}957958#[cfg(feature = "std")]959impl AsRef<dyn StdError + Send + Sync> for Error {960    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {961        &**self962    }963}964965#[cfg(feature = "std")]966impl AsRef<dyn StdError> for Error {967    fn as_ref(&self) -> &(dyn StdError + 'static) {968        &**self969    }970}