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
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(clippy::needless_borrow)]
// https://github.com/rust-lang/rust-clippy/pull/5998#issuecomment-731855891
#![allow(clippy::map_err_ignore)]
#![allow(clippy::option_if_let_else)]
#![allow(unknown_lints)]
#![warn(broken_intra_doc_links)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! Built in Ruby exception types.
//!
//! Descendants of class [`Exception`] are used to communicate between
//! [`Kernel#raise`] and `rescue` statements in `begin ... end` blocks.
//! Exception objects carry information about the exception – its type (the
//! exception's class name), an optional descriptive string, and optional
//! traceback information. `Exception` subclasses may add additional information
//! like [`NameError#name`].
//!
//! # Ruby Exception Hierarchy
//!
//! The built-in subclasses of [`Exception`] are:
//!
//! - [`NoMemoryError`]
//! - [`ScriptError`]
//!   - [`LoadError`]
//!   - [`NotImplementedError`]
//!   - [`SyntaxError`]
//! - [`SecurityError`]
//! - [`SignalException`]
//!   - [`Interrupt`]
//! - [`StandardError`] — default for `rescue`
//!   - [`ArgumentError`]
//!     - [`UncaughtThrowError`]
//!   - [`EncodingError`]
//!   - [`FiberError`]
//!   - [`IOError`]
//!     - [`EOFError`]
//!   - [`IndexError`]
//!     - [`KeyError`]
//!     - [`StopIteration`]
//!   - [`LocalJumpError`]
//!   - [`NameError`]
//!     - [`NoMethodError`]
//!   - [`RangeError`]
//!     - [`FloatDomainError`]
//!   - [`RegexpError`]
//!   - [`RuntimeError`] — default for `raise`
//!     - [`FrozenError`]
//!   - [`SystemCallError`]
//!     - `Errno::*`
//!   - [`ThreadError`]
//!   - [`TypeError`]
//!   - [`ZeroDivisionError`]
//! - [`SystemExit`]
//! - [`SystemStackError`]
//! - `fatal` — impossible to rescue
//!
//! # `no_std`
//!
//! This crate is `no_std` compatible when built without the `std` feature. This
//! crate has a required dependency on [`alloc`].
//!
//! # Crate features
//!
//! All features are enabled by default.
//!
//! - **std** - Enables a dependency on the Rust Standard Library. Activating
//!   this feature enables [`std::error::Error`] impls on error types in this
//!   crate.
//!
//! [`Exception`]: https://ruby-doc.org/core-2.6.3/Exception.html
//! [`Kernel#raise`]: https://ruby-doc.org/core-2.6.3/Kernel.html#method-i-raise
//! [`NameError#name`]: https://ruby-doc.org/core-2.6.3/NameError.html#method-i-name
//! [`NoMemoryError`]: https://ruby-doc.org/core-2.6.3/NoMemoryError.html
//! [`ScriptError`]: https://ruby-doc.org/core-2.6.3/ScriptError.html
//! [`LoadError`]: https://ruby-doc.org/core-2.6.3/LoadError.html
//! [`NotImplementedError`]: https://ruby-doc.org/core-2.6.3/NotImplementedError.html
//! [`SyntaxError`]: https://ruby-doc.org/core-2.6.3/SyntaxError.html
//! [`SecurityError`]: https://ruby-doc.org/core-2.6.3/SecurityError.html
//! [`SignalException`]: https://ruby-doc.org/core-2.6.3/SignalException.html
//! [`Interrupt`]: https://ruby-doc.org/core-2.6.3/Interrupt.html
//! [`StandardError`]: https://ruby-doc.org/core-2.6.3/StandardError.html
//! [`ArgumentError`]: https://ruby-doc.org/core-2.6.3/ArgumentError.html
//! [`UncaughtThrowError`]: https://ruby-doc.org/core-2.6.3/UncaughtThrowError.html
//! [`EncodingError`]: https://ruby-doc.org/core-2.6.3/EncodingError.html
//! [`FiberError`]: https://ruby-doc.org/core-2.6.3/FiberError.html
//! [`IOError`]: https://ruby-doc.org/core-2.6.3/IOError.html
//! [`EOFError`]: https://ruby-doc.org/core-2.6.3/EOFError.html
//! [`IndexError`]: https://ruby-doc.org/core-2.6.3/IndexError.html
//! [`KeyError`]: https://ruby-doc.org/core-2.6.3/KeyError.html
//! [`StopIteration`]: https://ruby-doc.org/core-2.6.3/StopIteration.html
//! [`LocalJumpError`]: https://ruby-doc.org/core-2.6.3/LocalJumpError.html
//! [`NameError`]: https://ruby-doc.org/core-2.6.3/NameError.html
//! [`NoMethodError`]: https://ruby-doc.org/core-2.6.3/NoMethodError.html
//! [`RangeError`]: https://ruby-doc.org/core-2.6.3/RangeError.html
//! [`FloatDomainError`]: https://ruby-doc.org/core-2.6.3/FloatDomainError.html
//! [`RegexpError`]: https://ruby-doc.org/core-2.6.3/RegexpError.html
//! [`RuntimeError`]: https://ruby-doc.org/core-2.6.3/RuntimeError.html
//! [`FrozenError`]: https://ruby-doc.org/core-2.6.3/FrozenError.html
//! [`SystemCallError`]: https://ruby-doc.org/core-2.6.3/SystemCallError.html
//! [`ThreadError`]: https://ruby-doc.org/core-2.6.3/ThreadError.html
//! [`TypeError`]: https://ruby-doc.org/core-2.6.3/TypeError.html
//! [`ZeroDivisionError`]: https://ruby-doc.org/core-2.6.3/ZeroDivisionError.html
//! [`SystemExit`]: https://ruby-doc.org/core-2.6.3/SystemExit.html
//! [`SystemStackError`]: https://ruby-doc.org/core-2.6.3/SystemStackError.html

#![no_std]

extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

use alloc::borrow::Cow;

pub mod core;

#[doc(inline)]
pub use self::core::*;

// Ensure code blocks in README.md compile
#[cfg(doctest)]
macro_rules! readme {
    ($x:expr) => {
        #[doc = $x]
        mod readme {}
    };
    () => {
        readme!(include_str!("../README.md"));
    };
}
#[cfg(doctest)]
readme!();

/// Polymorphic exception type that corresponds to Ruby's `Exception`.
///
/// This trait unifies all concrete exception types defined in this crate and is
/// [object safe]. This means `RubyException` can be used as a trait object to
/// represent an error type of any set of exception subclasses.
///
/// All types that implement `RubyException` should be `raise`able in an
/// Artichoke Ruby VM.
///
/// # Examples
///
/// ```
/// # use spinoso_exception::*;
/// # struct Array(()); impl Array { pub fn is_frozen(&self) -> bool { true } }
/// fn array_concat(slf: Array, other: Array) -> Result<Array, Box<dyn RubyException>> {
///     if slf.is_frozen() {
///         return Err(Box::new(FrozenError::new()));
///     }
///     Err(Box::new(NotImplementedError::new()))
/// }
/// ```
///
/// [object safe]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#object-safety-is-required-for-trait-objects
pub trait RubyException {
    /// The exception's message.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_exception::*;
    /// fn exception_inspect(exc: &dyn RubyException) {
    ///     let message = exc.message();
    ///     let message = String::from_utf8_lossy(&message);
    ///     println!("{} ({})", exc.name(), message);
    /// }
    /// ```
    ///
    /// # Implementation notes
    ///
    /// This method returns a byte slice since Ruby `String`s are best
    /// represented as a [`Vec<u8>`].
    ///
    /// [`Vec<u8>`]: alloc::vec::Vec
    fn message(&self) -> Cow<'_, [u8]>;

    /// The exception's class name.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_exception::*;
    /// fn exception_inspect(exc: &dyn RubyException) {
    ///     let message = exc.message();
    ///     let message = String::from_utf8_lossy(&message);
    ///     println!("{} ({})", exc.name(), message);
    /// }
    /// ```
    ///
    /// # Implementation notes
    ///
    /// This method returns a byte slice since Ruby `String`s are best
    /// represented as a [`Vec<u8>`].
    ///
    /// [`Vec<u8>`]: alloc::vec::Vec
    fn name(&self) -> Cow<'_, str>;
}

// Assert that `RubyException` is object-safe (i.e. supports dynamic dispatch).
const _: Option<&dyn RubyException> = None;