Merge pull request #34 from dtolnay/context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Support downcasting errors with context to C *or* E
authored by David Tolnay · committed by GitHub · parents 5e04e77, 61ad446 · Browse files · 3 files·+387 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+387 added−51 removed
- tests:+150 added−1 removed
- other:+237 added−50 removed
Provenance
- Commit
8fcd8d0- Tree
aa5ed3b- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5e04e77- Parent 2
61ad446
3 files changed+387 added−51 removed
modified:src/error.rs+141 added-50 removed
3 unmodified lines4 use std::error::Error as StdError;5 use std::fmt::{self, Debug, Display};6 use std::mem::{self, ManuallyDrop};7 use std::ops::{Deref, DerefMut};8-use std::ptr;8+use std::ptr::{self, NonNull};9 10 impl Error {11 /// Create a new error object from any error type.12 ///15 unmodified lines28 E: StdError + Send + Sync + 'static,29 {30 let vtable = &ErrorVTable {31 object_drop: object_drop::<E>,32- object_drop_front: object_drop_front::<E>,32 object_ref: object_ref::<E>,33 object_mut: object_mut::<E>,34 object_boxed: object_boxed::<E>,36- object_is: object_is::<E>,35+ object_downcast: object_downcast::<E>,36+ object_drop_rest: object_drop_front::<E>,37 };38 39 // Safety: passing vtable that operates on the right type E.40 unsafe { Error::construct(error, vtable, backtrace) }5 unmodified lines46 {47 let error: MessageError<M> = MessageError(message);48 let vtable = &ErrorVTable {49 object_drop: object_drop::<MessageError<M>>,50- object_drop_front: object_drop_front::<MessageError<M>>,50 object_ref: object_ref::<MessageError<M>>,51 object_mut: object_mut::<MessageError<M>>,52 object_boxed: object_boxed::<MessageError<M>>,54- object_is: object_is::<M>,53+ object_downcast: object_downcast::<M>,54+ object_drop_rest: object_drop_front::<M>,55 };56 57 // Safety: MessageError is repr(transparent) so it is okay for the58 // vtable to allow casting the MessageError<M> to M.6 unmodified lines65 {66 let error: DisplayError<M> = DisplayError(message);67 let vtable = &ErrorVTable {68 object_drop: object_drop::<DisplayError<M>>,69- object_drop_front: object_drop_front::<DisplayError<M>>,69 object_ref: object_ref::<DisplayError<M>>,70 object_mut: object_mut::<DisplayError<M>>,71 object_boxed: object_boxed::<DisplayError<M>>,73- object_is: object_is::<M>,72+ object_downcast: object_downcast::<M>,73+ object_drop_rest: object_drop_front::<M>,74 };75 76 // Safety: DisplayError is repr(transparent) so it is okay for the77 // vtable to allow casting the DisplayError<M> to M.8 unmodified lines86 let error: ContextError<C, E> = ContextError { context, error };87 88 let vtable = &ErrorVTable {89 object_drop: object_drop::<ContextError<C, E>>,90- object_drop_front: object_drop_front::<ContextError<C, E>>,90 object_ref: object_ref::<ContextError<C, E>>,91 object_mut: object_mut::<ContextError<C, E>>,92 object_boxed: object_boxed::<ContextError<C, E>>,94- object_is: object_is::<ContextError<C, E>>,93+ object_downcast: context_downcast::<C, E>,94+ object_drop_rest: context_drop_rest::<C, E>,95 };96 97 // Safety: passing vtable that operates on the right type.98 unsafe { Error::construct(error, vtable, backtrace) }14 unmodified lines113 {114 let inner = Box::new(ErrorImpl {115 vtable,116 backtrace,117- _error: error,117+ _object: error,118 });119 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);120 let inner = ManuallyDrop::new(erased);121 Error { inner }63 unmodified lines185 };186 187 let vtable = &ErrorVTable {188 object_drop: object_drop::<ContextError<C, Error>>,189- object_drop_front: object_drop_front::<ContextError<C, Error>>,189 object_ref: object_ref::<ContextError<C, Error>>,190 object_mut: object_mut::<ContextError<C, Error>>,191 object_boxed: object_boxed::<ContextError<C, Error>>,193- object_is: object_is::<ContextError<C, Error>>,192+ object_downcast: context_chain_downcast::<C>,193+ object_drop_rest: context_chain_drop_rest::<C>,194 };195 196 // As the cause is anyhow::Error, we already have a backtrace for it.197 let backtrace = None;56 unmodified lines254 }255 root_cause256 }257 258- /// Returns `true` if `E` is the type wrapped by this error object.258+ /// Returns true if `E` is the type held by this error object.259+ ///260+ /// For errors with context, this method returns true if `E` matches the261+ /// type of the context `C` **or** the type of the error on which the262+ /// context has been attached. For details about the interaction between263+ /// context and downcasting, [see here].264+ ///265+ /// [see here]: trait.Context.html#effect-on-downcasting266 pub fn is<E>(&self) -> bool267 where268 E: Display + Debug + Send + Sync + 'static,269 {263- let target = TypeId::of::<E>();264- unsafe { (self.inner.vtable.object_is)(target) }270+ self.downcast_ref::<E>().is_some()271 }272 273 /// Attempt to downcast the error object to a concrete type.274 pub fn downcast<E>(self) -> Result<E, Self>275 where276 E: Display + Debug + Send + Sync + 'static,277 {272- if self.is::<E>() {278+ let target = TypeId::of::<E>();279+ unsafe {280+ let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {281+ Some(addr) => addr,282+ None => return Err(self),283+ };284 let outer = ManuallyDrop::new(self);274- unsafe {275- let error = ptr::read(276- outer.inner.error() as *const (dyn StdError + Send + Sync) as *const E277- );278- let inner = ptr::read(&outer.inner);279- let erased = ManuallyDrop::into_inner(inner);280- (erased.vtable.object_drop_front)(erased);281- Ok(error)285+ let error = ptr::read(addr.cast::<E>().as_ptr());286+ let inner = ptr::read(&outer.inner);287+ let erased = ManuallyDrop::into_inner(inner);288+ (erased.vtable.object_drop_rest)(erased, target);289+ Ok(error)282- }283- } else {284- Err(self)290 }291 }292 293 /// Downcast this error object by reference.35 unmodified lines329 pub fn downcast_ref<E>(&self) -> Option<&E>330 where331 E: Display + Debug + Send + Sync + 'static,332 {328- if self.is::<E>() {329- Some(unsafe {330- &*(self.inner.error() as *const (dyn StdError + Send + Sync) as *const E)331- })332- } else {333- None333+ let target = TypeId::of::<E>();334+ unsafe {335+ let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;336+ Some(&*addr.cast::<E>().as_ptr())337 }338 }339 340 /// Downcast this error object by mutable reference.341 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>342 where343 E: Display + Debug + Send + Sync + 'static,344 {342- if self.is::<E>() {343- Some(unsafe {344- &mut *(self.inner.error_mut() as *mut (dyn StdError + Send + Sync) as *mut E)345- })346- } else {347- None345+ let target = TypeId::of::<E>();346+ unsafe {347+ let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;348+ Some(&mut *addr.cast::<E>().as_ptr())349 }350 }351 }352 47 unmodified lines400 }401 402 struct ErrorVTable {403 object_drop: unsafe fn(Box<ErrorImpl<()>>),403- object_drop_front: unsafe fn(Box<ErrorImpl<()>>),404 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),405 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),406 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,407- object_is: unsafe fn(TypeId) -> bool,407+ object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,408+ object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),409 }410 411 unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {412 // Cast back to ErrorImpl<E> so that the allocator receives the correct1 unmodified line414 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);415 drop(unerased);416 }417 417-unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {418+unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {419 // Drop the fields of ErrorImpl other than E as well as the Box allocation,420 // without dropping E itself. This is used by downcast after doing a421 // ptr::read to take ownership of the E.422+ let _ = target;423 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);424 drop(unerased);425 }426 427 unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)428 where429 E: StdError + Send + Sync + 'static,430 {429- &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._error431+ &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object432 }433 434 unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)435 where436 E: StdError + Send + Sync + 'static,437 {436- &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._error438+ &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object439 }440 441 unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>442 where1 unmodified line444 {445 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)446 }447 446-unsafe fn object_is<T>(target: TypeId) -> bool448+unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>449 where448- T: 'static,450+ E: 'static,451 {450- TypeId::of::<T>() == target452+ if TypeId::of::<E>() == target {453+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;454+ let addr = &(*unerased)._object as *const E as *mut ();455+ Some(NonNull::new_unchecked(addr))456+ } else {457+ None458+ }459 }460 453-// repr C to ensure that `E` remains in the final position461+unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>462+where463+ C: 'static,464+ E: 'static,465+{466+ if TypeId::of::<C>() == target {467+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;468+ let addr = &(*unerased)._object.context as *const C as *mut ();469+ Some(NonNull::new_unchecked(addr))470+ } else if TypeId::of::<E>() == target {471+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;472+ let addr = &(*unerased)._object.error as *const E as *mut ();473+ Some(NonNull::new_unchecked(addr))474+ } else {475+ None476+ }477+}478+479+unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)480+where481+ C: 'static,482+ E: 'static,483+{484+ // Called after downcasting by value to either the C or the E and doing a485+ // ptr::read to take ownership of that value.486+ if TypeId::of::<C>() == target {487+ let unerased = mem::transmute::<488+ Box<ErrorImpl<()>>,489+ Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,490+ >(e);491+ drop(unerased);492+ } else {493+ let unerased = mem::transmute::<494+ Box<ErrorImpl<()>>,495+ Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,496+ >(e);497+ drop(unerased);498+ }499+}500+501+unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>502+where503+ C: 'static,504+{505+ if TypeId::of::<C>() == target {506+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;507+ let addr = &(*unerased)._object.context as *const C as *mut ();508+ Some(NonNull::new_unchecked(addr))509+ } else {510+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;511+ let source = &(*unerased)._object.error;512+ (source.inner.vtable.object_downcast)(&source.inner, target)513+ }514+}515+516+unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)517+where518+ C: 'static,519+{520+ // Called after downcasting by value to either the C or one of the causes521+ // and doing a ptr::read to take ownership of that value.522+ if TypeId::of::<C>() == target {523+ let unerased = mem::transmute::<524+ Box<ErrorImpl<()>>,525+ Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,526+ >(e);527+ drop(unerased);528+ } else {529+ let unerased = mem::transmute::<530+ Box<ErrorImpl<()>>,531+ Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,532+ >(e);533+ let inner = ptr::read(&unerased._object.error.inner);534+ drop(unerased);535+ let erased = ManuallyDrop::into_inner(inner);536+ (erased.vtable.object_drop_rest)(erased, target);537+ }538+}539+540+// repr C to ensure that E remains in the final position.541 #[repr(C)]542 pub(crate) struct ErrorImpl<E> {543 vtable: &'static ErrorVTable,544 backtrace: Option<Backtrace>,458- // NOTE: Don't use directly. Use only through vtable. Erased type may have different alignment.459- _error: E,545+ // NOTE: Don't use directly. Use only through vtable. Erased type may have546+ // different alignment.547+ _object: E,548 }549 550+// repr C to ensure that ContextError<C, E> has the same layout as551+// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.552+#[repr(C)]553 pub(crate) struct ContextError<C, E> {554 pub context: C,555 pub error: E,556 }175 unmodified linesmodified:src/lib.rs+96 added
284 unmodified lines285 ///286 /// This trait is sealed and cannot be implemented for types outside of287 /// `anyhow`.288 ///289+/// <br>290+///291 /// # Example292 ///293 /// ```294 /// use anyhow::{Context, Result};32 unmodified lines327 ///328 /// Caused by:329 /// No such file or directory (os error 2)330 /// ```331+///332+/// <br>333+///334+/// # Effect on downcasting335+///336+/// After attaching context of type `C` onto an error of type `E`, the resulting337+/// `anyhow::Error` may be downcast to `C` **or** to `E`.338+///339+/// That is, in codebases that rely on downcasting, Anyhow's context supports340+/// both of the following use cases:341+///342+/// - **Attaching context whose type is insignificant onto errors whose type343+/// is used in downcasts.**344+///345+/// In other error libraries whose context is not designed this way, it can346+/// be risky to introduce context to existing code because new context might347+/// break existing working downcasts. In Anyhow, any downcast that worked348+/// before adding context will continue to work after you add a context, so349+/// you should freely add human-readable context to errors wherever it would350+/// be helpful.351+///352+/// ```353+/// # use anyhow::bail;354+/// # use thiserror::Error;355+/// #356+/// # #[derive(Error, Debug)]357+/// # #[error("???")]358+/// # struct SuspiciousError;359+/// #360+/// # fn helper() -> Result<()> {361+/// # bail!(SuspiciousError);362+/// # }363+/// #364+/// use anyhow::{Context, Result};365+///366+/// fn do_it() -> Result<()> {367+/// helper().context("failed to complete the work")?;368+/// # const IGNORE: &str = stringify! {369+/// ...370+/// # };371+/// # unreachable!()372+/// }373+///374+/// fn main() {375+/// let err = do_it().unwrap_err();376+/// if let Some(e) = err.downcast_ref::<SuspiciousError>() {377+/// // If helper() returned SuspiciousError, this downcast will378+/// // correctly succeed even with the context in between.379+/// # return;380+/// }381+/// # panic!("expected downcast to succeed");382+/// }383+/// ```384+///385+/// - **Attaching context whose type is used in downcasts onto errors whose386+/// type is insignificant.**387+///388+/// Some codebases prefer to use machine-readable context to categorize389+/// lower level errors in a way that will be actionable to higher levels of390+/// the application.391+///392+/// ```393+/// # use anyhow::bail;394+/// # use thiserror::Error;395+/// #396+/// # #[derive(Error, Debug)]397+/// # #[error("???")]398+/// # struct HelperFailed;399+/// #400+/// # fn helper() -> Result<()> {401+/// # bail!("no such file or directory");402+/// # }403+/// #404+/// use anyhow::{Context, Result};405+///406+/// fn do_it() -> Result<()> {407+/// helper().context(HelperFailed)?;408+/// # const IGNORE: &str = stringify! {409+/// ...410+/// # };411+/// # unreachable!()412+/// }413+///414+/// fn main() {415+/// let err = do_it().unwrap_err();416+/// if let Some(e) = err.downcast_ref::<HelperFailed>() {417+/// // If helper failed, this downcast will succeed because418+/// // HelperFailed is the context that has been attached to419+/// // that error.420+/// # return;421+/// }422+/// # panic!("expected downcast to succeed");423+/// }424+/// ```425 pub trait Context<T, E>: context::private::Sealed {426 /// Wrap the error value with additional context.427 fn context<C>(self, context: C) -> Result<T, Error>428 where28 unmodified linesmodified:tests/test_context.rs+150 added-1 removed
1-use anyhow::{Context, Result};1+mod drop;2 3+use crate::drop::{DetectDrop, Flag};4+use anyhow::{Context, Error, Result};5+use std::fmt::{self, Display};6+use thiserror::Error;7+8 // https://github.com/dtolnay/anyhow/issues/189 #[test]10 fn test_inference() -> Result<()> {11 let x = "1";12 let y: u32 = x.parse().context("...")?;13 assert_eq!(y, 1);14 Ok(())15 }16+17+macro_rules! context_type {18+ ($name:ident) => {19+ #[derive(Debug)]20+ struct $name {21+ message: &'static str,22+ drop: DetectDrop,23+ }24+25+ impl Display for $name {26+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {27+ f.write_str(self.message)28+ }29+ }30+ };31+}32+33+context_type!(HighLevel);34+context_type!(MidLevel);35+36+#[derive(Error, Debug)]37+#[error("{message}")]38+struct LowLevel {39+ message: &'static str,40+ drop: DetectDrop,41+}42+43+struct Dropped {44+ low: Flag,45+ mid: Flag,46+ high: Flag,47+}48+49+impl Dropped {50+ fn none(&self) -> bool {51+ !self.low.get() && !self.mid.get() && !self.high.get()52+ }53+54+ fn all(&self) -> bool {55+ self.low.get() && self.mid.get() && self.high.get()56+ }57+}58+59+fn make_chain() -> (Error, Dropped) {60+ let dropped = Dropped {61+ low: Flag::new(),62+ mid: Flag::new(),63+ high: Flag::new(),64+ };65+66+ let low = LowLevel {67+ message: "no such file or directory",68+ drop: DetectDrop::new(&dropped.low),69+ };70+71+ // impl Context for Result<T, E>72+ let mid = Err::<(), LowLevel>(low)73+ .context(MidLevel {74+ message: "failed to load config",75+ drop: DetectDrop::new(&dropped.mid),76+ })77+ .unwrap_err();78+79+ // impl Context for Result<T, Error>80+ let high = Err::<(), Error>(mid)81+ .context(HighLevel {82+ message: "failed to start server",83+ drop: DetectDrop::new(&dropped.high),84+ })85+ .unwrap_err();86+87+ (high, dropped)88+}89+90+#[test]91+fn test_downcast_ref() {92+ let (err, dropped) = make_chain();93+94+ assert!(!err.is::<String>());95+ assert!(err.downcast_ref::<String>().is_none());96+97+ assert!(err.is::<HighLevel>());98+ let high = err.downcast_ref::<HighLevel>().unwrap();99+ assert_eq!(high.to_string(), "failed to start server");100+101+ assert!(err.is::<MidLevel>());102+ let mid = err.downcast_ref::<MidLevel>().unwrap();103+ assert_eq!(mid.to_string(), "failed to load config");104+105+ assert!(err.is::<LowLevel>());106+ let low = err.downcast_ref::<LowLevel>().unwrap();107+ assert_eq!(low.to_string(), "no such file or directory");108+109+ assert!(dropped.none());110+ drop(err);111+ assert!(dropped.all());112+}113+114+#[test]115+fn test_downcast_high() {116+ let (err, dropped) = make_chain();117+118+ let err = err.downcast::<HighLevel>().unwrap();119+ assert!(!dropped.high.get());120+ assert!(dropped.low.get() && dropped.mid.get());121+122+ drop(err);123+ assert!(dropped.all());124+}125+126+#[test]127+fn test_downcast_mid() {128+ let (err, dropped) = make_chain();129+130+ let err = err.downcast::<MidLevel>().unwrap();131+ assert!(!dropped.mid.get());132+ assert!(dropped.low.get() && dropped.high.get());133+134+ drop(err);135+ assert!(dropped.all());136+}137+138+#[test]139+fn test_downcast_low() {140+ let (err, dropped) = make_chain();141+142+ let err = err.downcast::<LowLevel>().unwrap();143+ assert!(!dropped.low.get());144+ assert!(dropped.mid.get() && dropped.high.get());145+146+ drop(err);147+ assert!(dropped.all());148+}149+150+#[test]151+fn test_unsuccessful_downcast() {152+ let (err, dropped) = make_chain();153+154+ let err = err.downcast::<String>().unwrap_err();155+ assert!(dropped.none());156+157+ drop(err);158+ assert!(dropped.all());159+}