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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! General functionality over Ruby objects.

use std::fmt;
use crate::{
    prelude::*,
    ruby,
    mixin::MethodFn,
    vm::EvalArgs,
};

mod any;
mod non_null;
mod rosy;
mod ty;

pub(crate) use non_null::NonNullObject;

#[doc(inline)]
pub use self::{
    any::AnyObject,
    rosy::RosyObject,
    ty::Ty,
};

/// Some concrete Ruby object.
///
/// # Safety
///
/// All types that implement this trait _must_ be light wrappers around an
/// [`AnyObject`](struct.AnyObject.html) and thus have the same size and layout.
pub unsafe trait Object: Copy
    + Into<AnyObject>
    + AsRef<AnyObject>
    + PartialEq<AnyObject>
    + fmt::Debug
{
    /// Returns a unique identifier for an object type to facilitate casting.
    ///
    /// # Safety
    ///
    /// This value _must_ be unique. Rosy's built-in objects use identifiers
    /// that are very close to `u128::max_value()`, so those are easy to avoid.
    #[inline]
    fn unique_id() -> Option<u128> {
        None
    }

    /// Creates a new object from `raw` without checking.
    ///
    /// # Safety
    ///
    /// The following invariants must be upheld:
    /// - The value came from the Ruby VM
    /// - The value is a valid representation of `Self`
    ///
    /// Not following this will lead to
    /// [nasal demons](https://en.wikipedia.org/wiki/Nasal_demons). You've been
    /// warned.
    // TODO: Make a `const fn` once it stabilizes on trait items
    #[inline]
    unsafe fn from_raw(raw: ruby::VALUE) -> Self {
        Self::cast_unchecked(AnyObject::from_raw(raw))
    }

    /// Attempts to create an instance by casting `obj`.
    ///
    /// The default implementation checks the [`unique_id`](#method.unique_id)
    /// of `A` against that of `Self`.
    #[inline]
    fn cast<A: Object>(obj: A) -> Option<Self> {
        if A::unique_id() == Self::unique_id() {
            unsafe { Some(Self::cast_unchecked(obj)) }
        } else {
            None
        }
    }

    /// Casts `obj` to `Self` without checking its type.
    #[inline]
    unsafe fn cast_unchecked(obj: impl Object) -> Self {
        let mut result = std::mem::uninitialized::<Self>();
        std::ptr::write((&mut result) as *mut Self as *mut _, obj);
        result
    }

    /// Returns `self` as an `AnyObject`.
    #[inline]
    fn into_any_object(self) -> AnyObject { self.into() }

    /// Returns a reference to `self` as an `AnyObject`.
    #[inline]
    fn as_any_object(&self) -> &AnyObject { self.as_ref() }

    /// Returns `self` as a reference to a single-element slice.
    #[inline]
    fn as_any_slice(&self) -> &[AnyObject] {
        std::slice::from_ref(self.as_any_object())
    }

    /// Returns the raw object pointer.
    #[inline]
    fn raw(self) -> ruby::VALUE {
        self.as_any_object().raw()
    }

    /// Casts `self` to `O` without checking whether it is one.
    #[inline]
    unsafe fn as_unchecked<O: Object>(&self) -> &O {
        &*(self as *const _ as *const _)
    }

    /// Converts `self` to `O` without checking whether it is one.
    #[inline]
    unsafe fn into_unchecked<O: Object>(self) -> O {
        *self.as_unchecked()
    }

    /// Returns the object's identifier.
    #[inline]
    fn id(self) -> u64 {
        unsafe { ruby::rb_obj_id(self.raw()) as _ }
    }

    /// Returns the virtual type of `self`.
    #[inline]
    fn ty(self) -> Ty {
        self.as_any_object().ty()
    }

    /// Returns whether the virtual type of `self` is `ty`.
    #[inline]
    fn is_ty(self, ty: Ty) -> bool {
        crate::util::value_is_ty(self.raw(), ty)
    }

    /// Returns the `Class` for `self`.
    ///
    /// Note that if `Self` implements `Classify`, `Self::class()` may not be
    /// equal to the result of this method.
    #[inline]
    fn class(self) -> Class<Self> {
        unsafe { Class::from_raw(ruby::rb_obj_class(self.raw())) }
    }

    /// Returns the singleton `Class` of `self`, creating one if it doesn't
    /// exist already.
    ///
    /// Note that `Class::new_instance` does not work on singleton classes due
    /// to the class being attached to the specific object instance for `self`.
    #[inline]
    fn singleton_class(self) -> Class<Self> {
        unsafe { Class::from_raw(ruby::rb_singleton_class(self.raw())) }
    }

    /// Marks `self` for Ruby to avoid garbage collecting it.
    #[inline]
    fn mark(self) {
        crate::gc::mark(self);
    }

    /// Forces the garbage collector to free the contents of `self`.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `self` does not have ownership over any
    /// currently-referenced memory.
    #[inline]
    unsafe fn force_recycle(self) {
        crate::gc::force_recycle(self);
    }

    /// Defines a method for `name` on the singleton class of `self` that calls
    /// `f` when invoked.
    #[inline]
    fn def_singleton_method<N, F>(self, name: N, f: F) -> Result
    where
        N: Into<SymbolId>,
        F: MethodFn<Self>,
    {
        self.singleton_class().def_method(name, f)
    }

    /// Defines a method for `name` on the singleton class of `self` that calls
    /// `f` when invoked.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `self` is not frozen or else a `FrozenError`
    /// exception will be raised.
    #[inline]
    unsafe fn def_singleton_method_unchecked<N, F>(self, name: N, f: F)
    where
        N: Into<SymbolId>,
        F: MethodFn<Self>,
    {
        self.singleton_class().def_method_unchecked(name, f)
    }

    /// Calls `method` on `self` and returns its output.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    ///
    /// An exception will be raised if `method` is not defined on `self`.
    #[inline]
    unsafe fn call(self, method: impl Into<SymbolId>) -> AnyObject {
        let args: &[AnyObject] = &[];
        self.call_with(method, args)
    }

    /// Calls `method` on `self` and returns its output, or an exception if one
    /// is raised.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    #[inline]
    unsafe fn call_protected(self, method: impl Into<SymbolId>) -> Result<AnyObject> {
        let args: &[AnyObject] = &[];
        self.call_with_protected(method, args)
    }

    /// Calls `method` on `self` with `args` and returns its output.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    ///
    /// An exception will be raised if `method` is not defined on `self`.
    #[inline]
    unsafe fn call_with(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> AnyObject {
        AnyObject::from_raw(ruby::rb_funcallv(
            self.raw(),
            method.into().raw(),
            args.len() as _,
            args.as_ptr() as _,
        ))
    }

    /// Calls `method` on `self` with `args` and returns its output, or an
    /// exception if one is raised.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    #[inline]
    unsafe fn call_with_protected(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> Result<AnyObject> {
        // monomorphization
        unsafe fn call_with_protected(
            object: AnyObject,
            method: SymbolId,
            args: &[AnyObject],
        ) -> Result<AnyObject> {
            crate::protected_no_panic(|| object.call_with(method, args))
        }
        call_with_protected(self.into(), method.into(), AnyObject::convert_slice(args))
    }

    /// Calls the public `method` on `self` and returns its output.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    ///
    /// An exception will be raised if either `method` is not defined on `self`
    /// or `method` is not publicly callable.
    #[inline]
    unsafe fn call_public(
        self,
        method: impl Into<SymbolId>,
    ) -> AnyObject {
        let args: &[AnyObject] = &[];
        self.call_public_with(method, args)
    }

    /// Calls the public `method` on `self` and returns its output, or an
    /// exception if one is raised.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    #[inline]
    unsafe fn call_public_protected(
        self,
        method: impl Into<SymbolId>,
    ) -> Result<AnyObject> {
        let args: &[AnyObject] = &[];
        self.call_public_with_protected(method, args)
    }

    /// Calls the public `method` on `self` with `args` and returns its output.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    ///
    /// An exception will be raised if either `method` is not defined on `self`
    /// or `method` is not publicly callable.
    #[inline]
    unsafe fn call_public_with(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> AnyObject {
        AnyObject::from_raw(ruby::rb_funcallv_public(
            self.raw(),
            method.into().raw(),
            args.len() as _,
            args.as_ptr() as _,
        ))
    }

    /// Calls the public `method` on `self` with `args` and returns its output,
    /// or an exception if one is raised.
    ///
    /// # Safety
    ///
    /// Calling `method` may void the type safety of `Self`. For example, if one
    /// calls `push` on `Array<A>` with an object type `B`, then the inserted
    /// object will be treated as being of type `A`.
    #[inline]
    unsafe fn call_public_with_protected(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> Result<AnyObject> {
        // monomorphization
        fn call_public_with_protected(object: AnyObject, method: SymbolId, args: &[AnyObject]) -> Result<AnyObject> {
            unsafe { crate::protected_no_panic(|| {
                object.call_public_with(method, args)
            }) }
        }
        let args = AnyObject::convert_slice(args);
        call_public_with_protected(self.into(), method.into(), args)
    }

    /// Returns a printable string representation of `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # rosy::vm::init().unwrap();
    /// use rosy::{Object, Class};
    ///
    /// let array = Class::array();
    ///
    /// let expected = unsafe { array.call("inspect") };
    /// assert_eq!(array.inspect(), expected);
    /// ```
    #[inline]
    fn inspect(self) -> String {
        unsafe { String::from_raw(ruby::rb_inspect(self.raw())) }
    }

    /// Returns the result of calling the `to_s` method on `self`.
    #[inline]
    fn to_s(self) -> String {
        unsafe { String::from_raw(ruby::rb_obj_as_string(self.raw())) }
    }

    /// Returns whether modifications can be made to `self`.
    #[inline]
    fn is_frozen(self) -> bool {
        unsafe { ruby::rb_obj_frozen_p(self.raw()) != 0 }
    }

    /// Freezes `self`, preventing any further mutations.
    #[inline]
    fn freeze(self) {
        unsafe { ruby::rb_obj_freeze(self.raw()) };
    }

    /// Returns whether `self` is equal to `other` in terms of the `eql?`
    /// method.
    #[inline]
    fn is_eql<O: Object>(self, other: &O) -> bool {
        let this = self.raw();
        let that = other.raw();
        unsafe { ruby::rb_eql(this, that) != 0 }
    }

    /// Returns the value for the attribute of `self` associated with `name`.
    #[inline]
    fn get_attr<N: Into<SymbolId>>(self, name: N) -> AnyObject {
        let name = name.into().raw();
        unsafe { AnyObject::from_raw(ruby::rb_attr_get(self.raw(), name)) }
    }

    /// Evaluates `args` in the context of `self`.
    ///
    /// See the docs for `EvalArgs` for more info.
    ///
    /// # Safety
    ///
    /// Code executed from `args` may void the type safety of objects accessible
    /// from Rust. For example, if one calls `push` on an `Array<A>` with an
    /// object of type `B`, then the inserted object will be treated as being of
    /// type `A`.
    ///
    /// An exception may be raised by the code or by `args` being invalid.
    #[inline]
    unsafe fn eval(self, args: impl EvalArgs) -> AnyObject {
        args.eval_in_object(self)
    }

    /// Evaluates `args` in the context of `self`, returning any raised
    /// exceptions.
    ///
    /// See the docs for `EvalArgs` for more info.
    ///
    /// # Safety
    ///
    /// Code executed from `args` may void the type safety of objects accessible
    /// from Rust. For example, if one calls `push` on an `Array<A>` with an
    /// object of type `B`, then the inserted object will be treated as being of
    /// type `A`.
    #[inline]
    unsafe fn eval_protected(self, args: impl EvalArgs) -> Result<AnyObject> {
        args.eval_in_object_protected(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn array_unique_id() {
        let expected = !(Ty::ARRAY.id() as u128);
        let array_id = Array::<AnyObject>::unique_id().unwrap();
        assert_eq!(array_id, expected);
    }

    #[test]
    fn hash_unique_id() {
        let expected = !(Ty::HASH.id() as u128);
        let hash_id = Hash::<AnyObject, AnyObject>::unique_id().unwrap();
        assert_eq!(hash_id, expected);
    }

    #[test]
    fn unique_ids() {
        // Takes a sequence of `ty` and transforms it into an NxN sequence where
        // the work is done in the `single` branch over each `Hash` combination
        macro_rules! nxn_hash_ids {
            ($ids:expr => $($t:ty),*) => {
                nxn_hash_ids! { do_stuff $ids => $($t),* ; $($t),* }
            };
            (do_stuff $ids:expr => $t1next:ty ; $($t2s:ty),*) => {
                nxn_hash_ids! { expand $ids => $t1next, $($t2s),* }
            };
            (do_stuff $ids:expr => $t1next:ty, $($t1rest:ty),+ ; $($t2s:ty),*) => {
                nxn_hash_ids! { expand   $ids => $t1next,       $($t2s),* }
                nxn_hash_ids! { do_stuff $ids => $($t1rest),* ; $($t2s),* }
            };
            (expand $ids:expr => $t1:ty, $($t2s:ty),*) => {
                $(nxn_hash_ids! { single $ids => $t1, $t2s })*
            };
            (single $ids:expr => $t1:ty, $t2:ty) => {
                $ids.push((stringify!(Hash<$t1, $t2>), Hash::<$t1, $t2>::unique_id()));
            };
        }
        macro_rules! ids {
            ($($t:ty,)+) => { {
                let mut ids = vec![
                    $(
                        (stringify!(<$t>),              <$t>::unique_id()),
                        (stringify!(Array<$t>),         Array::<$t>::unique_id()),
                        (stringify!(Array<Array<$t>>),  Array::<Array<$t>>::unique_id()),
                    )+
                ];
                nxn_hash_ids!(ids => $($t),+);
                ids
            } }
        }
        let ids: &[(&str, _)] = &ids! {
            AnyException,
            AnyObject,
            Float,
            Integer,
            String,
            Symbol,
            crate::vm::InstrSeq,
        };
        for a in ids {
            for b in ids {
                if std::ptr::eq(a, b) {
                    continue;
                }
                match (a, b) {
                    ((ty_a, Some(a)), (ty_b, Some(b))) => {
                        assert_ne!(a, b, "{} and {} have same ID", ty_a, ty_b);
                    },
                    (_, _) => {},
                }
            }
        }
    }
}