artichoke_backend/
value.rs

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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Boxed values on the Ruby interpreter heap.

use std::borrow::Cow;
use std::error;
use std::fmt;
use std::ptr;

use artichoke_core::convert::{Convert, ConvertMut, TryConvertMut};
use artichoke_core::intern::Intern;
use artichoke_core::value::Value as ValueCore;
use spinoso_exception::{ArgumentError, Fatal};

use crate::core::ClassRegistry;
use crate::error::{Error, RubyException};
use crate::exception_handler;
use crate::gc::MrbGarbageCollection;
use crate::sys::{self, protect};
use crate::types::{self, Ruby};
use crate::Artichoke;

/// Max argument count for function calls including initialize and yield.
pub const MRB_FUNCALL_ARGC_MAX: usize = 16;

/// Boxed Ruby value in the [`Artichoke`] interpreter.
#[derive(Default, Debug, Clone, Copy)]
pub struct Value(sys::mrb_value);

impl From<Value> for sys::mrb_value {
    /// Extract the inner [`sys::mrb_value`] from this [`Value`].
    fn from(value: Value) -> Self {
        value.0
    }
}

impl From<sys::mrb_value> for Value {
    /// Construct a new [`Value`] from a [`sys::mrb_value`].
    fn from(value: sys::mrb_value) -> Self {
        Self(value)
    }
}

impl From<Option<sys::mrb_value>> for Value {
    fn from(value: Option<sys::mrb_value>) -> Self {
        if let Some(value) = value {
            Self::from(value)
        } else {
            Self::nil()
        }
    }
}

impl From<Option<Value>> for Value {
    fn from(value: Option<Value>) -> Self {
        value.unwrap_or_else(Value::nil)
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        let this = unsafe { sys::mrb_sys_basic_ptr(self.inner()) };
        let other = unsafe { sys::mrb_sys_basic_ptr(other.inner()) };
        ptr::eq(this, other)
    }
}

impl Value {
    /// Create a new, empty Ruby value.
    ///
    /// Alias for `Value::default`.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a `nil` Ruby Value.
    #[inline]
    #[must_use]
    pub fn nil() -> Self {
        Self::default()
    }

    /// Retrieve the inner [`sys::mrb_value`] that this [`Value`] wraps.
    #[inline]
    #[must_use]
    pub(crate) const fn inner(&self) -> sys::mrb_value {
        self.0
    }

    /// Whether a value is an interpreter-only variant not exposed to Ruby.
    ///
    /// Some type tags like [`MRB_TT_UNDEF`](sys::mrb_vtype::MRB_TT_UNDEF) are
    /// internal to the mruby VM and manipulating them with the [`sys`] API is
    /// unspecified and may result in a segfault.
    ///
    /// After extracting a [`sys::mrb_value`] from the interpreter, check to see
    /// if the value is [unreachable](Ruby::Unreachable) a [`Fatal`] exception.
    ///
    /// See: [mruby#4460](https://github.com/mruby/mruby/issues/4460).
    #[must_use]
    #[inline]
    pub fn is_unreachable(&self) -> bool {
        matches!(self.ruby_type(), Ruby::Unreachable)
    }

    /// Return whether this object is unreachable by any GC roots.
    #[must_use]
    pub fn is_dead(&self, interp: &mut Artichoke) -> bool {
        let value = self.inner();
        let is_dead = unsafe { interp.with_ffi_boundary(|mrb| sys::mrb_sys_value_is_dead(mrb, value)) };
        is_dead.unwrap_or_default()
    }

    pub fn is_range(&self, interp: &mut Artichoke, len: i64) -> Result<Option<protect::Range>, Error> {
        let mut arena = interp.create_arena_savepoint()?;
        let result = unsafe {
            arena
                .interp()
                .with_ffi_boundary(|mrb| protect::is_range(mrb, self.inner(), len))?
        };
        match result {
            Ok(range) => Ok(range),
            Err(exception) => {
                let exception = Self::from(exception);
                Err(exception_handler::last_error(&mut arena, exception)?)
            }
        }
    }
}

impl ValueCore for Value {
    type Artichoke = Artichoke;
    type Arg = Self;
    type Value = Self;
    type Block = Self;
    type Error = Error;

    fn funcall(
        &self,
        interp: &mut Self::Artichoke,
        func: &str,
        args: &[Self::Arg],
        block: Option<Self::Block>,
    ) -> Result<Self::Value, Self::Error> {
        if self.is_dead(interp) {
            let message = "Value receiver for function call is dead. \
                           This indicates a bug in the mruby garbage collector. \
                           Please leave a comment at https://github.com/artichoke/artichoke/issues/1336.";
            return Err(Fatal::with_message(message).into());
        }
        if let Ok(arg_count_error) = ArgCountError::try_from(args) {
            emit_fatal_warning!("Value::funcall invoked with too many arguments: {}", arg_count_error);
            return Err(arg_count_error.into());
        }
        let args = args.iter().map(Self::inner).collect::<Vec<_>>();
        let func = interp.intern_string(func.to_string())?;
        let result = unsafe {
            interp.with_ffi_boundary(|mrb| {
                protect::funcall(
                    mrb,
                    self.inner(),
                    func,
                    args.as_slice(),
                    block.as_ref().map(Self::inner),
                )
            })?
        };
        match result {
            Ok(value) => {
                let value = Self::from(value);
                if value.is_unreachable() {
                    // Unreachable values are internal to the mruby interpreter
                    // and interacting with them via the C API is unspecified
                    // and may result in a segfault.
                    //
                    // See: https://github.com/mruby/mruby/issues/4460
                    Err(Fatal::from("Unreachable Ruby value").into())
                } else {
                    Ok(interp.protect(value))
                }
            }
            Err(exception) => {
                let exception = interp.protect(Self::from(exception));
                Err(exception_handler::last_error(interp, exception)?)
            }
        }
    }

    fn freeze(&mut self, interp: &mut Self::Artichoke) -> Result<(), Self::Error> {
        self.funcall(interp, "freeze", &[], None)?;
        Ok(())
    }

    fn is_frozen(&self, interp: &mut Self::Artichoke) -> bool {
        let value = self.inner();
        let is_frozen = unsafe { interp.with_ffi_boundary(|mrb| sys::mrb_sys_obj_frozen(mrb, value)) };
        is_frozen.unwrap_or_default()
    }

    fn inspect(&self, interp: &mut Self::Artichoke) -> Vec<u8> {
        if let Ok(display) = self.funcall(interp, "inspect", &[], None) {
            display.try_convert_into_mut(interp).unwrap_or_default()
        } else {
            Vec::new()
        }
    }

    fn is_nil(&self) -> bool {
        matches!(self.ruby_type(), Ruby::Nil)
    }

    fn respond_to(&self, interp: &mut Self::Artichoke, method: &str) -> Result<bool, Self::Error> {
        // Look up a method in the mruby VM's method table for this value's
        // class object.
        let method_sym = if let Some(sym) = interp.check_interned_string(method)? {
            sym
        } else {
            interp.intern_string(String::from(method))?
        };
        let has_method =
            unsafe { interp.with_ffi_boundary(|mrb| sys::mrb_sys_value_has_method(mrb, self.inner(), method_sym))? };
        Ok(has_method)
    }

    fn to_s(&self, interp: &mut Self::Artichoke) -> Vec<u8> {
        if let Ok(display) = self.funcall(interp, "to_s", &[], None) {
            display.try_convert_into_mut(interp).unwrap_or_default()
        } else {
            Vec::new()
        }
    }

    fn ruby_type(&self) -> Ruby {
        types::ruby_from_mrb_value(self.inner())
    }
}

impl Convert<Value, Value> for Artichoke {
    fn convert(&self, value: Value) -> Value {
        value
    }
}

impl ConvertMut<Value, Value> for Artichoke {
    fn convert_mut(&mut self, value: Value) -> Value {
        value
    }
}

/// Argument count exceeds maximum allowed by the VM.
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArgCountError {
    /// Number of arguments given.
    pub given: usize,
    /// Maximum number of arguments supported.
    pub max: usize,
}

impl TryFrom<Vec<Value>> for ArgCountError {
    type Error = ();

    fn try_from(args: Vec<Value>) -> Result<Self, Self::Error> {
        if args.len() > MRB_FUNCALL_ARGC_MAX {
            Ok(Self {
                given: args.len(),
                max: MRB_FUNCALL_ARGC_MAX,
            })
        } else {
            Err(())
        }
    }
}

impl TryFrom<Vec<sys::mrb_value>> for ArgCountError {
    type Error = ();

    fn try_from(args: Vec<sys::mrb_value>) -> Result<Self, Self::Error> {
        if args.len() > MRB_FUNCALL_ARGC_MAX {
            Ok(Self {
                given: args.len(),
                max: MRB_FUNCALL_ARGC_MAX,
            })
        } else {
            Err(())
        }
    }
}

impl TryFrom<&[Value]> for ArgCountError {
    type Error = ();

    fn try_from(args: &[Value]) -> Result<Self, Self::Error> {
        if args.len() > MRB_FUNCALL_ARGC_MAX {
            Ok(Self {
                given: args.len(),
                max: MRB_FUNCALL_ARGC_MAX,
            })
        } else {
            Err(())
        }
    }
}

impl TryFrom<&[sys::mrb_value]> for ArgCountError {
    type Error = ();

    fn try_from(args: &[sys::mrb_value]) -> Result<Self, Self::Error> {
        if args.len() > MRB_FUNCALL_ARGC_MAX {
            Ok(Self {
                given: args.len(),
                max: MRB_FUNCALL_ARGC_MAX,
            })
        } else {
            Err(())
        }
    }
}

impl ArgCountError {
    /// Constructs a new, empty `ArgCountError`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            given: 0,
            max: MRB_FUNCALL_ARGC_MAX,
        }
    }
}

impl fmt::Display for ArgCountError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Too many arguments for function call: ")?;
        write!(
            f,
            "gave {} arguments, but Artichoke only supports a maximum of {} arguments",
            self.given, self.max
        )
    }
}

impl error::Error for ArgCountError {}

impl RubyException for ArgCountError {
    fn message(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(b"Too many arguments")
    }

    fn name(&self) -> Cow<'_, str> {
        "ArgumentError".into()
    }

    fn vm_backtrace(&self, interp: &mut Artichoke) -> Option<Vec<Vec<u8>>> {
        let _ = interp;
        None
    }

    fn as_mrb_value(&self, interp: &mut Artichoke) -> Option<sys::mrb_value> {
        let message = interp.try_convert_mut(self.to_string()).ok()?;
        let value = interp.new_instance::<ArgumentError>(&[message]).ok().flatten()?;
        Some(value.inner())
    }
}

impl From<ArgCountError> for Error {
    fn from(exception: ArgCountError) -> Self {
        let err: Box<dyn RubyException> = Box::new(exception);
        Self::from(err)
    }
}

#[cfg(test)]
mod tests {
    use bstr::ByteSlice;

    use crate::gc::MrbGarbageCollection;
    use crate::test::prelude::*;

    #[test]
    fn to_s_true() {
        let mut interp = interpreter();

        let value = interp.convert(true);
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"true".as_bstr());
    }

    #[test]
    fn inspect_true() {
        let mut interp = interpreter();

        let value = interp.convert(true);
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), b"true".as_bstr());
    }

    #[test]
    fn to_s_false() {
        let mut interp = interpreter();

        let value = interp.convert(false);
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"false".as_bstr());
    }

    #[test]
    fn inspect_false() {
        let mut interp = interpreter();

        let value = interp.convert(false);
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), b"false".as_bstr());
    }

    #[test]
    fn to_s_nil() {
        let mut interp = interpreter();

        let value = Value::nil();
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"".as_bstr());
    }

    #[test]
    fn inspect_nil() {
        let mut interp = interpreter();

        let value = Value::nil();
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), b"nil".as_bstr());
    }

    #[test]
    fn to_s_fixnum() {
        let mut interp = interpreter();

        let value = Convert::<_, Value>::convert(&*interp, 255);
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"255".as_bstr());
    }

    #[test]
    fn inspect_fixnum() {
        let mut interp = interpreter();

        let value = Convert::<_, Value>::convert(&*interp, 255);
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), b"255".as_bstr());
    }

    #[test]
    fn to_s_string() {
        let mut interp = interpreter();

        let value = interp.try_convert_mut("interstate").unwrap();
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"interstate".as_bstr());
    }

    #[test]
    fn inspect_string() {
        let mut interp = interpreter();

        let value = interp.try_convert_mut("interstate").unwrap();
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), br#""interstate""#.as_bstr());
    }

    #[test]
    fn to_s_empty_string() {
        let mut interp = interpreter();

        let value = interp.try_convert_mut("").unwrap();
        let string = value.to_s(&mut interp);
        assert_eq!(string.as_bstr(), b"".as_bstr());
    }

    #[test]
    fn inspect_empty_string() {
        let mut interp = interpreter();

        let value = interp.try_convert_mut("").unwrap();
        let debug = value.inspect(&mut interp);
        assert_eq!(debug.as_bstr(), br#""""#.as_bstr());
    }

    #[test]
    fn is_dead() {
        let mut interp = interpreter();
        let mut arena = interp.create_arena_savepoint().unwrap();
        let live = arena.eval(b"'dead'").unwrap();
        assert!(!live.is_dead(&mut arena));

        let dead = live;
        let live = arena.eval(b"'live'").unwrap();
        arena.restore();
        interp.full_gc().unwrap();

        // unreachable objects are dead after a full garbage collection
        assert!(dead.is_dead(&mut interp));
        // the result of the most recent eval is always live even after a full
        // garbage collection
        assert!(!live.is_dead(&mut interp));
    }

    #[test]
    fn funcall_is_dead() {
        let mut interp = interpreter();
        let mut arena = interp.create_arena_savepoint().unwrap();

        let dead = arena.eval(b"'dead'").unwrap();
        arena.eval(b"'live'").unwrap();
        arena.restore();
        interp.full_gc().unwrap();

        assert!(dead.is_dead(&mut interp));

        let error = dead.funcall(&mut interp, "nil?", &[], None).unwrap_err();
        assert_eq!(error.name().as_ref(), "fatal");
    }

    #[test]
    fn immediate_is_dead() {
        let mut interp = interpreter();
        let mut arena = interp.create_arena_savepoint().unwrap();
        let live = arena.eval(b"27").unwrap();
        assert!(!live.is_dead(&mut arena));

        let immediate = live;
        let live = arena.eval(b"64").unwrap();
        arena.restore();
        interp.full_gc().unwrap();

        // immediate objects are never dead
        assert!(!immediate.is_dead(&mut interp));
        // the result of the most recent eval is always live even after a full
        // garbage collection
        assert!(!live.is_dead(&mut interp));

        // `Fixnum`s are immediate even if they are created directly without an
        // interpreter.
        let fixnum = Convert::<_, Value>::convert(&*interp, 99);
        assert!(!fixnum.is_dead(&mut interp));
    }

    #[test]
    fn funcall_nil_nil() {
        let mut interp = interpreter();

        let nil = Value::nil();
        let result = nil
            .funcall(&mut interp, "nil?", &[], None)
            .and_then(|value| value.try_convert_into::<bool>(&interp));
        let nil_is_nil = unwrap_or_panic_with_backtrace(&mut interp, "Value::funcall", result);
        assert!(nil_is_nil);
    }

    #[test]
    fn funcall_string_nil() {
        let mut interp = interpreter();

        let s = interp.try_convert_mut("foo").unwrap();
        let result = s
            .funcall(&mut interp, "nil?", &[], None)
            .and_then(|value| value.try_convert_into::<bool>(&interp));
        let string_is_nil = unwrap_or_panic_with_backtrace(&mut interp, "Value::funcall", result);
        assert!(!string_is_nil);
    }

    #[test]
    #[cfg(feature = "core-regexp")]
    fn funcall_string_split_regexp() {
        let mut interp = interpreter();

        let s = interp.try_convert_mut("foo").unwrap();
        let delim = interp.try_convert_mut("").unwrap();
        let result = s
            .funcall(&mut interp, "split", &[delim], None)
            .and_then(|value| value.try_convert_into_mut::<Vec<&str>>(&mut interp));
        let split = unwrap_or_panic_with_backtrace(&mut interp, "Value::funcall", result);
        assert_eq!(split, vec!["f", "o", "o"]);
    }

    #[test]
    fn funcall_different_types() {
        let mut interp = interpreter();
        let nil = Value::nil();
        let s = interp.try_convert_mut("foo").unwrap();
        let result = nil
            .funcall(&mut interp, "==", &[s], None)
            .and_then(|value| value.try_convert_into::<bool>(&interp));
        let eql = unwrap_or_panic_with_backtrace(&mut interp, "Value::funcall", result);
        assert!(!eql);
    }

    #[test]
    fn funcall_type_error() {
        let mut interp = interpreter();
        let nil = Value::nil();
        let s = interp.try_convert_mut("foo").unwrap();
        let err = s
            .funcall(&mut interp, "+", &[nil], None)
            .and_then(|value| value.try_convert_into_mut::<String>(&mut interp))
            .unwrap_err();
        assert_eq!("TypeError", err.name().as_ref());
        assert_eq!(
            b"no implicit conversion of nil into String".as_bstr(),
            err.message().as_ref().as_bstr()
        );
    }

    #[test]
    fn funcall_method_not_exists() {
        let mut interp = interpreter();
        let nil = Value::nil();
        let s = interp.try_convert_mut("foo").unwrap();
        let err = nil.funcall(&mut interp, "garbage_method_name", &[s], None).unwrap_err();
        assert_eq!("NoMethodError", err.name().as_ref());
        assert_eq!(
            b"undefined method 'garbage_method_name'".as_bstr(),
            err.message().as_ref().as_bstr()
        );
    }

    #[test]
    fn value_respond_to() {
        let mut interp = interpreter();
        let nil = Value::nil();
        assert!(nil.respond_to(&mut interp, "nil?").unwrap());
        assert!(nil.respond_to(&mut interp, "class").unwrap());
        assert!(!nil.respond_to(&mut interp, "zyxw_not_a_method").unwrap());

        let object = interp.eval(b"Object.new").unwrap();
        assert!(object.respond_to(&mut interp, "class").unwrap());
        assert!(object.respond_to(&mut interp, "freeze").unwrap());
        assert!(!object.respond_to(&mut interp, "zyxw_not_a_method").unwrap());

        let array = interp.eval(b"[1, 2, 3]").unwrap();
        assert!(array.respond_to(&mut interp, "class").unwrap());
        assert!(array.respond_to(&mut interp, "length").unwrap());
        assert!(!array.respond_to(&mut interp, "zyxw_not_a_method").unwrap());
    }

    #[test]
    fn value_respond_to_basic_object() {
        let mut interp = interpreter();

        // `BasicObject` does not have `#respond_to?` and relies on
        // `Value::respond_to` being implemented with VM method table lookups.
        let basic_object = interp.eval(b"BasicObject.new").unwrap();
        assert!(basic_object.respond_to(&mut interp, "__send__").unwrap());
        assert!(!basic_object.respond_to(&mut interp, "class").unwrap());
        assert!(!basic_object.respond_to(&mut interp, "zyxw_not_a_method").unwrap());
    }
}