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
use std::ffi::CStr;
use crate::{
    prelude::*,
    ruby::{self, VALUE},
};

/// Evaluates `script` in an isolated binding without handling exceptions.
///
/// Variables:
/// - `__FILE__`: "(eval)"
/// - `__LINE__`: starts at 1
///
/// # Safety
///
/// Code executed from `script` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
///
/// ```
/// # rosy::vm::init().unwrap();
/// use std::ffi::CStr;
/// use rosy::prelude::*;
///
/// let array: Array<Integer> = (1..=3).collect(); // [1, 2, 3]
///
/// let module = Module::def("Evil").unwrap();
/// unsafe { module.set_const("ARR", array) };
///
/// let script = b"Evil::ARR.push('hi')\0";
/// let script = CStr::from_bytes_with_nul(script).unwrap();
///
/// unsafe { rosy::vm::eval(script) };
/// let hi = array.get(3).unwrap();
/// ```
///
/// If we try using `hi` as an `Integer` here, we will get a segmentation fault:
///
// Supports all failures, apparently
/// ```should_panic
// This is just for demonstration purposes
/// # rosy::vm::init().unwrap();
/// # use rosy::prelude::*;
/// # let hi = unsafe { Integer::cast_unchecked(String::from("hi")) };
/// let val = hi.to_truncated::<i32>();
/// ```
///
/// However, we can see that `hi` is actually a `String` despite being typed as
/// an `Integer`:
///
/// ```
// This is just for demonstration purposes
/// # rosy::vm::init().unwrap();
/// # use rosy::prelude::*;
/// # let hi = AnyObject::from("hi");
/// let hi = unsafe { String::cast_unchecked(hi) };
/// assert_eq!(hi, "hi");
/// ```
///
/// ...also, any exceptions raised in `script` must be handled in Rust-land.
#[inline]
pub unsafe fn eval(script: &CStr) -> AnyObject {
    AnyObject::from_raw(ruby::rb_eval_string(script.as_ptr()))
}

/// Evaluates `script` in an isolated binding, returning an exception if one is
/// raised.
///
/// Variables:
/// - `__FILE__`: "(eval)"
/// - `__LINE__`: starts at 1
///
/// # Safety
///
/// Code executed from `script` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
#[inline]
pub unsafe fn eval_protected(script: &CStr) -> Result<AnyObject> {
    let mut err = 0;
    let raw = ruby::rb_eval_string_protect(script.as_ptr(), &mut err);
    match err {
        0 => Ok(AnyObject::from_raw(raw)),
        _ => Err(AnyException::_take_current()),
    }
}

/// Evaluates `script` under a module binding in an isolated binding, returning
/// an exception if one is raised.
///
/// Variables:
/// - `__FILE__`: "(eval)"
/// - `__LINE__`: starts at 1
///
/// # Safety
///
/// Code executed from `script` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
#[inline]
pub unsafe fn eval_wrapped(script: &CStr) -> Result<AnyObject> {
    let mut err = 0;
    let raw = ruby::rb_eval_string_wrap(script.as_ptr(), &mut err);
    match err {
        0 => Ok(AnyObject::from_raw(raw)),
        _ => Err(AnyException::_take_current()),
    }
}

/// A type that can be used as one or more arguments for evaluating code within
/// the context of a [`Mixin`](trait.Mixin.html).
///
/// The difference between `eval_in_object` and `eval_in_mixin`
///
/// See the documentation of [its implementors](#foreign-impls) for much more
/// detailed information.
///
/// # Safety
///
/// Code executed from `self` 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`.
///
/// For non-`protected` variants, if an exception is raised due to an argument
/// error or from evaluating the script itself, it should be caught.
pub trait EvalArgs: Sized {
    /// Evaluates `self` in the context of `object`.
    ///
    /// This corresponds directly to `rb_obj_instance_eval`.
    ///
    /// In order to set the context, the variable `self` is set to `object`
    /// while the code is executing, giving the code access to `object`'s
    /// instance variables and private methods.
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject;

    /// Evaluates `self` in the context of `object`, returning any raised
    /// exceptions.
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject>;

    /// Evaluates `self` in the context of `mixin`.
    ///
    /// This corresponds directly to `rb_mod_module_eval`.
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject;

    /// Evaluates `self` in the context of `mixin`, returning any raised
    /// exceptions.
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject>;
}

/// Unchecked arguments directly to the evaluation function.
impl<O: Object> EvalArgs for &[O] {
    #[inline]
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject> {
        // monomorphization
        unsafe fn eval(args: &[AnyObject], object: AnyObject) -> Result<AnyObject> {
            crate::protected_no_panic(|| args.eval_in_object(object))
        }
        eval(AnyObject::convert_slice(self), object.into())
    }

    #[inline]
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject {
        let raw = ruby::rb_obj_instance_eval(
            self.len() as _,
            self.as_ptr() as *const VALUE,
            object.into().raw(),
        );
        AnyObject::from_raw(raw)
    }

    #[inline]
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject> {
        // monomorphization
        unsafe fn eval(args: &[AnyObject], mixin: VALUE) -> Result<AnyObject> {
            let raw = crate::protected_no_panic(|| ruby::rb_mod_module_eval(
                args.len() as _,
                args.as_ptr() as *const VALUE,
                mixin,
            ))?;
            Ok(AnyObject::from_raw(raw))
        }
        eval(AnyObject::convert_slice(self), mixin.raw())
    }

    #[inline]
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject {
        let raw = ruby::rb_mod_module_eval(
            self.len() as _,
            self.as_ptr() as *const VALUE,
            mixin.raw(),
        );
        AnyObject::from_raw(raw)
    }
}

/// The script argument without any extra information.
impl EvalArgs for String {
    #[inline]
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject> {
        self.as_any_slice().eval_in_object_protected(object)
    }

    #[inline]
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject {
        self.as_any_slice().eval_in_object(object)
    }

    #[inline]
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject> {
        self.as_any_slice().eval_in_mixin_protected(mixin)
    }

    #[inline]
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject {
        self.as_any_slice().eval_in_mixin(mixin)
    }
}

/// The script argument as a UTF-8 string, without any extra information.
// TODO: Impl for `Into<String>` when specialization stabilizes
impl EvalArgs for &str {
    #[inline]
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject> {
        String::from(self).eval_in_object_protected(object)
    }

    #[inline]
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject {
        String::from(self).eval_in_object(object)
    }

    #[inline]
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject> {
        String::from(self).eval_in_mixin_protected(mixin)
    }

    #[inline]
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject {
        String::from(self).eval_in_mixin(mixin)
    }
}

/// The script and filename arguments.
impl<S: Into<String>, F: Into<String>> EvalArgs for (S, F) {
    #[inline]
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject> {
        let (s, f) = self;
        [s.into(), f.into()].eval_in_object_protected(object)
    }

    #[inline]
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject {
        let (s, f) = self;
        [s.into(), f.into()].eval_in_object(object)
    }

    #[inline]
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject> {
        let (s, f) = self;
        [s.into(), f.into()].eval_in_mixin_protected(mixin)
    }

    #[inline]
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject {
        let (s, f) = self;
        [s.into(), f.into()].eval_in_mixin(mixin)
    }
}

/// The script, filename, and line number arguments.
impl<S, F, L> EvalArgs for (S, F, L)
where
    S: Into<String>,
    F: Into<String>,
    L: Into<Integer>,
{
    #[inline]
    unsafe fn eval_in_object_protected(self, object: impl Into<AnyObject>) -> Result<AnyObject> {
        let (s, f, l) = self;
        let s = AnyObject::from(s.into());
        let f = AnyObject::from(f.into());
        let l = AnyObject::from(l.into());
        [s, f, l].eval_in_object_protected(object)
    }

    #[inline]
    unsafe fn eval_in_object(self, object: impl Into<AnyObject>) -> AnyObject {
        let (s, f, l) = self;
        let s = AnyObject::from(s.into());
        let f = AnyObject::from(f.into());
        let l = AnyObject::from(l.into());
        [s, f, l].eval_in_object(object)
    }

    #[inline]
    unsafe fn eval_in_mixin_protected(self, mixin: impl Mixin) -> Result<AnyObject> {
        let (s, f, l) = self;
        let s = AnyObject::from(s.into());
        let f = AnyObject::from(f.into());
        let l = AnyObject::from(l.into());
        [s, f, l].eval_in_mixin_protected(mixin)
    }

    #[inline]
    unsafe fn eval_in_mixin(self, mixin: impl Mixin) -> AnyObject {
        let (s, f, l) = self;
        let s = AnyObject::from(s.into());
        let f = AnyObject::from(f.into());
        let l = AnyObject::from(l.into());
        [s, f, l].eval_in_mixin(mixin)
    }
}