Skip to content
Myr

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

4 files+453 added−0 removed

added:src/as_error.rs+27 added
1use std::error::Error;23use crate::Exception;45/// View type as an error object.6pub trait AsError {7 /// View type as an error object.8 fn as_error(&self) -> &(dyn Error + Send + Sync + 'static);9}1011impl<T: Error + Send + Sync + 'static> AsError for T {12 fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {13 self14 }15}1617impl AsError for dyn Error + Send + Sync + 'static {18 fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {19 self20 }21}2223impl AsError for Exception {24 fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {25 &**self26 }27}
added:src/context.rs+87 added
1use std::backtrace::Backtrace;2use std::fmt::{self, Debug, Display};3use std::error::Error;45use crate::Exception;67/// Provides the `context` method for `Result`.8pub 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>;1112 /// 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}1718impl<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 }2223 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}3031impl<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 }3536 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}4344struct ContextError<E, C> {45 error: E,46 context: C,47}4849impl<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}5455impl<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}6061impl<E: Error + 'static, C: Display> Error for ContextError<E, C> {62 fn backtrace(&self) -> Option<&Backtrace> {63 self.error.backtrace()64 }6566 fn cause(&self) -> Option<&dyn Error> {67 Some(&self.error)68 }6970 fn source(&self) -> Option<&(dyn Error + 'static)> {71 Some(&self.error)72 }73}7475impl<C: Display> Error for ContextError<Exception, C> {76 fn backtrace(&self) -> Option<&Backtrace> {77 Some(self.error.backtrace())78 }7980 fn cause(&self) -> Option<&dyn Error> {81 Some(&*self.error)82 }8384 fn source(&self) -> Option<&(dyn Error + 'static)> {85 Some(&*self.error)86 }87}
added:src/exception.rs+293 added
1use std::any::TypeId;2use std::backtrace::{Backtrace, BacktraceStatus};3use std::error::Error;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// 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.18pub struct Exception {19 inner: Box<InnerException<()>>,20}2122impl 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 }3435 #[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 }4142 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 }5859 /// View this exception as the underlying error.60 pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {61 &**self62 }6364 /// 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 }6869 /// 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 }7677 /// 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 }8485 /// 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 }8990 /// 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 }103104 /// 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 }110111 /// 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}118119impl<E: Error + Send + Sync + 'static> From<E> for Exception {120 fn from(error: E) -> Exception {121 Exception::new(error)122 }123}124125impl Deref for Exception {126 type Target = dyn Error + Send + Sync + 'static;127 fn deref(&self) -> &Self::Target {128 self.inner.error()129 }130}131132impl DerefMut for Exception {133 fn deref_mut(&mut self) -> &mut Self::Target {134 self.inner.error_mut()135 }136}137138impl Debug for Exception {139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {140 writeln!(f, "{}", self.inner.error())?;141142 let mut errors = self.errors().skip(1).enumerate();143144 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 }151152 let backtrace = self.backtrace();153154 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 }164165 Ok(())166 }167}168169impl Display for Exception {170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {171 write!(f, "{}", self.inner.error())172 }173}174175unsafe impl Send for Exception { }176unsafe impl Sync for Exception { }177178impl Drop for Exception {179 fn drop(&mut self) {180 unsafe { ptr::drop_in_place(self.inner.error_mut()) }181 }182}183184// repr C to ensure that `E` remains in the final position185#[repr(C)]186struct InnerException<E> {187 vtable: *const (),188 type_id: TypeId,189 backtrace: Option<Backtrace>,190 error: E,191}192193// repr C to ensure that transmuting from trait objects is safe194#[repr(C)]195struct TraitObject {196 data: *const (),197 vtable: *const (),198}199200#[repr(transparent)]201struct MessageError<M: Display + Debug>(M);202203impl<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}208209impl<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}214215impl<M: Display + Debug + 'static> Error for MessageError<M> { }216217impl 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 }226227 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}236237/// Iterator of errors in an `Exception`.238pub struct Errors<'a> {239 next: Option<&'a (dyn Error + 'static)>,240}241242impl<'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}250251#[cfg(test)]252mod repr_correctness {253 use super::*;254255 use std::mem;256 use std::marker::Unpin;257258 #[test]259 fn size_of_exception() {260 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());261 }262263 #[allow(dead_code)] fn assert_exception_autotraits() where264 Exception: Unpin + Send + Sync + 'static265 { }266267 #[test]268 fn destructors_work() {269 use std::sync::*;270271 #[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 }285286 let has_dropped = Arc::new(Mutex::new(false));287288 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));289290 assert!(*has_dropped.lock().unwrap());291292 }293}
added:src/lib.rs+46 added
1#![feature(backtrace)]23mod as_error;4mod exception;5mod context;67#[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`.15pub use fehler_macros::throws;1617#[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.24pub use fehler_macros::Error;2526pub use crate::as_error::AsError;27pub use crate::exception::{Exception, Errors};28pub use crate::context::Context;2930/// Throw an error.31///32/// This macro is equivalent to `Err($err)?`.33#[macro_export]34macro_rules! throw {35 ($err:expr) => (return std::result::Result::Err(std::convert::From::from($err)))36}3738/// 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]43macro_rules! error {44 ($e:expr) => { $crate::Exception::new_adhoc($e) };45 ($($arg:tt)*) => { $crate::Exception::new_adhoc(format!($($arg)*)) };46}