rutie 0.14.1

The tie between Ruby and Rust.
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
use std::ffi::CStr;

use crate::{
    binding::symbol,
    helpers::scan_args::ScanArgsFormat,
    rubysys::{class, typed_data, types::RBasic, variable},
    typed_data::DataTypeWrapper,
    types::{c_int, c_void, Callback, CallbackPtr, Id, Value, ValueType},
    util, Object,
};

pub fn define_class(name: &str, superclass: Value) -> Value {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_class(name.as_ptr(), superclass) }
}

pub fn define_nested_class(outer: Value, name: &str, superclass: Value) -> Value {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_class_under(outer, name.as_ptr(), superclass) }
}

pub fn const_get(klass: Value, name: &str) -> Value {
    unsafe { class::rb_const_get(klass, symbol::internal_id(name)) }
}

pub fn const_set(klass: Value, name: &str, value: Value) {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_const(klass, name.as_ptr(), value) };
}

pub fn object_class(object: Value) -> Value {
    unsafe { class::rb_obj_class(object) }
}

pub fn superclass(klass: Value) -> Value {
    unsafe { class::rb_class_superclass(klass) }
}

pub fn singleton_class(object: Value) -> Value {
    unsafe { class::rb_singleton_class(object) }
}

pub fn ancestors(klass: Value) -> Value {
    unsafe { class::rb_mod_ancestors(klass) }
}

pub fn new_instance(klass: Value, arguments: &[Value]) -> Value {
    let (argc, argv) = util::process_arguments(arguments);

    unsafe { class::rb_class_new_instance(argc, argv, klass) }
}

pub fn instance_variable_get(object: Value, name: &str) -> Value {
    unsafe { class::rb_ivar_get(object, symbol::internal_id(name)) }
}

pub fn instance_variable_set(object: Value, name: &str, value: Value) -> Value {
    unsafe { class::rb_ivar_set(object, symbol::internal_id(name), value) }
}

pub fn define_attribute(object: Value, name: &str, reader: bool, writer: bool) {
    let name = util::str_to_cstring(name);
    let reader = util::bool_to_c_int(reader);
    let writer = util::bool_to_c_int(writer);

    unsafe { class::rb_define_attr(object, name.as_ptr(), reader, writer) };
}

pub fn respond_to(object: Value, method: &str) -> bool {
    let result = unsafe { class::rb_respond_to(object, symbol::internal_id(method)) };

    util::c_int_to_bool(result)
}

pub fn define_method<I: Object, O: Object>(klass: Value, name: &str, callback: Callback<I, O>) {
    let name = util::str_to_cstring(name);

    unsafe {
        class::rb_define_method(klass, name.as_ptr(), callback as CallbackPtr, -1);
    }
}

pub fn define_private_method<I: Object, O: Object>(
    klass: Value,
    name: &str,
    callback: Callback<I, O>,
) {
    let name = util::str_to_cstring(name);

    unsafe {
        class::rb_define_private_method(klass, name.as_ptr(), callback as CallbackPtr, -1);
    }
}

pub fn define_singleton_method<I: Object, O: Object>(
    klass: Value,
    name: &str,
    callback: Callback<I, O>,
) {
    let name = util::str_to_cstring(name);

    unsafe {
        class::rb_define_singleton_method(klass, name.as_ptr(), callback as CallbackPtr, -1);
    }
}

pub fn wrap_data<T>(klass: Value, data: T, wrapper: &dyn DataTypeWrapper<T>) -> Value {
    let data = Box::into_raw(Box::new(data)) as *mut c_void;

    unsafe { typed_data::rb_data_typed_object_wrap(klass, data, wrapper.data_type()) }
}

pub fn get_data<T>(object: Value, wrapper: &dyn DataTypeWrapper<T>) -> &mut T {
    unsafe {
        let data = typed_data::rb_check_typeddata(object, wrapper.data_type());

        &mut *(data as *mut T)
    }
}

pub fn is_frozen(object: Value) -> Value {
    unsafe { class::rb_obj_frozen_p(object) }
}

pub fn freeze(object: Value) -> Value {
    unsafe { class::rb_obj_freeze(object) }
}

pub fn is_eql(object1: Value, object2: Value) -> bool {
    util::c_int_to_bool(unsafe { class::rb_eql(object1, object2) })
}

pub fn equals(object1: Value, object2: Value) -> Value {
    unsafe { class::rb_equal(object1, object2) }
}

pub fn is_kind_of(object: Value, klass: Value) -> bool {
    unsafe { class::rb_obj_is_kind_of(object, klass) }.is_true()
}

pub fn define_alias(klass: Value, new_name: &str, old_name: &str) {
    let new_name = util::str_to_cstring(new_name);
    let old_name = util::str_to_cstring(old_name);

    unsafe { class::rb_define_alias(klass, new_name.as_ptr(), old_name.as_ptr()) };
}

pub fn undef_method(klass: Value, name: &str) {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_undef_method(klass, name.as_ptr()) };
}

pub fn define_alloc_func(klass: Value, func: class::AllocFunction) {
    unsafe { class::rb_define_alloc_func(klass, func) };
}

pub fn undef_alloc_func(klass: Value) {
    unsafe { class::rb_undef_alloc_func(klass) };
}

// Looks up the keywords in `table` (required ones first) in `keyword_hash`
// (an empty hash when it is `nil`), writing them to `values`. Found keys are
// removed from `keyword_hash`; missing optional keywords are left `Qundef`.
// Raises `ArgumentError` for missing required or (unless `allow_extra`)
// unknown keywords, so the caller owns `table` and `values`.
pub fn get_kwargs(
    keyword_hash: Value,
    table: &[Id],
    required: usize,
    allow_extra: bool,
    values: &mut [Value],
) {
    assert!(required <= table.len() && values.len() >= table.len());

    let optional = (table.len() - required) as c_int;
    let optional = if allow_extra { -1 - optional } else { optional };

    unsafe {
        class::rb_get_kwargs(
            keyword_hash,
            table.as_ptr(),
            required as c_int,
            optional,
            values.as_mut_ptr(),
        )
    };
}

// The most `VALUE *` outputs any `rb_scan_args` format can have:
// 9 required + 9 optional + splat + 9 post + keywords + block.
pub const SCAN_ARGS_MAX_VARIABLES: usize = 30;

// `rb_scan_args` takes one `VALUE *` per variable in `format`. C ignores
// surplus variadic arguments, so all `SCAN_ARGS_MAX_VARIABLES` slots of
// `out` are always passed and `rb_scan_args` fills as many as it needs.
//
// Raises `ArgumentError` on an arity mismatch, so the caller owns `format`
// and `out`.
// How a trailing `Hash` is treated (`rb_scan_args_kw`'s `kw_flag`).
pub const SCAN_ARGS_PASS_CALLED_KEYWORDS: c_int = 0;
pub const SCAN_ARGS_LAST_HASH_KEYWORDS: c_int = 3;

pub fn scan_args(
    arguments: &[Value],
    format: &CStr,
    out: &mut [Value; SCAN_ARGS_MAX_VARIABLES],
    kw_flag: c_int,
) -> c_int {
    // `rb_scan_args` aborts the process on a format it cannot parse.
    let valid = format
        .to_str()
        .map(|format| ScanArgsFormat::parse(format).is_ok())
        .unwrap_or(false);
    assert!(valid, "invalid scan args format");

    let (argc, argv) = util::process_arguments(arguments);
    let o = out.as_mut_ptr();

    unsafe {
        class::rb_scan_args_kw(
            kw_flag,
            argc,
            argv,
            format.as_ptr(),
            o,
            o.add(1),
            o.add(2),
            o.add(3),
            o.add(4),
            o.add(5),
            o.add(6),
            o.add(7),
            o.add(8),
            o.add(9),
            o.add(10),
            o.add(11),
            o.add(12),
            o.add(13),
            o.add(14),
            o.add(15),
            o.add(16),
            o.add(17),
            o.add(18),
            o.add(19),
            o.add(20),
            o.add(21),
            o.add(22),
            o.add(23),
            o.add(24),
            o.add(25),
            o.add(26),
            o.add(27),
            o.add(28),
            o.add(29),
        )
    }
}

pub fn is_method_defined(klass: Value, name: &str, include_private: bool) -> bool {
    // `ex` bit 0x01 leaves out private methods.
    let ex = if include_private { 0 } else { 1 };

    unsafe { class::rb_method_boundp(klass, symbol::internal_id(name), ex) != 0 }
}

pub fn class_name(klass: Value) -> Value {
    unsafe { class::rb_class_name(klass) }
}

pub fn class_path(klass: Value) -> Value {
    unsafe { class::rb_class_path(klass) }
}

pub fn module_name(module: Value) -> Value {
    unsafe { class::rb_mod_name(module) }
}

pub fn inherited_p(module: Value, other: Value) -> Value {
    unsafe { class::rb_class_inherited_p(module, other) }
}

pub fn include_p(module: Value, other: Value) -> bool {
    unsafe { class::rb_mod_include_p(module, other) }.is_true()
}

pub fn module_eval(module: Value, code: &str) -> Value {
    let arguments = [crate::binding::string::new_utf8(code)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe { class::rb_mod_module_eval(argc, argv, module) }
}

pub fn instance_methods(module: Value, include_inherited: bool) -> Value {
    let arguments = [util::bool_to_value(include_inherited)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe { class::rb_class_instance_methods(argc, argv, module) }
}

pub fn is_class_variable_defined(klass: Value, name: &str) -> bool {
    unsafe { class::rb_cvar_defined(klass, symbol::internal_id(name)) }.is_true()
}

pub fn class_variable_get(klass: Value, name: &str) -> Value {
    unsafe { class::rb_cvar_get(klass, symbol::internal_id(name)) }
}

pub fn class_variable_set(klass: Value, name: &str, value: Value) {
    unsafe { class::rb_cvar_set(klass, symbol::internal_id(name), value) }
}

pub fn is_const_defined(klass: Value, name: &str) -> bool {
    util::c_int_to_bool(unsafe { class::rb_const_defined(klass, symbol::internal_id(name)) })
}

pub fn is_const_defined_at(klass: Value, name: &str) -> bool {
    util::c_int_to_bool(unsafe { class::rb_const_defined_at(klass, symbol::internal_id(name)) })
}

pub fn const_remove(module: Value, name: &str) -> Value {
    unsafe { class::rb_const_remove(module, symbol::internal_id(name)) }
}

// Raises `ArgumentError` for an unknown path, so the caller owns `path`.
pub fn path_to_class(path: &CStr) -> Value {
    unsafe { class::rb_path2class(path.as_ptr()) }
}

pub fn define_global_const(name: &str, value: Value) {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_global_const(name.as_ptr(), value) }
}

pub fn subclasses(klass: Value) -> Value {
    unsafe { class::rb_class_subclasses(klass) }
}

// Raises `TypeError` unless `klass` is a singleton class.
pub fn attached_object(klass: Value) -> Value {
    unsafe { class::rb_class_attached_object(klass) }
}

pub fn refinement_new() -> Value {
    unsafe { class::rb_refinement_new() }
}

// Returns the value of the class variable and the class or module that
// defines it. Raises `NameError` when it is not defined, and `RuntimeError`
// when a class and its ancestor both define it ("overtaken").
pub fn class_variable_find(klass: Value, name: &str) -> (Value, Value) {
    let mut front = Value::from(0);
    let value = unsafe { class::rb_cvar_find(klass, symbol::internal_id(name), &mut front) };

    // A module in the ancestors is found through its `T_ICLASS`, which must
    // not reach Ruby; its `klass` is the module itself.
    if front.ty() == ValueType::IClass {
        front = Value::from(unsafe { (*(front.value as *const RBasic)).klass });
    }

    (value, front)
}

// Raises `NameError` when `module` does not define the constant itself, and
// `FrozenError` when it is frozen, so the caller owns `name`.
pub fn deprecate_constant(module: Value, name: &CStr) {
    unsafe { class::rb_deprecate_constant(module, name.as_ptr()) }
}

// An anonymous class with its own metaclass, so class methods of
// `superclass` are inherited; `inherited` is not called. Raises `TypeError`
// when `superclass` cannot be subclassed.
pub fn new_anonymous_class(superclass: Value) -> Value {
    unsafe { class::rb_define_class_id(0, superclass) }
}

pub fn new_anonymous_module() -> Value {
    unsafe { class::rb_module_new() }
}

pub fn check_inheritable(klass: Value) {
    unsafe { class::rb_check_inheritable(klass) }
}

pub fn class_real(klass: Value) -> Value {
    unsafe { class::rb_class_real(klass) }
}

pub enum MethodVisibility {
    Public,
    Protected,
    Private,
}

pub fn instance_methods_with_visibility(
    module: Value,
    include_inherited: bool,
    visibility: MethodVisibility,
) -> Value {
    let arguments = [util::bool_to_value(include_inherited)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe {
        match visibility {
            MethodVisibility::Public => class::rb_class_public_instance_methods(argc, argv, module),
            MethodVisibility::Protected => {
                class::rb_class_protected_instance_methods(argc, argv, module)
            }
            MethodVisibility::Private => {
                class::rb_class_private_instance_methods(argc, argv, module)
            }
        }
    }
}

pub fn included_modules(module: Value) -> Value {
    unsafe { class::rb_mod_included_modules(module) }
}

pub fn singleton_methods(object: Value, include_modules: bool) -> Value {
    let arguments = [util::bool_to_value(include_modules)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe { class::rb_obj_singleton_methods(argc, argv, object) }
}

pub fn constants(module: Value, include_inherited: bool) -> Value {
    let arguments = [util::bool_to_value(include_inherited)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe { variable::rb_mod_constants(argc, argv, module) }
}

pub fn class_variables(module: Value, include_inherited: bool) -> Value {
    let arguments = [util::bool_to_value(include_inherited)];
    let (argc, argv) = util::process_arguments(&arguments);

    unsafe { variable::rb_mod_class_variables(argc, argv, module) }
}

// Raises `NameError` unless `module` itself defines the constant.
pub fn const_get_at(module: Value, name: &str) -> Value {
    unsafe { variable::rb_const_get_at(module, symbol::internal_id(name)) }
}

// Raises `NameError` when the constant is missing.
pub fn const_get_from(module: Value, name: &str) -> Value {
    unsafe { variable::rb_const_get_from(module, symbol::internal_id(name)) }
}

pub fn is_const_defined_from(module: Value, name: &str) -> bool {
    util::c_int_to_bool(unsafe {
        variable::rb_const_defined_from(module, symbol::internal_id(name))
    })
}

// Raises `NameError` when the class variable is not defined in `module`.
pub fn remove_class_variable(module: Value, name: &str) -> Value {
    let name = symbol::id_to_sym(symbol::internal_id(name));

    unsafe { variable::rb_mod_remove_cvar(module, name) }
}

pub fn autoload_path(module: Value, name: &str) -> Value {
    unsafe { variable::rb_autoload_p(module, symbol::internal_id(name)) }
}

// Raises what loading the file raises.
pub fn autoload_load(module: Value, name: &str) -> bool {
    unsafe { variable::rb_autoload_load(module, symbol::internal_id(name)) }.is_true()
}

// Raises `NameError` unless `klass` itself defines the method.
pub fn remove_method(klass: Value, name: &str) {
    unsafe { class::rb_remove_method_id(klass, symbol::internal_id(name)) }
}

pub fn is_method_basic_definition(klass: Value, name: &str) -> bool {
    util::c_int_to_bool(unsafe {
        class::rb_method_basic_definition_p(klass, symbol::internal_id(name))
    })
}

pub fn set_class_path(klass: Value, outer: Value, name: &str) {
    let name = crate::binding::string::new_utf8(name);

    unsafe { variable::rb_set_class_path_string(klass, outer, name) }
}

pub fn define_protected_method<I: Object, O: Object>(
    klass: Value,
    name: &str,
    callback: Callback<I, O>,
) {
    let name = util::str_to_cstring(name);

    unsafe {
        class::rb_define_protected_method(klass, name.as_ptr(), callback as CallbackPtr, -1);
    }
}

pub fn define_global_function<I: Object, O: Object>(name: &str, callback: Callback<I, O>) {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_global_function(name.as_ptr(), callback as CallbackPtr, -1) }
}

// A method that raises `NotImplementedError`, and that `respond_to?` reports
// as missing.
pub fn define_not_implemented_method(klass: Value, name: &str) {
    let name = util::str_to_cstring(name);

    unsafe { class::rb_define_method(klass, name.as_ptr(), notimplement_function(), -1) }
}

// The address of Ruby's own `rb_f_notimplement`, which Ruby compares against to
// mark a method as not implemented. With the GNU toolchain on Windows, Rust takes
// a function's address from the executable's import thunk, so read the import
// table entry instead. The block has no `link` attribute so the name is used as is.
#[cfg(all(windows, target_env = "gnu", rutie_dllimport))]
fn notimplement_function() -> CallbackPtr {
    extern "C" {
        #[link_name = "__imp_rb_f_notimplement"]
        static IMPORTED: CallbackPtr;
    }

    unsafe { IMPORTED }
}

#[cfg(not(all(windows, target_env = "gnu", rutie_dllimport)))]
fn notimplement_function() -> CallbackPtr {
    crate::rubysys::vm::rb_f_notimplement as CallbackPtr
}

// The last argument must be a `Hash`; it is passed as keywords.
pub fn new_instance_with_keywords(klass: Value, arguments: &[Value]) -> Value {
    let (argc, argv) = util::process_arguments(arguments);

    unsafe { class::rb_class_new_instance_kw(argc, argv, klass, 1) }
}

pub fn respond_to_including_private(object: Value, method: &str) -> bool {
    util::c_int_to_bool(unsafe {
        crate::rubysys::object::rb_obj_respond_to(object, symbol::internal_id(method), 1)
    })
}