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
//! General functionality over Ruby objects.

use crate::{
    prelude::*,
    ruby,
    mixin::MethodFn,
};

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> {
    /// 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`.
    #[inline]
    fn class(self) -> Class {
        unsafe { Class::from_raw(ruby::rb_obj_class(self.raw())) }
    }

    /// Returns the singleton `Class` of `self`, creating one if it doesn't
    /// exist already.
    #[inline]
    fn singleton_class(self) -> Class {
        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.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.singleton_class().def_method_unchecked(name, f);
    }

    /// Calls `method` on `self` and returns the result.
    #[inline]
    fn call(self, method: impl Into<SymbolId>) -> Result<AnyObject> {
        crate::protected(|| unsafe { self.call_unchecked(method) })
    }

    /// Calls `method` on `self` and returns the result.
    ///
    /// # Safety
    ///
    /// An exception will be raised if `method` is not defined on `self`.
    #[inline]
    unsafe fn call_unchecked(self, method: impl Into<SymbolId>) -> AnyObject {
        let args: &[AnyObject] = &[];
        self.call_with_unchecked(method, args)
    }

    /// Calls `method` on `self` with `args` and returns the result.
    #[inline]
    fn call_with(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> Result<AnyObject> {
        crate::protected(|| unsafe { self.call_with_unchecked(method, args) })
    }

    /// Calls `method` on `self` with `args` and returns the result.
    ///
    /// # Safety
    ///
    /// An exception will be raised if `method` is not defined on `self`.
    #[inline]
    unsafe fn call_with_unchecked(
        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 the public `method` on `self` and returns the result.
    #[inline]
    fn call_public(
        self,
        method: impl Into<SymbolId>,
    ) -> Result<AnyObject> {
        crate::protected(|| unsafe { self.call_public_unchecked(method) })
    }

    /// Calls the public `method` on `self` and returns the result.
    ///
    /// # Safety
    ///
    /// An exception will be raised if either `method` is not defined on `self`
    /// or `method` is not publicly callable.
    #[inline]
    unsafe fn call_public_unchecked(
        self,
        method: impl Into<SymbolId>,
    ) -> AnyObject {
        let args: &[AnyObject] = &[];
        self.call_public_with_unchecked(method, args)
    }

    /// Calls the public `method` on `self` with `args` and returns the result.
    #[inline]
    fn call_public_with(
        self,
        method: impl Into<SymbolId>,
        args: &[impl Object]
    ) -> Result<AnyObject> {
        crate::protected(|| unsafe {
            self.call_public_with_unchecked(method, args)
        })
    }

    /// Calls the public `method` on `self` with `args` and returns the result.
    ///
    /// # Safety
    ///
    /// 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_unchecked(
        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 _,
        ))
    }

    /// Returns a printable string representation of `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # rosy::vm::init().unwrap();
    /// use rosy::{Object, Class};
    ///
    /// let a = Class::array();
    /// assert_eq!(a.inspect(), a.call("inspect").unwrap());
    /// ```
    #[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 }
    }
}

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

    #[test]
    fn unique_ids() {
        macro_rules! ids {
            ($($t:ty,)+) => { [$(
                <$t>::unique_id(),
                Array::<$t>::unique_id(),
                Array::<Array<$t>>::unique_id(),
            )+] }
        }
        let ids: &[_] = &ids! {
            AnyObject,
            AnyException,
            Hash,
            String,
            Symbol,
            crate::vm::InstrSeq,
            RosyObject<std::string::String>,
        };
        for a in ids {
            for b in ids {
                if std::ptr::eq(a, b) {
                    continue;
                }
                match (a, b) {
                    (Some(a), Some(b)) => assert_ne!(a, b),
                    (_, _) => {},
                }
            }
        }
    }
}