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
use crate::sys;

/// Artichoke native floating point type.
///
/// `Fp` is the backend to the [`Float`](crate::extn::core::float::Float) class.
///
/// The `Fp` type alias is for the `f64` floating point primitive.
///
/// ```
/// # use std::any::TypeId;
/// # use std::mem;
/// # use artichoke_backend::types::Fp;
/// assert_eq!(mem::size_of::<f64>(), mem::size_of::<Fp>());
/// assert_eq!(TypeId::of::<f64>(), TypeId::of::<Fp>());
/// ```
pub type Fp = f64;

/// Artichoke native integer type.
///
/// `Int` is the fixed size (`Fixnum`) backend to the
/// [`Integer`](crate::extn::core::integer::Integer) class.
///
/// The `Int` type alias is for the `i64` integer primitive.
///
/// ```
/// # use std::any::TypeId;
/// # use std::mem;
/// # use artichoke_backend::types::Int;
/// assert_eq!(mem::size_of::<i64>(), mem::size_of::<Int>());
/// assert_eq!(i64::min_value(), Int::min_value());
/// assert_eq!(i64::max_value(), Int::max_value());
/// assert_eq!(TypeId::of::<i64>(), TypeId::of::<Int>());
/// ```
pub type Int = i64;

pub use crate::core::{Ruby, Rust};

/// Parse a [`Ruby`] type classifier from a [`sys::mrb_value`].
///
/// This function collapses some mruby types into a [`Ruby::Unreachable`] type
/// that force an interaction with the VM to return an error.
#[allow(non_upper_case_globals)]
#[allow(clippy::enum_glob_use)]
#[must_use]
pub fn ruby_from_mrb_value(value: sys::mrb_value) -> Ruby {
    use sys::mrb_vtype::*;

    // Suppress lint to enumerate match arms in the same order they are defined
    // in the `sys::mrb_vtype` enum C source.
    #[allow(clippy::match_same_arms)]
    match value.tt {
        // `nil` is implemented with the `MRB_TT_FALSE` type tag in mruby
        // (since both values are falsy). The difference is that booleans are
        // non-zero `Fixnum`s.
        MRB_TT_FALSE if unsafe { sys::mrb_sys_value_is_nil(value) } => Ruby::Nil,
        MRB_TT_FALSE => Ruby::Bool,
        // `MRB_TT_FREE` is a marker type tag that indicates to the mruby
        // VM that an object is unreachable and should be deallocated by the
        // garbage collector.
        MRB_TT_FREE => Ruby::Unreachable,
        MRB_TT_TRUE => Ruby::Bool,
        MRB_TT_FIXNUM => Ruby::Fixnum,
        MRB_TT_SYMBOL => Ruby::Symbol,
        // internal use: #undef; should not happen
        MRB_TT_UNDEF => Ruby::Unreachable,
        MRB_TT_FLOAT => Ruby::Float,
        // `MRB_TT_CPTR` wraps a borrowed `void *` pointer.
        MRB_TT_CPTR => Ruby::CPointer,
        MRB_TT_OBJECT => Ruby::Object,
        MRB_TT_CLASS => Ruby::Class,
        MRB_TT_MODULE => Ruby::Module,
        // `MRB_TT_ICLASS` is an internal use type tag meant for holding
        // mixed in modules.
        MRB_TT_ICLASS => Ruby::Unreachable,
        // `MRB_TT_SCLASS` represents a singleton class, or a class that is
        // defined anonymously, e.g. `c1` or `c2` below:
        //
        // ```ruby
        // c1 = Class.new {
        //   def foo; :foo; end
        // }
        // c2 = (class <<cls; self; end)
        // ```
        //
        // mruby also uses the term singleton method to refer to methods
        // defined on an object's eigenclass, e.g. `bar` below:
        //
        // ```ruby
        // class Foo; end
        // obj = Foo.new
        // def obj.bar; 'bar'; end
        // ```
        MRB_TT_SCLASS => Ruby::SingletonClass,
        MRB_TT_PROC => Ruby::Proc,
        // `MRB_TT_ARRAY` refers to the mruby `mrb_array` implementation.
        // Artichoke implements its own `Array` as a `Ruby::Data`, so this
        // variant is unreachable.
        MRB_TT_ARRAY => Ruby::Unreachable,
        MRB_TT_HASH => Ruby::Hash,
        MRB_TT_STRING => Ruby::String,
        MRB_TT_RANGE => Ruby::Range,
        MRB_TT_EXCEPTION => Ruby::Exception,
        // This is a special value type for the `mruby-io` implementation of
        // the `File` class. Artichoke does not bundle `mruby-io`, so this
        // variant is unreachable.
        MRB_TT_FILE => Ruby::Unreachable,
        // ENV is currently implemented as a singleton object in Ruby.
        // NOTE(lopopolo): This might be an internal closure symbol table,
        // rather than the `ENV` core object.
        MRB_TT_ENV => Ruby::Unreachable,
        // `MRB_TT_DATA` is a type tag for wrapped C pointers. It is used
        // to indicate that an `mrb_value` has an owned pointer to an
        // external data structure stored in its `value.p` field.
        MRB_TT_DATA => Ruby::Data,
        // NOTE(lopopolo): `Fiber`s are unimplemented in Artichoke.
        MRB_TT_FIBER => Ruby::Fiber,
        // MRB_TT_ISTRUCT is an "inline structure", or a mrb_value that
        // stores data in a char* buffer inside an mrb_value. These
        // mrb_values cannot have a finalizer and cannot have instance
        // variables.
        //
        // See vendor/mruby-*/include/mruby/istruct.h
        MRB_TT_ISTRUCT => Ruby::InlineStruct,
        // `MRB_TT_BREAK` is used internally to the mruby VM. BREAK is used as
        // the return value of `mrb_yield` when the block has a non-local
        // return.
        //
        // FIXME(lopopolo): The below "unreachable" designation is incorrect.
        // BREAK should be handled by `sys::protect::block_yield`.
        MRB_TT_BREAK => Ruby::Unreachable,
        // `MRB_TT_MAXDEFINE` is a marker enum value used by the mruby VM to
        // dynamically check if a type tag is valid using the less than
        // operator. It does not correspond to an instantiated type.
        MRB_TT_MAXDEFINE => Ruby::Unreachable,
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use crate::test::prelude::*;
    use crate::types;

    #[test]
    fn parse_nil_ruby_type() {
        let nil = Value::nil();
        assert_eq!(Ruby::Nil, types::ruby_from_mrb_value(nil.inner()));
    }

    #[test]
    fn parse_bool_ruby_type() {
        let interp = interpreter().unwrap();
        let yes = interp.convert(true);
        assert_eq!(Ruby::Bool, types::ruby_from_mrb_value(yes.inner()));
        let no = interp.convert(false);
        assert_eq!(Ruby::Bool, types::ruby_from_mrb_value(no.inner()));
    }

    #[test]
    fn parse_fixnum_ruby_type() {
        let interp = interpreter().unwrap();
        let zero = interp.convert(0_i64);
        assert_eq!(Ruby::Fixnum, types::ruby_from_mrb_value(zero.inner()));
        let thousand = interp.convert(1000_i64);
        assert_eq!(Ruby::Fixnum, types::ruby_from_mrb_value(thousand.inner()));
    }

    #[test]
    fn parse_symbol_ruby_type() {
        let mut interp = interpreter().unwrap();
        let empty = interp.eval(b":''").unwrap();
        assert_eq!(Ruby::Symbol, types::ruby_from_mrb_value(empty.inner()));
        let utf8 = interp.eval(b":Artichoke").unwrap();
        assert_eq!(Ruby::Symbol, types::ruby_from_mrb_value(utf8.inner()));
        let binary = interp.eval(r#":"\xFE""#.as_bytes()).unwrap();
        assert_eq!(Ruby::Symbol, types::ruby_from_mrb_value(binary.inner()));
    }

    #[test]
    fn parse_float_ruby_type() {
        let mut interp = interpreter().unwrap();
        let zero = interp.convert_mut(0.0_f64);
        assert_eq!(Ruby::Float, types::ruby_from_mrb_value(zero.inner()));
        let float = interp.convert_mut(1.5_f64);
        assert_eq!(Ruby::Float, types::ruby_from_mrb_value(float.inner()));
    }

    #[test]
    fn parse_object_ruby_type() {
        let mut interp = interpreter().unwrap();
        let object = interp.eval(b"Object.new").unwrap();
        assert_eq!(Ruby::Object, types::ruby_from_mrb_value(object.inner()));
        let env = interp.eval(b"ENV").unwrap();
        assert_eq!(Ruby::Object, types::ruby_from_mrb_value(env.inner()));
    }

    #[test]
    fn parse_class_ruby_type() {
        let mut interp = interpreter().unwrap();
        let builtin = interp.eval(b"Object").unwrap();
        assert_eq!(Ruby::Class, types::ruby_from_mrb_value(builtin.inner()));
        let data = interp.eval(b"Array").unwrap();
        assert_eq!(Ruby::Class, types::ruby_from_mrb_value(data.inner()));
        let source = interp.eval(b"Math::DomainError").unwrap();
        assert_eq!(Ruby::Class, types::ruby_from_mrb_value(source.inner()));
    }

    #[test]
    fn parse_module_ruby_type() {
        let mut interp = interpreter().unwrap();
        let builtin = interp.eval(b"Comparable").unwrap();
        assert_eq!(Ruby::Module, types::ruby_from_mrb_value(builtin.inner()));
        let data = interp.eval(b"Math").unwrap();
        assert_eq!(Ruby::Module, types::ruby_from_mrb_value(data.inner()));
        let artichoke = interp.eval(b"Artichoke").unwrap();
        assert_eq!(Ruby::Module, types::ruby_from_mrb_value(artichoke.inner()));
    }

    #[test]
    fn parse_proc_ruby_type() {
        let mut interp = interpreter().unwrap();
        let literal = interp.eval(b"proc {}").unwrap();
        assert_eq!(Ruby::Proc, types::ruby_from_mrb_value(literal.inner()));
        let proc = interp.eval(b"Proc.new {}").unwrap();
        assert_eq!(Ruby::Proc, types::ruby_from_mrb_value(proc.inner()));
        let lambda = interp.eval(b"lambda {}").unwrap();
        assert_eq!(Ruby::Proc, types::ruby_from_mrb_value(lambda.inner()));
        let stabby = interp.eval(b"->() {}").unwrap();
        assert_eq!(Ruby::Proc, types::ruby_from_mrb_value(stabby.inner()));
    }

    #[test]
    fn parse_string_ruby_type() {
        let mut interp = interpreter().unwrap();
        let empty = interp.convert_mut("");
        assert_eq!(Ruby::String, types::ruby_from_mrb_value(empty.inner()));
        let utf8 = interp.convert_mut("Artichoke");
        assert_eq!(Ruby::String, types::ruby_from_mrb_value(utf8.inner()));
        let binary = interp.convert_mut(vec![0xFF_u8, 0x00, 0xFE]);
        assert_eq!(Ruby::String, types::ruby_from_mrb_value(binary.inner()));
    }

    #[test]
    fn parse_array_ruby_type() {
        let mut interp = interpreter().unwrap();
        let empty = interp.eval(b"[]").unwrap();
        assert_eq!(Ruby::Data, types::ruby_from_mrb_value(empty.inner()));
        let array = interp.eval(b"[1, /./, Object.new]").unwrap();
        assert_eq!(Ruby::Data, types::ruby_from_mrb_value(array.inner()));
        let ary = vec!["a", "b", "c"];
        let converted = interp.try_convert_mut(ary).unwrap();
        assert_eq!(Ruby::Data, types::ruby_from_mrb_value(converted.inner()));
    }

    #[test]
    fn parse_hash_ruby_type() {
        let mut interp = interpreter().unwrap();
        let empty = interp.eval(b"{}").unwrap();
        assert_eq!(Ruby::Hash, types::ruby_from_mrb_value(empty.inner()));
        let hash = interp.eval(b"{a: 1, b: [/./]}").unwrap();
        assert_eq!(Ruby::Hash, types::ruby_from_mrb_value(hash.inner()));
        let mut map = HashMap::default();
        map.insert(b"a".to_vec(), vec![0_u8]);
        map.insert(b"b".to_vec(), b"binary".to_vec());
        let converted = interp.convert_mut(map);
        assert_eq!(Ruby::Hash, types::ruby_from_mrb_value(converted.inner()));
    }

    #[test]
    fn parse_range_ruby_type() {
        let mut interp = interpreter().unwrap();
        let dot2 = interp.eval(b"0..0").unwrap();
        assert_eq!(Ruby::Range, types::ruby_from_mrb_value(dot2.inner()));
        let dot3 = interp.eval(b"0...0").unwrap();
        assert_eq!(Ruby::Range, types::ruby_from_mrb_value(dot3.inner()));
    }

    #[test]
    fn parse_exception_ruby_type() {
        let mut interp = interpreter().unwrap();
        let root = interp.eval(b"Exception.new").unwrap();
        assert_eq!(Ruby::Exception, types::ruby_from_mrb_value(root.inner()));
        let stderror = interp.eval(b"StandardError.new").unwrap();
        assert_eq!(
            Ruby::Exception,
            types::ruby_from_mrb_value(stderror.inner())
        );
        let index = interp.eval(b"IndexError.new").unwrap();
        assert_eq!(Ruby::Exception, types::ruby_from_mrb_value(index.inner()));
        let domain = interp.eval(b"Math::DomainError.new").unwrap();
        assert_eq!(Ruby::Exception, types::ruby_from_mrb_value(domain.inner()));
    }
}