Import implementation from fehler 1.0.0-alpha.1
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Tolnay · committed by David Tolnay · parent 7f711bb · Browse files · 4 files·+453 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+453 added−0 removed
- other:+453 added−0 removed
Provenance
- Commit
727f36f- Tree
21eedf5- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
7f711bb
4 files changed+453 added−0 removed
added:src/as_error.rs+27 added
1+use std::error::Error;2+3+use crate::Exception;4+5+/// View type as an error object.6+pub trait AsError {7+ /// View type as an error object.8+ fn as_error(&self) -> &(dyn Error + Send + Sync + 'static);9+}10+11+impl<T: Error + Send + Sync + 'static> AsError for T {12+ fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {13+ self14+ }15+}16+17+impl AsError for dyn Error + Send + Sync + 'static {18+ fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {19+ self20+ }21+}22+23+impl AsError for Exception {24+ fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {25+ &**self26+ }27+}added:src/context.rs+87 added
1+use std::backtrace::Backtrace;2+use std::fmt::{self, Debug, Display};3+use std::error::Error;4+5+use crate::Exception;6+7+/// Provides the `context` method for `Result`.8+pub trait Context<T, E> {9+ /// Wrap the error value with additional context.10+ fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception>;11+12+ /// Wrap the error value with additional context lazily.13+ fn with_context<C, F>(self, f: F) -> Result<T, Exception> where14+ C: Display + Send + Sync + 'static,15+ F: FnOnce(&E) -> C;16+}17+18+impl<T, E: Error + Send + Sync + 'static> Context<T, E> for Result<T, E> {19+ fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {20+ self.map_err(|error| Exception::from(ContextError { error, context }))21+ }22+23+ fn with_context<C, F>(self, f: F) -> Result<T, Exception> where24+ C: Display + Send + Sync + 'static,25+ F: FnOnce(&E) -> C26+ {27+ self.map_err(|error| Exception::from(ContextError { context: f(&error), error }))28+ }29+}30+31+impl<T> Context<T, Exception> for Result<T, Exception> {32+ fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {33+ self.map_err(|error| Exception::from(ContextError { error, context }))34+ }35+36+ fn with_context<C, F>(self, f: F) -> Result<T, Exception> where37+ C: Display + Send + Sync + 'static,38+ F: FnOnce(&Exception) -> C39+ {40+ self.map_err(|error| Exception::from(ContextError { context: f(&error), error }))41+ }42+}43+44+struct ContextError<E, C> {45+ error: E,46+ context: C,47+}48+49+impl<E: Debug, C: Display> Debug for ContextError<E, C> {50+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {51+ write!(f, "{:?}\n\n{}", self.error, self.context)52+ }53+}54+55+impl<E, C: Display> Display for ContextError<E, C> {56+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {57+ Display::fmt(&self.context, f)58+ }59+}60+61+impl<E: Error + 'static, C: Display> Error for ContextError<E, C> {62+ fn backtrace(&self) -> Option<&Backtrace> {63+ self.error.backtrace()64+ }65+66+ fn cause(&self) -> Option<&dyn Error> {67+ Some(&self.error)68+ }69+70+ fn source(&self) -> Option<&(dyn Error + 'static)> {71+ Some(&self.error)72+ }73+}74+75+impl<C: Display> Error for ContextError<Exception, C> {76+ fn backtrace(&self) -> Option<&Backtrace> {77+ Some(self.error.backtrace())78+ }79+80+ fn cause(&self) -> Option<&dyn Error> {81+ Some(&*self.error)82+ }83+84+ fn source(&self) -> Option<&(dyn Error + 'static)> {85+ Some(&*self.error)86+ }87+}added:src/exception.rs+293 added
1+use std::any::TypeId;2+use std::backtrace::{Backtrace, BacktraceStatus};3+use std::error::Error;4+use std::fmt::{self, Debug, Display};5+use std::mem;6+use std::ops::{Deref, DerefMut};7+use std::ptr;8+9+/// The `Exception type, a wrapper around a dynamic error type.10+///11+/// `Exception` functions a lot like `Box<dyn Error>`, with these differences:12+///13+/// - `Exception` requires that the error is `Send`, `Sync`, and `'static`14+/// - `Exception` guarantees that a backtrace will exist, even if the error type15+/// did not provide one16+/// - `Exception` is represented as a narrow pointer - exactly one word in size,17+/// instead of two.18+pub struct Exception {19+ inner: Box<InnerException<()>>,20+}21+22+impl Exception {23+ /// Create a new exception from any error type.24+ ///25+ /// The error type must be threadsafe and `'static`, so that the `Exception` will be as well.26+ ///27+ /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28+ /// that a backtrace exists.29+ pub fn new<E>(error: E) -> Exception where30+ E: Error + Send + Sync + 'static31+ {32+ Exception::construct(error, TypeId::of::<E>())33+ }34+35+ #[doc(hidden)]36+ pub fn new_adhoc<M>(message: M) -> Exception where37+ M: Display + Debug + Send + Sync + 'static38+ {39+ Exception::construct(MessageError(message), TypeId::of::<M>())40+ }41+42+ fn construct<E>(error: E, type_id: TypeId) -> Exception where43+ E: Error + Send + Sync + 'static,44+ {45+ unsafe {46+ let backtrace = match error.backtrace() {47+ Some(_) => None,48+ None => Some(Backtrace::capture()),49+ };50+ let obj: TraitObject = mem::transmute(&error as &dyn Error);51+ let vtable = obj.vtable;52+ let inner = InnerException { vtable, type_id, backtrace, error };53+ Exception {54+ inner: mem::transmute(Box::new(inner))55+ }56+ }57+ }58+59+ /// View this exception as the underlying error.60+ pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {61+ &**self62+ }63+64+ /// View this exception as the underlying error, mutably.65+ pub fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {66+ &mut **self67+ }68+69+ /// Get the backtrace for this Exception.70+ pub fn backtrace(&self) -> &Backtrace {71+ // NB: this unwrap can only fail if the underlying error's backtrace method is72+ // nondeterministic, which would only happen in maliciously constructed code73+ self.inner.backtrace.as_ref().or_else(|| self.inner.error().backtrace())74+ .expect("exception backtrace capture failed")75+ }76+77+ /// An iterator of errors contained by this Exception.78+ ///79+ /// This iterator will visit every error in the "cause chain" of this exception, beginning with80+ /// the error that this exception was created from.81+ pub fn errors(&self) -> Errors<'_> {82+ Errors { next: Some(self.inner.error()) }83+ }84+85+ /// Returns `true` if `E` is the type wrapped by this exception.86+ pub fn is<E: Display + Debug + Send + Sync + 'static>(&self) -> bool {87+ TypeId::of::<E>() == self.inner.type_id88+ }89+90+ /// Attempt to downcast the exception to a concrete type.91+ pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Exception> {92+ if let Some(error) = self.downcast_ref::<E>() {93+ unsafe {94+ let error = ptr::read(error);95+ drop(ptr::read(&self.inner));96+ mem::forget(self);97+ Ok(error)98+ }99+ } else {100+ Err(self)101+ }102+ }103+104+ /// Downcast this exception by reference.105+ pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {106+ if self.is::<E>() {107+ unsafe { Some(&*(self.inner.error() as *const dyn Error as *const E)) }108+ } else { None }109+ }110+111+ /// Downcast this exception by mutable reference.112+ pub fn downcast_mut<E: Display + Debug + Send + Sync + 'static>(&mut self) -> Option<&mut E> {113+ if self.is::<E>() {114+ unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }115+ } else { None }116+ }117+}118+119+impl<E: Error + Send + Sync + 'static> From<E> for Exception {120+ fn from(error: E) -> Exception {121+ Exception::new(error)122+ }123+}124+125+impl Deref for Exception {126+ type Target = dyn Error + Send + Sync + 'static;127+ fn deref(&self) -> &Self::Target {128+ self.inner.error()129+ }130+}131+132+impl DerefMut for Exception {133+ fn deref_mut(&mut self) -> &mut Self::Target {134+ self.inner.error_mut()135+ }136+}137+138+impl Debug for Exception {139+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {140+ writeln!(f, "{}", self.inner.error())?;141+142+ let mut errors = self.errors().skip(1).enumerate();143+144+ if let Some((n, error)) = errors.next() {145+ writeln!(f, "\ncaused by:")?;146+ writeln!(f, "\t{}: {}", n, error)?;147+ for (n, error) in errors {148+ writeln!(f, "\t{}: {}", n, error)?;149+ }150+ }151+152+ let backtrace = self.backtrace();153+154+ match backtrace.status() {155+ BacktraceStatus::Captured => {156+ writeln!(f, "\n{}", backtrace)?;157+ }158+ BacktraceStatus::Disabled => {159+ writeln!(f, "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \160+ to display a backtrace")?;161+ }162+ _ => { }163+ }164+165+ Ok(())166+ }167+}168+169+impl Display for Exception {170+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {171+ write!(f, "{}", self.inner.error())172+ }173+}174+175+unsafe impl Send for Exception { }176+unsafe impl Sync for Exception { }177+178+impl Drop for Exception {179+ fn drop(&mut self) {180+ unsafe { ptr::drop_in_place(self.inner.error_mut()) }181+ }182+}183+184+// repr C to ensure that `E` remains in the final position185+#[repr(C)]186+struct InnerException<E> {187+ vtable: *const (),188+ type_id: TypeId,189+ backtrace: Option<Backtrace>,190+ error: E,191+}192+193+// repr C to ensure that transmuting from trait objects is safe194+#[repr(C)]195+struct TraitObject {196+ data: *const (),197+ vtable: *const (),198+}199+200+#[repr(transparent)]201+struct MessageError<M: Display + Debug>(M);202+203+impl<M: Display + Debug> Debug for MessageError<M> {204+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {205+ Debug::fmt(&self.0, f)206+ }207+}208+209+impl<M: Display + Debug> Display for MessageError<M> {210+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {211+ Display::fmt(&self.0, f)212+ }213+}214+215+impl<M: Display + Debug + 'static> Error for MessageError<M> { }216+217+impl InnerException<()> {218+ fn error(&self) -> &(dyn Error + Send + Sync + 'static) {219+ unsafe {220+ mem::transmute(TraitObject {221+ data: &self.error,222+ vtable: self.vtable,223+ })224+ }225+ }226+227+ fn error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {228+ unsafe {229+ mem::transmute(TraitObject {230+ data: &mut self.error,231+ vtable: self.vtable,232+ })233+ }234+ }235+}236+237+/// Iterator of errors in an `Exception`.238+pub struct Errors<'a> {239+ next: Option<&'a (dyn Error + 'static)>,240+}241+242+impl<'a> Iterator for Errors<'a> {243+ type Item = &'a (dyn Error + 'static);244+ fn next(&mut self) -> Option<Self::Item> {245+ let next = self.next.take()?;246+ self.next = next.source();247+ Some(next)248+ }249+}250+251+#[cfg(test)]252+mod repr_correctness {253+ use super::*;254+255+ use std::mem;256+ use std::marker::Unpin;257+258+ #[test]259+ fn size_of_exception() {260+ assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());261+ }262+263+ #[allow(dead_code)] fn assert_exception_autotraits() where264+ Exception: Unpin + Send + Sync + 'static265+ { }266+267+ #[test]268+ fn destructors_work() {269+ use std::sync::*;270+271+ #[derive(Debug)] struct HasDrop(Box<Arc<Mutex<bool>>>);272+ impl Error for HasDrop { }273+ impl Display for HasDrop {274+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {275+ write!(f, "does something")276+ }277+ }278+ impl Drop for HasDrop {279+ fn drop(&mut self) {280+ let mut has_dropped = self.0.lock().unwrap();281+ assert!(!*has_dropped);282+ *has_dropped = true;283+ }284+ }285+286+ let has_dropped = Arc::new(Mutex::new(false));287+288+ drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));289+290+ assert!(*has_dropped.lock().unwrap());291+292+ }293+}added:src/lib.rs+46 added
1+#![feature(backtrace)]2+3+mod as_error;4+mod exception;5+mod context;6+7+#[doc(inline)]8+/// Annotations a function that "throws" a Result.9+///10+/// Inside functions tagged with `throws`, you can use `?` and the `throw!` macro to return errors,11+/// but you don't need to wrap the successful return values in `Ok`.12+///13+/// `throws` can optionally take a type as an argument, which will be the error type returned by14+/// this function. By default, the function will throw `Exception`.15+pub use fehler_macros::throws;16+17+#[doc(inline)]18+/// Derive for the Error trait.19+///20+/// If the type contains a `Backtrace`, it will generate the `backtrace` method to find it.21+///22+/// If this wraps a different, underlying error, you can tag that field with `#[error::source]`,23+/// which will generate the `cause` and `source` methods correctly.24+pub use fehler_macros::Error;25+26+pub use crate::as_error::AsError;27+pub use crate::exception::{Exception, Errors};28+pub use crate::context::Context;29+30+/// Throw an error.31+///32+/// This macro is equivalent to `Err($err)?`.33+#[macro_export]34+macro_rules! throw {35+ ($err:expr) => (return std::result::Result::Err(std::convert::From::from($err)))36+}37+38+/// Construct an ad-hoc exception from a string.39+///40+/// This evaluates to an `Exception`. It can take either just a string, or a format string with41+/// arguments. It also can take any custom type which implements `Debug` and `Display`.42+#[macro_export]43+macro_rules! error {44+ ($e:expr) => { $crate::Exception::new_adhoc($e) };45+ ($($arg:tt)*) => { $crate::Exception::new_adhoc(format!($($arg)*)) };46+}