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
//! Ruby exceptions.

use std::{
    convert::Infallible,
    error::Error,
    fmt,
};
use crate::{
    object::NonNullObject,
    prelude::*,
    ruby,
};

/// Some concrete Ruby exception.
///
/// # Safety
///
/// The implementing object type _must_ be an exception type. Otherwise, methods
/// like [`backtrace`](#method.backtrace) and [`cause`](#method.cause) will
/// cause a segmentation fault.
pub unsafe trait Exception: Object + Error {
    /// Returns `self` as an [`AnyException`](struct.AnyException.html).
    #[inline]
    fn into_any_exception(self) -> AnyException { *self.as_any_exception() }

    /// Returns a reference to `self` as an `AnyObject`.
    #[inline]
    fn as_any_exception(&self) -> &AnyException {
        unsafe { &*(self as *const Self as *const AnyException) }
    }

    /// Raises the exception.
    ///
    /// # Safety
    ///
    /// This call should be wrapped around in code that can properly handle
    /// `self`; otherwise a segmentation fault will occur.
    ///
    /// # Examples
    ///
    /// Using `protected` ensures that calling this method is indeed safe:
    ///
    /// ```
    /// # rosy::vm::init().unwrap();
    /// use rosy::{AnyException, Exception, protected};
    ///
    /// let exc = AnyException::new("Oh noes, something happened!");
    /// let err = protected(|| unsafe { exc.raise() }).unwrap_err();
    ///
    /// assert_eq!(exc, err);
    /// ```
    #[inline]
    unsafe fn raise(self) -> ! {
        ruby::rb_exc_raise(self.raw());
    }

    /// Returns a backtrace associated with `self`.
    #[inline]
    fn backtrace(&self) -> Option<Array<String>> {
        unsafe {
            let obj = self.call("backtrace");
            if obj.is_nil() {
                None
            } else {
                Some(Array::cast_unchecked(obj))
            }
        }
    }

    /// The underlying exception that caused `self`.
    #[inline]
    fn cause(&self) -> Option<AnyException> {
        unsafe {
            let obj = self.call("cause");
            if obj.is_nil() {
                None
            } else {
                Some(AnyException::cast_unchecked(obj))
            }
        }
    }
}

/// Any Ruby exception.
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct AnyException(NonNullObject);

impl AsRef<AnyObject> for AnyException {
    #[inline]
    fn as_ref(&self) -> &AnyObject { self.0.as_ref() }
}

impl From<AnyException> for AnyObject {
    #[inline]
    fn from(obj: AnyException) -> Self { obj.0.into() }
}

unsafe impl Object for AnyException {
    #[inline]
    fn cast<A: Object>(obj: A) -> Option<Self> {
        if obj.class().inherits(Class::exception()) {
            unsafe { Some(Self::from_raw(obj.raw())) }
        } else {
            None
        }
    }
}

impl fmt::Display for AnyException {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_any_object().fmt(f)
    }
}

impl Error for AnyException {}

unsafe impl Exception for AnyException {

}

impl From<Infallible> for AnyException {
    #[inline]
    fn from(error: Infallible) -> Self {
        match error {}
    }
}

impl<O: Object> PartialEq<O> for AnyException {
    #[inline]
    fn eq(&self, other: &O) -> bool {
        self.raw() == other.raw()
    }
}

impl Eq for AnyException {}

impl AnyException {
    // Returns the current exception without checking, clearing it globally
    #[cold] // Exception is less likely than success
    #[inline]
    pub(crate) unsafe fn _take_current() -> AnyException {
        let exc = ruby::rb_errinfo();
        ruby::rb_set_errinfo(crate::util::NIL_VALUE);
        AnyException::from_raw(exc)
    }

    /// Creates a new instance of `Exception` with `message`.
    pub fn new(message: impl Into<String>) -> Self {
        unsafe { Self::of_class(Class::exception(), message) }
    }

    /// Creates a new instance of `class` with `message`.
    ///
    /// # Safety
    ///
    /// The `class` argument must inherit from an exception class.
    pub unsafe fn of_class(
        class: impl Into<Class>,
        message: impl Into<String>,
    ) -> Self {
        Self::cast_unchecked(class.into().new_instance_with_unchecked(&[
            message.into()
        ]))
    }

    /// Returns the current pending exception.
    #[inline]
    pub fn current() -> Option<AnyException> {
        unsafe {
            match ruby::rb_errinfo() {
                crate::util::NIL_VALUE => None,
                raw => Some(AnyException::from_raw(raw))
            }
        }
    }

    /// Returns the current pending exception, removing it from its global spot.
    #[inline]
    pub fn take_current() -> Option<AnyException> {
        let current = AnyException::current()?;
        unsafe { ruby::rb_set_errinfo(crate::util::NIL_VALUE) };
        Some(current)
    }

    /// Returns whether `self` is a `StandardError`.
    #[inline]
    pub fn is_standard_error(self) -> bool {
        self.class() == Class::standard_error()
    }

    /// Returns whether `self` is a `SystemExit`.
    #[inline]
    pub fn is_system_exit(self) -> bool {
        self.class() == Class::system_exit()
    }

    /// Returns whether `self` is a `Interrupt`.
    #[inline]
    pub fn is_interrupt(self) -> bool {
        self.class() == Class::interrupt()
    }

    /// Returns whether `self` is a `Signal`.
    #[inline]
    pub fn is_signal(self) -> bool {
        self.class() == Class::signal()
    }

    /// Returns whether `self` is a `Fatal`.
    #[inline]
    pub fn is_fatal(self) -> bool {
        self.class() == Class::fatal()
    }

    /// Returns whether `self` is a `ArgumentError`.
    #[inline]
    pub fn is_arg_error(self) -> bool {
        self.class() == Class::arg_error()
    }

    /// Returns whether `self` is a `EOFError`.
    #[inline]
    pub fn is_eof_error(self) -> bool {
        self.class() == Class::eof_error()
    }

    /// Returns whether `self` is a `IndexError`.
    #[inline]
    pub fn is_index_error(self) -> bool {
        self.class() == Class::index_error()
    }

    /// Returns whether `self` is a `StopIteration`.
    #[inline]
    pub fn is_stop_iteration(self) -> bool {
        self.class() == Class::stop_iteration()
    }

    /// Returns whether `self` is a `KeyError`.
    #[inline]
    pub fn is_key_error(self) -> bool {
        self.class() == Class::key_error()
    }

    /// Returns whether `self` is a `RangeError`.
    #[inline]
    pub fn is_range_error(self) -> bool {
        self.class() == Class::range_error()
    }

    /// Returns whether `self` is a `IOError`.
    #[inline]
    pub fn is_io_error(self) -> bool {
        self.class() == Class::io_error()
    }

    /// Returns whether `self` is a `RuntimeError`.
    #[inline]
    pub fn is_runtime_error(self) -> bool {
        self.class() == Class::runtime_error()
    }

    /// Returns whether `self` is a `FrozenError`.
    #[inline]
    pub fn is_frozen_error(self) -> bool {
        self.class() == Class::frozen_error()
    }

    /// Returns whether `self` is a `SecurityError`.
    #[inline]
    pub fn is_security_error(self) -> bool {
        self.class() == Class::security_error()
    }

    /// Returns whether `self` is a `SystemCallError`.
    #[inline]
    pub fn is_system_call_error(self) -> bool {
        self.class() == Class::system_call_error()
    }

    /// Returns whether `self` is a `ThreadError`.
    #[inline]
    pub fn is_thread_error(self) -> bool {
        self.class() == Class::thread_error()
    }

    /// Returns whether `self` is a `TypeError`.
    #[inline]
    pub fn is_type_error(self) -> bool {
        self.class() == Class::type_error()
    }

    /// Returns whether `self` is a `ZeroDivError`.
    #[inline]
    pub fn is_zero_div_error(self) -> bool {
        self.class() == Class::zero_div_error()
    }

    /// Returns whether `self` is a `NotImpError`.
    #[inline]
    pub fn is_not_imp_error(self) -> bool {
        self.class() == Class::not_imp_error()
    }

    /// Returns whether `self` is a `NoMemError`.
    #[inline]
    pub fn is_no_mem_error(self) -> bool {
        self.class() == Class::no_mem_error()
    }

    /// Returns whether `self` is a `NoMethodError`.
    #[inline]
    pub fn is_no_method_error(self) -> bool {
        self.class() == Class::no_method_error()
    }

    /// Returns whether `self` is a `FloatDomainErr`.
    #[inline]
    pub fn is_float_domain_error(self) -> bool {
        self.class() == Class::float_domain_error()
    }

    /// Returns whether `self` is a `LocalJumpError`.
    #[inline]
    pub fn is_local_jump_error(self) -> bool {
        self.class() == Class::local_jump_error()
    }

    /// Returns whether `self` is a `SysStackError`.
    #[inline]
    pub fn is_sys_stack_error(self) -> bool {
        self.class() == Class::sys_stack_error()
    }

    /// Returns whether `self` is a `RegexpError`.
    #[inline]
    pub fn is_regexp_error(self) -> bool {
        self.class() == Class::regexp_error()
    }

    /// Returns whether `self` is a `EncodingError`.
    #[inline]
    pub fn is_encoding_error(self) -> bool {
        self.class() == Class::encoding_error()
    }

    /// Returns whether `self` is a `EncCompatError`.
    #[inline]
    pub fn is_enc_compat_error(self) -> bool {
        self.class() == Class::enc_compat_error()
    }

    /// Returns whether `self` is a `ScriptError`.
    #[inline]
    pub fn is_script_error(self) -> bool {
        self.class() == Class::script_error()
    }

    /// Returns whether `self` is a `NameError`.
    #[inline]
    pub fn is_name_error(self) -> bool {
        self.class() == Class::name_error()
    }

    /// Returns whether `self` is a `SyntaxError`.
    #[inline]
    pub fn is_syntax_error(self) -> bool {
        self.class() == Class::syntax_error()
    }

    /// Returns whether `self` is a `LoadError`.
    #[inline]
    pub fn is_load_error(self) -> bool {
        self.class() == Class::load_error()
    }

    /// Returns whether `self` is a `MathDomainError`.
    #[inline]
    pub fn is_math_domain_error(self) -> bool {
        self.class() == Class::math_domain_error()
    }
}