1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Contains the `Error` type and company as used by Amethyst.
//!
//! **Note:** This type is not intended to be used outside of Amethyst.
//! If you are integrating a crate from amethyst to use this, it is recommended that you treat this
//! type as an opaque [`std::error::Error`].
//!
//! [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html

// Parts copied from failure:
// https://github.com/rust-lang-nursery/failure

#![warn(
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    rust_2018_compatibility
)]
#![warn(clippy::all)]
#![allow(clippy::new_without_default)]

pub use backtrace::Backtrace;
use std::{
    borrow::Cow,
    env, error, fmt, result,
    sync::atomic::{self, AtomicUsize},
};

const RUST_BACKTRACE: &str = "RUST_BACKTRACE";

/// Internal parts of `Error`.
#[derive(Debug)]
struct Inner<T: ?Sized> {
    source: Option<Box<Error>>,
    backtrace: Option<Backtrace>,
    error: T,
}

/// The error type used by Amethyst.
///
/// Wraps error diagnostics like messages and other errors, and keeps track of causal chains and
/// backtraces.
pub struct Error {
    inner: Box<Inner<dyn error::Error + Send + Sync>>,
}

impl Error {
    /// Default constructor for our error types.
    ///
    /// Wraps anything that is an error in a box.
    pub fn new<E>(error: E) -> Self
    where
        E: 'static + error::Error + Send + Sync,
    {
        Self {
            inner: Box::new(Inner {
                source: None,
                backtrace: new_backtrace(),
                error: Box::new(error),
            }),
        }
    }

    /// Update the source of an error.
    pub fn with_source<S>(mut self, source: S) -> Self
    where
        S: 'static + Into<Error>,
    {
        self.inner.source = Some(Box::new(source.into()));
        self
    }

    /// Construct a new error from a string.
    pub fn from_string<M>(message: M) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        /// Wrapper for string errors.
        #[derive(Debug)]
        struct StringError(Cow<'static, str>);

        impl fmt::Display for StringError {
            fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(fmt)
            }
        }

        impl error::Error for StringError {}

        Self {
            inner: Box::new(Inner {
                source: None,
                backtrace: new_backtrace(),
                error: Box::new(StringError(message.into())),
            }),
        }
    }

    /// Get backtrace.
    pub fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace.as_ref()
    }

    /// Get the source of the error.
    ///
    /// # Examples
    ///
    /// The only way to set the source is through [`ResultExt`](ResultExt) using
    /// [`with_context`](ResultExt::with_context).
    ///
    /// ```rust
    /// use amethyst_error::{Error, ResultExt};
    /// use std::io;
    ///
    /// let e = io::Error::new(io::ErrorKind::Other, "wrapped");
    /// let a = Error::new(e);
    ///
    /// let res = Result::Err::<(), Error>(a).with_context(|_| Error::from_string("top"));
    /// let e = res.expect_err("no error");
    ///
    /// assert_eq!("top", e.to_string());
    /// assert_eq!("wrapped", e.source().expect("no source").to_string());
    /// ```
    pub fn source(&self) -> Option<&Error> {
        self.inner.source.as_ref().map(|e| &**e)
    }

    /// Iterate over all causes, including this one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use amethyst_error::{Error, ResultExt};
    ///
    /// fn failing_function() -> Result<(), Error> {
    ///     Err(Error::from_string("failing"))
    /// }
    ///
    /// fn other_function() -> Result<(), Error> {
    ///     Ok(failing_function().with_context(|_| Error::from_string("other"))?)
    /// }
    ///
    /// let e = other_function().expect_err("no error");
    ///
    /// let messages = e.causes().map(|e| e.to_string()).collect::<Vec<_>>();
    /// assert_eq!(vec!["other", "failing"], messages);
    /// ```
    pub fn causes(&self) -> Causes<'_> {
        Causes {
            current: Some(self),
        }
    }

    /// Access the internal `std::error::Error` as a trait.
    ///
    /// This can be useful for integrating with systems that operate on `std::error::Error`.
    ///
    /// **Warning:** This erases most diagnostics in favor of returning only the top error.
    /// `std::error::Error` is expanded further.
    pub fn as_error(&self) -> &(dyn error::Error + 'static) {
        &self.inner.error
    }
}

/// Blanket implementation.
///
/// Encapsulate errors which are Send + Sync.
impl<T> From<T> for Error
where
    T: 'static + error::Error + Send + Sync,
{
    fn from(value: T) -> Error {
        Error::new(value)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.inner.error, fmt)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Error")
            .field("inner", &self.inner)
            .finish()
    }
}

/// Extra convenience functions for results based on core errors.
pub trait ResultExt<T>
where
    Self: Sized,
{
    /// Provide a context for the result in case it is an error.
    ///
    /// The context callback is expected to return a new error, which will replace the given error
    /// and set the replaced error as its [`source`](Error::source).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use amethyst_error::{Error, ResultExt};
    ///
    /// fn failing_function() -> Result<(), Error> {
    ///     Err(Error::from_string("failing"))
    /// }
    ///
    /// fn other_function() -> Result<(), Error> {
    ///     Ok(failing_function().with_context(|_| Error::from_string("other"))?)
    /// }
    ///
    /// let e = other_function().expect_err("no error");
    ///
    /// assert_eq!("other", e.to_string());
    /// assert_eq!("failing", e.source().expect("no source").to_string());
    /// assert!(e.source().expect("no source").source().is_none());
    /// ```
    fn with_context<C, D>(self, chain: C) -> Result<T, Error>
    where
        C: FnOnce(&Error) -> D,
        D: Into<Error>;
}

impl<T, E> ResultExt<T> for result::Result<T, E>
where
    E: Into<Error>,
{
    fn with_context<C, D>(self, chain: C) -> Result<T, Error>
    where
        C: FnOnce(&Error) -> D,
        D: Into<Error>,
    {
        match self {
            Err(e) => {
                let e = e.into();
                Err(chain(&e).into().with_source(e))
            }
            Ok(value) => Ok(value),
        }
    }
}

/// An iterator over all the causes for this error.
///
/// Created using [`Error::causes`](Error::causes).
#[derive(Debug, Clone)]
pub struct Causes<'a> {
    current: Option<&'a Error>,
}

impl<'a> Iterator for Causes<'a> {
    type Item = &'a Error;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(e) = self.current {
            self.current = e.source();
            return Some(e);
        }

        None
    }
}

/// Constructs an `Error` using the standard string interpolation syntax.
///
/// ```rust
/// #[macro_use] extern crate amethyst_error;
///
/// fn main() {
///     let err = format_err!("number: {}", 42);
///     assert_eq!("number: 42", err.to_string());
/// }
/// ```
#[macro_export]
macro_rules! format_err {
    ($($arg:tt)*) => { $crate::Error::from_string(format!($($arg)*)) }
}

/// Constructs an [`Error`](Error) from a string.
pub fn err_msg<M>(message: M) -> Error
where
    M: 'static + Send + Sync + fmt::Debug + fmt::Display,
{
    Error::new(ErrMsgError { message })
}

/// Treat something that can be displayed as an error.
struct ErrMsgError<M> {
    message: M,
}

impl<M> error::Error for ErrMsgError<M> where M: fmt::Debug + fmt::Display {}

impl<M> fmt::Display for ErrMsgError<M>
where
    M: fmt::Display,
{
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.message.fmt(fmt)
    }
}

impl<M> fmt::Debug for ErrMsgError<M>
where
    M: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.message.fmt(fmt)
    }
}

/// Test if backtracing is enabled.
fn is_backtrace_enabled() -> bool {
    match env::var_os(RUST_BACKTRACE) {
        Some(ref val) if val != "0" => true,
        _ => false,
    }
}

// 0: unchecked
// 1: disabled
// 2: enabled
static BACKTRACE_STATUS: AtomicUsize = AtomicUsize::new(0);

/// Constructs a new backtrace, if backtraces are enabled.
fn new_backtrace() -> Option<Backtrace> {
    match BACKTRACE_STATUS.load(atomic::Ordering::Relaxed) {
        0 => {
            let enabled = is_backtrace_enabled();

            BACKTRACE_STATUS.store(enabled as usize + 1, atomic::Ordering::Relaxed);

            if !enabled {
                return None;
            }
        }
        1 => return None,
        _ => {}
    }

    Some(Backtrace::new())
}

#[cfg(test)]
mod tests {
    use super::{Error, ResultExt};

    #[test]
    fn test_error_from_string() {
        assert_eq!("foo", Error::from_string("foo").to_string());
    }

    #[test]
    fn test_error_from_error() {
        use std::io;
        let e = io::Error::new(io::ErrorKind::Other, "i/o other");
        assert_eq!("i/o other", Error::new(e).to_string());
    }

    #[test]
    fn test_result_ext_source() {
        use std::io;

        let e = io::Error::new(io::ErrorKind::Other, "wrapped");
        let a = Error::new(e);

        let res = Result::Err::<(), Error>(a).with_context(|_| Error::from_string("top"));
        let e = res.expect_err("no error");

        assert_eq!("top", e.to_string());
        assert_eq!("wrapped", e.source().expect("no source").to_string());
    }

    #[test]
    fn test_sources() {
        use std::io;

        let e = io::Error::new(io::ErrorKind::Other, "wrapped");
        let a = Error::new(e);

        let res = Result::Err::<(), Error>(a).with_context(|_| Error::from_string("top"));
        let e = res.expect_err("no error");

        let messages = e.causes().map(|e| e.to_string()).collect::<Vec<_>>();
        assert_eq!(messages, vec!["top", "wrapped"]);
    }

    #[test]
    fn test_try_compat() {
        use std::io;

        fn foo() -> Result<u32, io::Error> {
            Err(io::Error::new(io::ErrorKind::Other, "foo"))
        }

        fn bar() -> Result<u32, Error> {
            let v = foo().with_context(|_| Error::from_string("bar"))?;
            Ok(v + 1)
        }

        let e = bar().expect_err("no error");
        let messages = e.causes().map(|e| e.to_string()).collect::<Vec<_>>();
        assert_eq!(messages, vec!["bar", "foo"]);
    }

    #[test]
    fn test_with_source() {
        let e = Error::from_string("foo");
        assert_eq!(e.to_string(), "foo");
        assert!(e.source().is_none());

        let e = e.with_source(Error::from_string("bar"));
        assert_eq!(e.to_string(), "foo");
        assert_eq!(e.source().map(|e| e.to_string()), Some(String::from("bar")));
    }

    // Note: all backtrace tests have to be in the same test case since they
    // depend on the state of the global `BACKTRACE_STATUS`.
    #[test]
    fn test_backtrace() {
        use super::BACKTRACE_STATUS;
        use std::sync::atomic;

        BACKTRACE_STATUS.store(2, atomic::Ordering::Relaxed);

        #[allow(warnings)]
        #[inline(never)]
        #[no_mangle]
        fn a_really_unique_name_42() -> Error {
            Error::from_string("an error")
        }

        let e = a_really_unique_name_42();
        let bt = e.backtrace().expect("a backtrace");

        let frame_names = bt
            .frames()
            .iter()
            .flat_map(|f| f.symbols().iter().flat_map(|s| s.name()))
            .map(|n| n.to_string())
            .collect::<Vec<_>>();

        assert!(frame_names
            .iter()
            .any(|n| n.ends_with("a_really_unique_name_42")));

        // Test disabled.
        BACKTRACE_STATUS.store(1, atomic::Ordering::Relaxed);
        assert!(Error::from_string("an error").backtrace().is_none());
    }
}