Skip to content
Myr

error.rs

This file

Path

src/error.rs

997 lines · 35.0 KiB · Rust

Last changed by

provide_api -> error_generic_member_accessDavid Tolnaybefore adoption2b79af8

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;14#[cfg(error_generic_member_access)]15use std::error::{self, Request};1617#[cfg(feature = "std")]18use core::ops::{Deref, DerefMut};1920impl Error {21    /// Create a new error object from any error type.22    ///23    /// The error type must be threadsafe and `'static`, so that the `Error`24    /// will be as well.25    ///26    /// If the error type does not provide a backtrace, a backtrace will be27    /// created here to ensure that a backtrace exists.28    #[cfg(feature = "std")]29    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]30    #[cold]31    #[must_use]32    pub fn new<E>(error: E) -> Self33    where34        E: StdError + Send + Sync + 'static,35    {36        let backtrace = backtrace_if_absent!(&error);37        Error::from_std(error, backtrace)38    }3940    /// Create a new error object from a printable error message.41    ///42    /// If the argument implements std::error::Error, prefer `Error::new`43    /// instead which preserves the underlying error's cause chain and44    /// backtrace. If the argument may or may not implement std::error::Error45    /// now or in the future, use `anyhow!(err)` which handles either way46    /// correctly.47    ///48    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally49    /// convenient in places where a function is preferable over a macro, such50    /// as iterator or stream combinators:51    ///52    /// ```53    /// # mod ffi {54    /// #     pub struct Input;55    /// #     pub struct Output;56    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {57    /// #         unimplemented!()58    /// #     }59    /// # }60    /// #61    /// # use ffi::{Input, Output};62    /// #63    /// use anyhow::{Error, Result};64    /// use futures::stream::{Stream, StreamExt, TryStreamExt};65    ///66    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>67    /// where68    ///     S: Stream<Item = Input>,69    /// {70    ///     stream71    ///         .then(ffi::do_some_work) // returns Result<Output, &str>72    ///         .map_err(Error::msg)73    ///         .try_collect()74    ///         .await75    /// }76    /// ```77    #[cold]78    #[must_use]79    pub fn msg<M>(message: M) -> Self80    where81        M: Display + Debug + Send + Sync + 'static,82    {83        Error::from_adhoc(message, backtrace!())84    }8586    #[cfg(feature = "std")]87    #[cold]88    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self89    where90        E: StdError + Send + Sync + 'static,91    {92        let vtable = &ErrorVTable {93            object_drop: object_drop::<E>,94            object_ref: object_ref::<E>,95            #[cfg(anyhow_no_ptr_addr_of)]96            object_mut: object_mut::<E>,97            object_boxed: object_boxed::<E>,98            object_downcast: object_downcast::<E>,99            #[cfg(anyhow_no_ptr_addr_of)]100            object_downcast_mut: object_downcast_mut::<E>,101            object_drop_rest: object_drop_front::<E>,102            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]103            object_backtrace: no_backtrace,104        };105106        // Safety: passing vtable that operates on the right type E.107        unsafe { Error::construct(error, vtable, backtrace) }108    }109110    #[cold]111    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self112    where113        M: Display + Debug + Send + Sync + 'static,114    {115        use crate::wrapper::MessageError;116        let error: MessageError<M> = MessageError(message);117        let vtable = &ErrorVTable {118            object_drop: object_drop::<MessageError<M>>,119            object_ref: object_ref::<MessageError<M>>,120            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]121            object_mut: object_mut::<MessageError<M>>,122            object_boxed: object_boxed::<MessageError<M>>,123            object_downcast: object_downcast::<M>,124            #[cfg(anyhow_no_ptr_addr_of)]125            object_downcast_mut: object_downcast_mut::<M>,126            object_drop_rest: object_drop_front::<M>,127            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]128            object_backtrace: no_backtrace,129        };130131        // Safety: MessageError is repr(transparent) so it is okay for the132        // vtable to allow casting the MessageError<M> to M.133        unsafe { Error::construct(error, vtable, backtrace) }134    }135136    #[cold]137    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self138    where139        M: Display + Send + Sync + 'static,140    {141        use crate::wrapper::DisplayError;142        let error: DisplayError<M> = DisplayError(message);143        let vtable = &ErrorVTable {144            object_drop: object_drop::<DisplayError<M>>,145            object_ref: object_ref::<DisplayError<M>>,146            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]147            object_mut: object_mut::<DisplayError<M>>,148            object_boxed: object_boxed::<DisplayError<M>>,149            object_downcast: object_downcast::<M>,150            #[cfg(anyhow_no_ptr_addr_of)]151            object_downcast_mut: object_downcast_mut::<M>,152            object_drop_rest: object_drop_front::<M>,153            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]154            object_backtrace: no_backtrace,155        };156157        // Safety: DisplayError is repr(transparent) so it is okay for the158        // vtable to allow casting the DisplayError<M> to M.159        unsafe { Error::construct(error, vtable, backtrace) }160    }161162    #[cfg(feature = "std")]163    #[cold]164    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self165    where166        C: Display + Send + Sync + 'static,167        E: StdError + Send + Sync + 'static,168    {169        let error: ContextError<C, E> = ContextError { context, error };170171        let vtable = &ErrorVTable {172            object_drop: object_drop::<ContextError<C, E>>,173            object_ref: object_ref::<ContextError<C, E>>,174            #[cfg(anyhow_no_ptr_addr_of)]175            object_mut: object_mut::<ContextError<C, E>>,176            object_boxed: object_boxed::<ContextError<C, E>>,177            object_downcast: context_downcast::<C, E>,178            #[cfg(anyhow_no_ptr_addr_of)]179            object_downcast_mut: context_downcast_mut::<C, E>,180            object_drop_rest: context_drop_rest::<C, E>,181            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]182            object_backtrace: no_backtrace,183        };184185        // Safety: passing vtable that operates on the right type.186        unsafe { Error::construct(error, vtable, backtrace) }187    }188189    #[cfg(feature = "std")]190    #[cold]191    pub(crate) fn from_boxed(192        error: Box<dyn StdError + Send + Sync>,193        backtrace: Option<Backtrace>,194    ) -> Self {195        use crate::wrapper::BoxedError;196        let error = BoxedError(error);197        let vtable = &ErrorVTable {198            object_drop: object_drop::<BoxedError>,199            object_ref: object_ref::<BoxedError>,200            #[cfg(anyhow_no_ptr_addr_of)]201            object_mut: object_mut::<BoxedError>,202            object_boxed: object_boxed::<BoxedError>,203            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,204            #[cfg(anyhow_no_ptr_addr_of)]205            object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,206            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,207            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]208            object_backtrace: no_backtrace,209        };210211        // Safety: BoxedError is repr(transparent) so it is okay for the vtable212        // to allow casting to Box<dyn StdError + Send + Sync>.213        unsafe { Error::construct(error, vtable, backtrace) }214    }215216    // Takes backtrace as argument rather than capturing it here so that the217    // user sees one fewer layer of wrapping noise in the backtrace.218    //219    // Unsafe because the given vtable must have sensible behavior on the error220    // value of type E.221    #[cold]222    unsafe fn construct<E>(223        error: E,224        vtable: &'static ErrorVTable,225        backtrace: Option<Backtrace>,226    ) -> Self227    where228        E: StdError + Send + Sync + 'static,229    {230        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {231            vtable,232            backtrace,233            _object: error,234        });235        // Erase the concrete type of E from the compile-time type system. This236        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to237        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the238        // result is a thin pointer. The necessary behavior for manipulating the239        // underlying ErrorImpl<E> is preserved in the vtable provided by the240        // caller rather than a builtin fat pointer vtable.241        let inner = Own::new(inner).cast::<ErrorImpl>();242        Error { inner }243    }244245    /// Wrap the error value with additional context.246    ///247    /// For attaching context to a `Result` as it is propagated, the248    /// [`Context`][crate::Context] extension trait may be more convenient than249    /// this function.250    ///251    /// The primary reason to use `error.context(...)` instead of252    /// `result.context(...)` via the `Context` trait would be if the context253    /// needs to depend on some data held by the underlying error:254    ///255    /// ```256    /// # use std::fmt::{self, Debug, Display};257    /// #258    /// # type T = ();259    /// #260    /// # impl std::error::Error for ParseError {}261    /// # impl Debug for ParseError {262    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {263    /// #         unimplemented!()264    /// #     }265    /// # }266    /// # impl Display for ParseError {267    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {268    /// #         unimplemented!()269    /// #     }270    /// # }271    /// #272    /// use anyhow::Result;273    /// use std::fs::File;274    /// use std::path::Path;275    ///276    /// struct ParseError {277    ///     line: usize,278    ///     column: usize,279    /// }280    ///281    /// fn parse_impl(file: File) -> Result<T, ParseError> {282    ///     # const IGNORE: &str = stringify! {283    ///     ...284    ///     # };285    ///     # unimplemented!()286    /// }287    ///288    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {289    ///     let file = File::open(&path)?;290    ///     parse_impl(file).map_err(|error| {291    ///         let context = format!(292    ///             "only the first {} lines of {} are valid",293    ///             error.line, path.as_ref().display(),294    ///         );295    ///         anyhow::Error::new(error).context(context)296    ///     })297    /// }298    /// ```299    #[cold]300    #[must_use]301    pub fn context<C>(self, context: C) -> Self302    where303        C: Display + Send + Sync + 'static,304    {305        let error: ContextError<C, Error> = ContextError {306            context,307            error: self,308        };309310        let vtable = &ErrorVTable {311            object_drop: object_drop::<ContextError<C, Error>>,312            object_ref: object_ref::<ContextError<C, Error>>,313            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]314            object_mut: object_mut::<ContextError<C, Error>>,315            object_boxed: object_boxed::<ContextError<C, Error>>,316            object_downcast: context_chain_downcast::<C>,317            #[cfg(anyhow_no_ptr_addr_of)]318            object_downcast_mut: context_chain_downcast_mut::<C>,319            object_drop_rest: context_chain_drop_rest::<C>,320            #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]321            object_backtrace: context_backtrace::<C>,322        };323324        // As the cause is anyhow::Error, we already have a backtrace for it.325        let backtrace = None;326327        // Safety: passing vtable that operates on the right type.328        unsafe { Error::construct(error, vtable, backtrace) }329    }330331    /// Get the backtrace for this Error.332    ///333    /// In order for the backtrace to be meaningful, one of the two environment334    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined335    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat336    /// expensive to capture in Rust, so we don't necessarily want to be337    /// capturing them all over the place all the time.338    ///339    /// - If you want panics and errors to both have backtraces, set340    ///   `RUST_BACKTRACE=1`;341    /// - If you want only errors to have backtraces, set342    ///   `RUST_LIB_BACKTRACE=1`;343    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and344    ///   `RUST_LIB_BACKTRACE=0`.345    ///346    /// # Stability347    ///348    /// Standard library backtraces are only available when using Rust ≥ 1.65.349    /// On older 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    #[cfg(any(backtrace, feature = "backtrace"))]358    #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]359    pub fn backtrace(&self) -> &impl_backtrace!() {360        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }361    }362363    /// An iterator of the chain of source errors contained by this Error.364    ///365    /// This iterator will visit every error in the cause chain of this error366    /// object, beginning with the error that this error object was created367    /// from.368    ///369    /// # Example370    ///371    /// ```372    /// use anyhow::Error;373    /// use std::io;374    ///375    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {376    ///     for cause in error.chain() {377    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {378    ///             return Some(io_error.kind());379    ///         }380    ///     }381    ///     None382    /// }383    /// ```384    #[cfg(feature = "std")]385    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]386    #[cold]387    pub fn chain(&self) -> Chain {388        unsafe { ErrorImpl::chain(self.inner.by_ref()) }389    }390391    /// The lowest level cause of this error &mdash; this error's cause's392    /// cause's cause etc.393    ///394    /// The root cause is the last error in the iterator produced by395    /// [`chain()`][Error::chain].396    #[cfg(feature = "std")]397    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]398    pub fn root_cause(&self) -> &(dyn StdError + 'static) {399        self.chain().last().unwrap()400    }401402    /// Returns true if `E` is the type held by this error object.403    ///404    /// For errors with context, this method returns true if `E` matches the405    /// type of the context `C` **or** the type of the error on which the406    /// context has been attached. For details about the interaction between407    /// context and downcasting, [see here].408    ///409    /// [see here]: trait.Context.html#effect-on-downcasting410    pub fn is<E>(&self) -> bool411    where412        E: Display + Debug + Send + Sync + 'static,413    {414        self.downcast_ref::<E>().is_some()415    }416417    /// Attempt to downcast the error object to a concrete type.418    pub fn downcast<E>(mut self) -> Result<E, Self>419    where420        E: Display + Debug + Send + Sync + 'static,421    {422        let target = TypeId::of::<E>();423        let inner = self.inner.by_mut();424        unsafe {425            // Use vtable to find NonNull<()> which points to a value of type E426            // somewhere inside the data structure.427            #[cfg(not(anyhow_no_ptr_addr_of))]428            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {429                Some(addr) => addr.by_mut().extend(),430                None => return Err(self),431            };432            #[cfg(anyhow_no_ptr_addr_of)]433            let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {434                Some(addr) => addr.extend(),435                None => return Err(self),436            };437438            // Prepare to read E out of the data structure. We'll drop the rest439            // of the data structure separately so that E is not dropped.440            let outer = ManuallyDrop::new(self);441442            // Read E from where the vtable found it.443            let error = addr.cast::<E>().read();444445            // Drop rest of the data structure outside of E.446            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);447448            Ok(error)449        }450    }451452    /// Downcast this error object by reference.453    ///454    /// # Example455    ///456    /// ```457    /// # use anyhow::anyhow;458    /// # use std::fmt::{self, Display};459    /// # use std::task::Poll;460    /// #461    /// # #[derive(Debug)]462    /// # enum DataStoreError {463    /// #     Censored(()),464    /// # }465    /// #466    /// # impl Display for DataStoreError {467    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {468    /// #         unimplemented!()469    /// #     }470    /// # }471    /// #472    /// # impl std::error::Error for DataStoreError {}473    /// #474    /// # const REDACTED_CONTENT: () = ();475    /// #476    /// # let error = anyhow!("...");477    /// # let root_cause = &error;478    /// #479    /// # let ret =480    /// // If the error was caused by redaction, then return a tombstone instead481    /// // of the content.482    /// match root_cause.downcast_ref::<DataStoreError>() {483    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),484    ///     None => Err(error),485    /// }486    /// # ;487    /// ```488    pub fn downcast_ref<E>(&self) -> Option<&E>489    where490        E: Display + Debug + Send + Sync + 'static,491    {492        let target = TypeId::of::<E>();493        unsafe {494            // Use vtable to find NonNull<()> which points to a value of type E495            // somewhere inside the data structure.496            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;497            Some(addr.cast::<E>().deref())498        }499    }500501    /// Downcast this error object by mutable reference.502    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>503    where504        E: Display + Debug + Send + Sync + 'static,505    {506        let target = TypeId::of::<E>();507        unsafe {508            // Use vtable to find NonNull<()> which points to a value of type E509            // somewhere inside the data structure.510511            #[cfg(not(anyhow_no_ptr_addr_of))]512            let addr =513                (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();514515            #[cfg(anyhow_no_ptr_addr_of)]516            let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;517518            Some(addr.cast::<E>().deref_mut())519        }520    }521522    #[cfg(error_generic_member_access)]523    pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {524        unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }525    }526527    // Called by thiserror when you have `#[source] anyhow::Error`. This provide528    // implementation includes the anyhow::Error's Backtrace if any, unlike529    // deref'ing to dyn Error where the provide implementation would include530    // only the original error's Backtrace from before it got wrapped into an531    // anyhow::Error.532    #[cfg(error_generic_member_access)]533    #[doc(hidden)]534    pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {535        Self::provide(self, request);536    }537}538539#[cfg(feature = "std")]540#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]541impl<E> From<E> for Error542where543    E: StdError + Send + Sync + 'static,544{545    #[cold]546    fn from(error: E) -> Self {547        let backtrace = backtrace_if_absent!(&error);548        Error::from_std(error, backtrace)549    }550}551552#[cfg(feature = "std")]553#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]554impl Deref for Error {555    type Target = dyn StdError + Send + Sync + 'static;556557    fn deref(&self) -> &Self::Target {558        unsafe { ErrorImpl::error(self.inner.by_ref()) }559    }560}561562#[cfg(feature = "std")]563#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]564impl DerefMut for Error {565    fn deref_mut(&mut self) -> &mut Self::Target {566        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }567    }568}569570impl Display for Error {571    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {572        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }573    }574}575576impl Debug for Error {577    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {578        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }579    }580}581582impl Drop for Error {583    fn drop(&mut self) {584        unsafe {585            // Invoke the vtable's drop behavior.586            (vtable(self.inner.ptr).object_drop)(self.inner);587        }588    }589}590591struct ErrorVTable {592    object_drop: unsafe fn(Own<ErrorImpl>),593    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,594    #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]595    object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),596    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,597    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,598    #[cfg(anyhow_no_ptr_addr_of)]599    object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,600    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),601    #[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]602    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,603}604605// Safety: requires layout of *e to match ErrorImpl<E>.606unsafe fn object_drop<E>(e: Own<ErrorImpl>) {607    // Cast back to ErrorImpl<E> so that the allocator receives the correct608    // Layout to deallocate the Box's memory.609    let unerased_own = e.cast::<ErrorImpl<E>>();610    drop(unsafe { unerased_own.boxed() });611}612613// Safety: requires layout of *e to match ErrorImpl<E>.614unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {615    // Drop the fields of ErrorImpl other than E as well as the Box allocation,616    // without dropping E itself. This is used by downcast after doing a617    // ptr::read to take ownership of the E.618    let _ = target;619    let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();620    drop(unsafe { unerased_own.boxed() });621}622623// Safety: requires layout of *e to match ErrorImpl<E>.624unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>625where626    E: StdError + Send + Sync + 'static,627{628    // Attach E's native StdError vtable onto a pointer to self._object.629630    let unerased_ref = e.cast::<ErrorImpl<E>>();631632    #[cfg(not(anyhow_no_ptr_addr_of))]633    return Ref::from_raw(unsafe {634        NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)635    });636637    #[cfg(anyhow_no_ptr_addr_of)]638    return Ref::new(unsafe { &unerased_ref.deref()._object });639}640641// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived642// from a `&mut`643#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]644unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)645where646    E: StdError + Send + Sync + 'static,647{648    // Attach E's native StdError vtable onto a pointer to self._object.649    let unerased_mut = e.cast::<ErrorImpl<E>>();650    unsafe { &mut unerased_mut.deref_mut()._object }651}652653// Safety: requires layout of *e to match ErrorImpl<E>.654unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>655where656    E: StdError + Send + Sync + 'static,657{658    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.659    let unerased_own = e.cast::<ErrorImpl<E>>();660    unsafe { unerased_own.boxed() }661}662663// Safety: requires layout of *e to match ErrorImpl<E>.664unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>665where666    E: 'static,667{668    if TypeId::of::<E>() == target {669        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a670        // pointer to its E field.671672        let unerased_ref = e.cast::<ErrorImpl<E>>();673674        #[cfg(not(anyhow_no_ptr_addr_of))]675        return Some(676            Ref::from_raw(unsafe {677                NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)678            })679            .cast::<()>(),680        );681682        #[cfg(anyhow_no_ptr_addr_of)]683        return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());684    } else {685        None686    }687}688689// Safety: requires layout of *e to match ErrorImpl<E>.690#[cfg(anyhow_no_ptr_addr_of)]691unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>692where693    E: 'static,694{695    if TypeId::of::<E>() == target {696        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a697        // pointer to its E field.698        let unerased_mut = e.cast::<ErrorImpl<E>>();699        let unerased = unsafe { unerased_mut.deref_mut() };700        Some(Mut::new(&mut unerased._object).cast::<()>())701    } else {702        None703    }704}705706#[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]707fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {708    let _ = e;709    None710}711712// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.713#[cfg(feature = "std")]714unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>715where716    C: 'static,717    E: 'static,718{719    if TypeId::of::<C>() == target {720        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();721        let unerased = unsafe { unerased_ref.deref() };722        Some(Ref::new(&unerased._object.context).cast::<()>())723    } else if TypeId::of::<E>() == target {724        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();725        let unerased = unsafe { unerased_ref.deref() };726        Some(Ref::new(&unerased._object.error).cast::<()>())727    } else {728        None729    }730}731732// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.733#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]734unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>735where736    C: 'static,737    E: 'static,738{739    if TypeId::of::<C>() == target {740        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();741        let unerased = unsafe { unerased_mut.deref_mut() };742        Some(Mut::new(&mut unerased._object.context).cast::<()>())743    } else if TypeId::of::<E>() == target {744        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();745        let unerased = unsafe { unerased_mut.deref_mut() };746        Some(Mut::new(&mut unerased._object.error).cast::<()>())747    } else {748        None749    }750}751752// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.753#[cfg(feature = "std")]754unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)755where756    C: 'static,757    E: 'static,758{759    // Called after downcasting by value to either the C or the E and doing a760    // ptr::read to take ownership of that value.761    if TypeId::of::<C>() == target {762        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();763        drop(unsafe { unerased_own.boxed() });764    } else {765        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();766        drop(unsafe { unerased_own.boxed() });767    }768}769770// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.771unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>772where773    C: 'static,774{775    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();776    let unerased = unsafe { unerased_ref.deref() };777    if TypeId::of::<C>() == target {778        Some(Ref::new(&unerased._object.context).cast::<()>())779    } else {780        // Recurse down the context chain per the inner error's vtable.781        let source = &unerased._object.error;782        unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }783    }784}785786// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.787#[cfg(anyhow_no_ptr_addr_of)]788unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>789where790    C: 'static,791{792    let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();793    let unerased = unsafe { unerased_mut.deref_mut() };794    if TypeId::of::<C>() == target {795        Some(Mut::new(&mut unerased._object.context).cast::<()>())796    } else {797        // Recurse down the context chain per the inner error's vtable.798        let source = &mut unerased._object.error;799        unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }800    }801}802803// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.804unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)805where806    C: 'static,807{808    // Called after downcasting by value to either the C or one of the causes809    // and doing a ptr::read to take ownership of that value.810    if TypeId::of::<C>() == target {811        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();812        // Drop the entire rest of the data structure rooted in the next Error.813        drop(unsafe { unerased_own.boxed() });814    } else {815        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();816        let unerased = unsafe { unerased_own.boxed() };817        // Read the Own<ErrorImpl> from the next error.818        let inner = unerased._object.error.inner;819        drop(unerased);820        let vtable = unsafe { vtable(inner.ptr) };821        // Recursively drop the next error using the same target typeid.822        unsafe { (vtable.object_drop_rest)(inner, target) };823    }824}825826// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.827#[cfg(all(not(error_generic_member_access), any(backtrace, feature = "backtrace")))]828#[allow(clippy::unnecessary_wraps)]829unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>830where831    C: 'static,832{833    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();834    let unerased = unsafe { unerased_ref.deref() };835    let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };836    Some(backtrace)837}838839// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor840// of raw pointers and `NonNull`.841// repr C to ensure that E remains in the final position.842#[repr(C)]843pub(crate) struct ErrorImpl<E = ()> {844    vtable: &'static ErrorVTable,845    backtrace: Option<Backtrace>,846    // NOTE: Don't use directly. Use only through vtable. Erased type may have847    // different alignment.848    _object: E,849}850851// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but852// avoids converting `p` into a reference.853unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {854    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.855    unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }856}857858// repr C to ensure that ContextError<C, E> has the same layout as859// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.860#[repr(C)]861pub(crate) struct ContextError<C, E> {862    pub context: C,863    pub error: E,864}865866impl<E> ErrorImpl<E> {867    fn erase(&self) -> Ref<ErrorImpl> {868        // Erase the concrete type of E but preserve the vtable in self.vtable869        // for manipulating the resulting thin pointer. This is analogous to an870        // unsize coercion.871        Ref::new(self).cast::<ErrorImpl>()872    }873}874875impl ErrorImpl {876    pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {877        // Use vtable to attach E's native StdError vtable for the right878        // original type E.879        unsafe { (vtable(this.ptr).object_ref)(this).deref() }880    }881882    #[cfg(feature = "std")]883    pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {884        // Use vtable to attach E's native StdError vtable for the right885        // original type E.886887        #[cfg(not(anyhow_no_ptr_addr_of))]888        return unsafe {889            (vtable(this.ptr).object_ref)(this.by_ref())890                .by_mut()891                .deref_mut()892        };893894        #[cfg(anyhow_no_ptr_addr_of)]895        return unsafe { (vtable(this.ptr).object_mut)(this) };896    }897898    #[cfg(any(backtrace, feature = "backtrace"))]899    pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {900        // This unwrap can only panic if the underlying error's backtrace method901        // is nondeterministic, which would only happen in maliciously902        // constructed code.903        unsafe { this.deref() }904            .backtrace905            .as_ref()906            .or_else(|| {907                #[cfg(error_generic_member_access)]908                return error::request_ref::<Backtrace>(unsafe { Self::error(this) });909                #[cfg(not(error_generic_member_access))]910                return unsafe { (vtable(this.ptr).object_backtrace)(this) };911            })912            .expect("backtrace capture failed")913    }914915    #[cfg(error_generic_member_access)]916    unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {917        if let Some(backtrace) = unsafe { &this.deref().backtrace } {918            request.provide_ref(backtrace);919        }920        unsafe { Self::error(this) }.provide(request);921    }922923    #[cold]924    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {925        Chain::new(unsafe { Self::error(this) })926    }927}928929impl<E> StdError for ErrorImpl<E>930where931    E: StdError,932{933    fn source(&self) -> Option<&(dyn StdError + 'static)> {934        unsafe { ErrorImpl::error(self.erase()).source() }935    }936937    #[cfg(error_generic_member_access)]938    fn provide<'a>(&'a self, request: &mut Request<'a>) {939        unsafe { ErrorImpl::provide(self.erase(), request) }940    }941}942943impl<E> Debug for ErrorImpl<E>944where945    E: Debug,946{947    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {948        unsafe { ErrorImpl::debug(self.erase(), formatter) }949    }950}951952impl<E> Display for ErrorImpl<E>953where954    E: Display,955{956    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {957        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }958    }959}960961impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {962    #[cold]963    fn from(error: Error) -> Self {964        let outer = ManuallyDrop::new(error);965        unsafe {966            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for967            // the right original type E.968            (vtable(outer.inner.ptr).object_boxed)(outer.inner)969        }970    }971}972973impl From<Error> for Box<dyn StdError + Send + 'static> {974    fn from(error: Error) -> Self {975        Box::<dyn StdError + Send + Sync>::from(error)976    }977}978979impl From<Error> for Box<dyn StdError + 'static> {980    fn from(error: Error) -> Self {981        Box::<dyn StdError + Send + Sync>::from(error)982    }983}984985#[cfg(feature = "std")]986impl AsRef<dyn StdError + Send + Sync> for Error {987    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {988        &**self989    }990}991992#[cfg(feature = "std")]993impl AsRef<dyn StdError> for Error {994    fn as_ref(&self) -> &(dyn StdError + 'static) {995        &**self996    }997}