rutie 0.14.0

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
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
use crate::rubysys::types::{
    c_char, c_int, c_void, size_t, Argc, BlockCallFunction, CallbackMutPtr, CallbackPtr, Id, Value,
    VmPointer,
};

#[cfg_attr(rutie_dllimport, link(name = "rutie_ruby"))]
extern "C" {
    // RUBY_EXTERN VALUE rb_argv0;
    //
    // The script name given to `ruby_options`; `Qfalse` (0) until it runs.
    pub static rb_argv0: Value;
    // void
    // ruby_init(void)
    pub fn ruby_init();
    // void
    // ruby_init_loadpath(void)
    pub fn ruby_init_loadpath();
    // void
    // ruby_vm_at_exit(void(*func)(ruby_vm_t *))
    pub fn ruby_vm_at_exit(func: VmPointer);
    // VALUE
    // rb_block_proc(void)
    pub fn rb_block_proc() -> Value;
    // int
    // rb_block_given_p(void)
    pub fn rb_block_given_p() -> c_int;
    // VALUE
    // rb_errinfo(void)
    pub fn rb_errinfo() -> Value;
    // VALUE
    // rb_eval_string(const char *str)
    pub fn rb_eval_string(string: *const c_char) -> Value;
    // VALUE
    // rb_eval_string_protect(const char *str, int *pstate)
    pub fn rb_eval_string_protect(string: *const c_char, state: *mut c_int) -> Value;
    // VALUE
    // rb_f_abort(int argc, const VALUE *argv)
    pub fn rb_f_abort(argc: Argc, argv: *const Value) -> Value;
    // //////////////// UNAVAILABLE METHOD ////////////////
    // // VALUE
    // // rb_f_eval(int argc, const VALUE *argv, VALUE self)
    // pub fn rb_f_eval(argc: c_int, argv: *const Value, self_: Value) -> Value;
    // ///////////////// ///////////////// ///////////////
    // void
    // rb_exc_raise(VALUE mesg)
    pub fn rb_exc_raise(exception: Value) -> !;
    // void
    // rb_exit(int status)
    pub fn rb_exit(status: c_int);
    // void
    // rb_raise(VALUE exc, const char *fmt, ...)
    //
    // `fmt` is a printf format; never pass untrusted text as `fmt`.
    pub fn rb_raise(exception: Value, fmt: *const c_char, ...) -> !;
    // VALUE
    // rb_require(const char *fname)
    pub fn rb_require(name: *const c_char) -> Value;
    // void
    // rb_set_errinfo(VALUE err)
    pub fn rb_set_errinfo(err: Value);
    // VALUE
    // rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate)
    pub fn rb_protect(func: CallbackPtr, args: *const c_void, state: *mut c_int) -> Value;
    // VALUE
    // rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
    pub fn rb_funcallv(receiver: Value, method: Id, argc: Argc, argv: *const Value) -> Value;
    // VALUE
    // rb_funcallv_public(VALUE recv, ID mid, int argc, const VALUE *argv)
    pub fn rb_funcallv_public(receiver: Value, method: Id, argc: Argc, argv: *const Value)
        -> Value;
    // VALUE
    // rb_block_call(VALUE obj, ID mid, int argc, const VALUE * argv,
    //               VALUE (*bl_proc) (ANYARGS), VALUE data2)
    pub fn rb_block_call(
        obj: Value,
        method_id: Id,
        argc: Argc,
        argv: *const Value,
        block: BlockCallFunction,
        outer_scope: Value,
    ) -> Value;
    // VALUE
    // rb_yield_splat(VALUE values)
    pub fn rb_yield_splat(values: Value) -> Value;
    // VALUE
    // rb_yield_values2(int n, const VALUE *argv)
    pub fn rb_yield_values2(argc: Argc, argv: *const Value) -> Value;
    // VALUE
    // rb_yield(VALUE val)
    pub fn rb_yield(value: Value) -> Value;
    // VALUE
    // rb_call_super(int argc, const VALUE *argv)
    pub fn rb_call_super(argc: Argc, argv: *const Value) -> Value;
    // VALUE
    // rb_catch(const char *tag, VALUE (*func)(ANYARGS), VALUE data)
    pub fn rb_catch(tag: *const c_char, func: BlockCallFunction, data: Value) -> Value;
    // VALUE
    // rb_catch_obj(VALUE tag, VALUE (*func)(ANYARGS), VALUE data)
    pub fn rb_catch_obj(tag: Value, func: BlockCallFunction, data: Value) -> Value;
    // VALUE
    // rb_ensure(VALUE (*b_proc)(ANYARGS), VALUE data1,
    //           VALUE (*e_proc)(ANYARGS), VALUE data2)
    pub fn rb_ensure(
        body: rutie_callback!(type fn(CallbackMutPtr) -> Value),
        body_data: CallbackMutPtr,
        ensure: rutie_callback!(type fn(CallbackMutPtr) -> Value),
        ensure_data: CallbackMutPtr,
    ) -> Value;
    // VALUE
    // rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE pass_procval)
    pub fn rb_funcall_with_block(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
        procval: Value,
    ) -> Value;
    // VALUE
    // rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
    pub fn rb_funcallv_kw(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
        kw_splat: c_int,
    ) -> Value;
    // void
    // rb_iter_break(void)
    pub fn rb_iter_break() -> !;
    // void
    // rb_iter_break_value(VALUE val)
    pub fn rb_iter_break_value(value: Value) -> !;
    // void
    // rb_jump_tag(int state)
    pub fn rb_jump_tag(state: c_int) -> !;
    // int
    // rb_keyword_given_p(void)
    pub fn rb_keyword_given_p() -> c_int;
    // void
    // rb_need_block(void)
    //
    // Raises `LocalJumpError` unless a block was given.
    pub fn rb_need_block();
    // void
    // rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
    pub fn rb_obj_call_init(object: Value, argc: Argc, argv: *const Value);
    // VALUE
    // rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1,
    //           VALUE (* r_proc)(ANYARGS), VALUE data2)
    pub fn rb_rescue(
        body: rutie_callback!(type fn(CallbackMutPtr) -> Value),
        body_data: CallbackMutPtr,
        rescue: rutie_callback!(type fn(CallbackMutPtr, Value) -> Value),
        rescue_data: CallbackMutPtr,
    ) -> Value;
    // VALUE
    // rb_rescue2(VALUE (* b_proc)(ANYARGS), VALUE data1,
    //            VALUE (* r_proc)(ANYARGS), VALUE data2, ...)
    //
    // The variadic arguments are the exception classes to rescue,
    // terminated by a `0` (`Value::from(0)`).
    pub fn rb_rescue2(
        body: rutie_callback!(type fn(CallbackMutPtr) -> Value),
        body_data: CallbackMutPtr,
        rescue: rutie_callback!(type fn(CallbackMutPtr, Value) -> Value),
        rescue_data: CallbackMutPtr,
        ...
    ) -> Value;
    // void
    // rb_set_end_proc(void (*func)(VALUE), VALUE data)
    //
    // `data` is marked by the GC, so it must be a Ruby object or an
    // immediate value, never a raw pointer.
    pub fn rb_set_end_proc(func: rutie_callback!(type fn(Value)), data: Value);
    // void
    // rb_throw(const char *tag, VALUE val)
    pub fn rb_throw(tag: *const c_char, value: Value) -> !;
    // void
    // rb_throw_obj(VALUE tag, VALUE value)
    pub fn rb_throw_obj(tag: Value, value: Value) -> !;
    // int
    // ruby_cleanup(volatile int ex)
    pub fn ruby_cleanup(status: c_int) -> c_int;
    // int
    // ruby_setup(void)
    //
    // `ruby_init` without the `exit(EXIT_FAILURE)` on failure; returns the
    // tag state instead. Does nothing when the VM already exists.
    pub fn ruby_setup() -> c_int;
    // void
    // rb_ext_ractor_safe(bool flag)
    //
    // Sets whether C methods defined afterwards on this thread may run in
    // any Ractor; `require` resets it for each extension it loads.
    pub fn rb_ext_ractor_safe(flag: bool);
    // void
    // ruby_finalize(void)
    //
    // Runs the end procs and the finalizers of every object without freeing
    // the VM; no Ruby object may be used afterwards.
    pub fn ruby_finalize();
    // void *
    // ruby_options(int argc, char **argv)
    //
    // Processes `ruby(1)` command line options and compiles the script. Keeps
    // `argv` (for `$0=` and `Process.setproctitle`), which must therefore
    // live until the process exits. Only callable once per process: Ruby
    // 2.7 reads past its builtin table when it loads the prelude again.
    pub fn ruby_options(argc: c_int, argv: *mut *mut c_char) -> *mut c_void;
    // int
    // ruby_executable_node(void *n, int *status)
    pub fn ruby_executable_node(node: *mut c_void, status: *mut c_int) -> c_int;
    // int
    // ruby_exec_node(void *n)
    pub fn ruby_exec_node(node: *mut c_void) -> c_int;
    // int
    // ruby_run_node(void *n)
    //
    // `ruby_exec_node` followed by `ruby_cleanup`.
    pub fn ruby_run_node(node: *mut c_void) -> c_int;
    // void
    // ruby_script(const char *name)
    pub fn ruby_script(name: *const c_char);
    // void
    // ruby_set_script_name(VALUE name)
    pub fn ruby_set_script_name(name: Value);
    // void
    // ruby_set_argv(int argc, char **argv)
    pub fn ruby_set_argv(argc: c_int, argv: *mut *mut c_char);
    // void
    // ruby_prog_init(void)
    pub fn ruby_prog_init();
    // void
    // ruby_init_stack(volatile VALUE *addr)
    pub fn ruby_init_stack(addr: *mut Value);
    // void
    // ruby_sysinit(int *argc, char ***argv)
    //
    // Keeps `argv` like `ruby_options` does. On Windows it also sets up the
    // Win32 layer (standard handles, environment, Winsock) and must run
    // before `ruby_init`.
    pub fn ruby_sysinit(argc: *mut c_int, argv: *mut *mut *mut c_char);
    // int
    // ruby_native_thread_p(void)
    pub fn ruby_native_thread_p() -> c_int;
    // int
    // ruby_stack_check(void)
    pub fn ruby_stack_check() -> c_int;
    // size_t
    // ruby_stack_length(VALUE **p)
    pub fn ruby_stack_length(p: *mut *mut Value) -> size_t;
    // void
    // rb_clear_constant_cache_for_id(ID id)
    //
    // Invalidates the inline caches of constant lookups for the name `id`.
    pub fn rb_clear_constant_cache_for_id(id: Id);
    // void *
    // rb_ext_resolve_symbol(const char *feature, const char *symbol)
    //
    // The address of `symbol` in the native extension loaded for `feature`
    // (such as `"json/ext/parser"`); null when the feature is not loaded, is
    // not a native extension, or has no such symbol.
    pub fn rb_ext_resolve_symbol(feature: *const c_char, symbol: *const c_char) -> *mut c_void;
}

#[cfg_attr(rutie_dllimport, link(name = "rutie_ruby"))]
extern "C" {
    // Whether Ruby frees all of its memory when the VM shuts down (the
    // `RUBY_FREE_AT_EXIT` environment variable, for memory checkers). Ruby
    // 3.4+.
    //
    // bool
    // ruby_free_at_exit_p(void)
    pub fn ruby_free_at_exit_p() -> bool;
    // Raises the `NoMemoryError`-style "malloc: possible integer overflow"
    // error for `x + y`. Ruby 3.4+.
    //
    // void
    // ruby_malloc_add_size_overflow(size_t x, size_t y)
    pub fn ruby_malloc_add_size_overflow(x: size_t, y: size_t) -> !;
    // Reports a failed `RUBY_ASSERT` with a printf-style detail message and
    // aborts. Ruby 3.4+.
    //
    // void
    // rb_assert_failure_detail(const char *file, int line, const char *name,
    //                          const char *expr, const char *fmt, ...)
    pub fn rb_assert_failure_detail(
        file: *const c_char,
        line: c_int,
        name: *const c_char,
        expr: *const c_char,
        fmt: *const c_char,
        ...
    ) -> !;
}

#[cfg_attr(rutie_dllimport, link(name = "rutie_ruby"))]
extern "C" {
    // void
    // rb_backtrace(void)
    //
    // Prints the current backtrace to `$stderr`.
    pub fn rb_backtrace();
    // VALUE
    // rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
    //
    // Never returns (raises `NotImplementedError`). Defining a method with
    // this function as its body (arity -1) makes `respond_to?` false for it.
    pub fn rb_f_notimplement(argc: Argc, argv: *const Value, object: Value, marker: Value)
        -> Value;
    // int
    // rb_frame_method_id_and_class(ID *idp, VALUE *klassp)
    //
    // `0` outside a method; either pointer may be null.
    pub fn rb_frame_method_id_and_class(id: *mut Id, klass: *mut Value) -> c_int;
    // VALUE
    // rb_make_backtrace(void)
    pub fn rb_make_backtrace() -> Value;
    // const char *
    // rb_sourcefile(void)
    //
    // Null outside Ruby code.
    pub fn rb_sourcefile() -> *const c_char;
    // int
    // rb_sourceline(void)
    pub fn rb_sourceline() -> c_int;
    // VALUE
    // rb_call_super_kw(int argc, const VALUE *argv, int kw_splat)
    pub fn rb_call_super_kw(argc: Argc, argv: *const Value, kw_splat: c_int) -> Value;
    // VALUE
    // rb_current_receiver(void)
    //
    // Raises `RuntimeError` outside a method.
    pub fn rb_current_receiver() -> Value;
    // VALUE
    // rb_eval_string_wrap(const char *str, int *state)
    //
    // `rb_eval_string_protect` under an anonymous module, like
    // `load(file, true)`. The exception stays in `$!` on failure.
    pub fn rb_eval_string_wrap(string: *const c_char, state: *mut c_int) -> Value;
    // VALUE
    // rb_extract_keywords(VALUE *orighash)
    //
    // Returns a new hash of the Symbol-keyed entries of `*orighash` (or `0`
    // when there are none), and sets `*orighash` to a new hash of the other
    // entries (or `0` when there are none). The hash itself is unchanged.
    pub fn rb_extract_keywords(original: *mut Value) -> Value;
    // VALUE
    // rb_funcall(VALUE recv, ID mid, int n, ...)
    //
    // The variadic arguments are `n` `VALUE`s.
    pub fn rb_funcall(receiver: Value, method: Id, n: c_int, ...) -> Value;
    // VALUE
    // rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE *argv)
    //
    // Passes the block given to the method running.
    pub fn rb_funcall_passing_block(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
    ) -> Value;
    // VALUE
    // rb_funcall_passing_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
    pub fn rb_funcall_passing_block_kw(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
        kw_splat: c_int,
    ) -> Value;
    // VALUE
    // rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE procval, int kw_splat)
    pub fn rb_funcall_with_block_kw(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
        procval: Value,
        kw_splat: c_int,
    ) -> Value;
    // VALUE
    // rb_funcallv_public_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
    pub fn rb_funcallv_public_kw(
        receiver: Value,
        method: Id,
        argc: Argc,
        argv: *const Value,
        kw_splat: c_int,
    ) -> Value;
    // VALUE
    // rb_f_exit(int argc, const VALUE *argv)
    //
    // `Kernel#exit`: never returns (raises `SystemExit`).
    pub fn rb_f_exit(argc: Argc, argv: *const Value) -> Value;
    // ID
    // rb_frame_callee(void)
    //
    // The name the method running was called by (an alias); `0` outside a
    // method.
    pub fn rb_frame_callee() -> Id;
    // ID
    // rb_frame_this_func(void)
    //
    // The original name of the method running; `0` outside a method.
    pub fn rb_frame_this_func() -> Id;
    // VALUE
    // rb_make_exception(int argc, const VALUE *argv)
    //
    // Builds the exception `raise(*argv)` would raise; `nil` for no
    // arguments.
    pub fn rb_make_exception(argc: Argc, argv: *const Value) -> Value;
    // void
    // rb_obj_call_init_kw(VALUE, int, const VALUE*, int)
    pub fn rb_obj_call_init_kw(object: Value, argc: Argc, argv: *const Value, kw_splat: c_int);
    // VALUE
    // rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE *argv,
    //                  rb_block_call_func_t proc, VALUE data2, int kw_splat)
    pub fn rb_block_call_kw(
        obj: Value,
        method_id: Id,
        argc: Argc,
        argv: *const Value,
        block: BlockCallFunction,
        outer_scope: Value,
        kw_splat: c_int,
    ) -> Value;
    // VALUE
    // rb_each(VALUE obj)
    //
    // Calls `obj.each` with the block given to the method running.
    pub fn rb_each(object: Value) -> Value;
    // VALUE
    // rb_yield_block(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
    //
    // A block function (for `rb_block_call`) that yields its arguments to
    // the block of the method running.
    pub fn rb_yield_block(
        yielded_arg: Value,
        callback_arg: Value,
        argc: c_int,
        argv: *const Value,
        block_arg: Value,
    ) -> Value;
    // VALUE
    // rb_yield_splat_kw(VALUE ary, int kw_splat)
    pub fn rb_yield_splat_kw(values: Value, kw_splat: c_int) -> Value;
    // VALUE
    // rb_yield_values(int n, ...)
    //
    // The variadic arguments are `n` `VALUE`s.
    pub fn rb_yield_values(n: c_int, ...) -> Value;
    // VALUE
    // rb_yield_values_kw(int n, const VALUE *argv, int kw_splat)
    pub fn rb_yield_values_kw(argc: Argc, argv: *const Value, kw_splat: c_int) -> Value;
    // VALUE
    // rb_get_argv(void)
    //
    // `ARGV`.
    pub fn rb_get_argv() -> Value;
    // void *
    // rb_load_file(const char *file)
    //
    // Parses (does not run) a script, returning the node for
    // `ruby_exec_node`, or null after printing the syntax error.
    pub fn rb_load_file(file: *const c_char) -> *mut c_void;
    // void *
    // rb_load_file_str(VALUE file)
    pub fn rb_load_file_str(file: Value) -> *mut c_void;
}

// `ruby/version.h`: the running Ruby's version strings (NUL-terminated,
// read them through `as_ptr`).
#[cfg_attr(rutie_dllimport, link(name = "rutie_ruby"))]
extern "C" {
    // RUBY_EXTERN const int ruby_api_version[3];
    pub static ruby_api_version: [c_int; 3];
    // RUBY_EXTERN const char ruby_version[];
    //
    // `RUBY_VERSION`, such as `"4.0.7"`.
    pub static ruby_version: [c_char; 0];
    // RUBY_EXTERN const char ruby_release_date[];
    pub static ruby_release_date: [c_char; 0];
    // RUBY_EXTERN const char ruby_platform[];
    pub static ruby_platform: [c_char; 0];
    // RUBY_EXTERN const int  ruby_patchlevel;
    pub static ruby_patchlevel: c_int;
    // RUBY_EXTERN const char ruby_description[];
    //
    // `RUBY_DESCRIPTION` as Ruby was built (without the YJIT/ZJIT marker
    // a running Ruby adds when they are enabled).
    pub static ruby_description: [c_char; 0];
    // RUBY_EXTERN const char ruby_copyright[];
    pub static ruby_copyright: [c_char; 0];
    // RUBY_EXTERN const char ruby_engine[];
    //
    // `"ruby"`.
    pub static ruby_engine: [c_char; 0];
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        binding::symbol::internal_id,
        rubysys::{array, exception, hash, object, range, rb_cObject, rstruct},
        AnyObject, Fixnum, Object, RString, Symbol, VM,
    };

    fn inspect(value: Value) -> String {
        AnyObject::from(value).inspect_object().to_string()
    }

    fn fixnum(value: i64) -> Value {
        Fixnum::new(value).value()
    }

    #[test]
    fn test_raw_variadic_and_call_functions() {
        crate::on_ruby_thread(|| unsafe {
            let sum = rb_funcall(fixnum(40), internal_id("+"), 1, fixnum(2));
            assert_eq!(inspect(sum), "42");
            let max = rb_funcall(
                array::rb_ary_new_from_args(3, fixnum(3), fixnum(9), fixnum(4)),
                internal_id("max"),
                0,
            );
            assert_eq!(inspect(max), "9");

            let arguments = array::rb_ary_new_from_args(2, fixnum(1), fixnum(2));
            assert_eq!(
                inspect(object::rb_apply(fixnum(5), internal_id("clamp"), arguments)),
                "2"
            );

            let target = VM::eval("o = Object.new; def o.kw(a, b: 0); a + b; end; o")
                .unwrap()
                .value();
            let keywords = VM::eval("{ b: 5 }").unwrap().value();
            let argv = [fixnum(1), keywords];
            assert_eq!(
                inspect(rb_funcallv_public_kw(
                    target,
                    internal_id("kw"),
                    2,
                    argv.as_ptr(),
                    1
                )),
                "6"
            );
            let block = VM::eval("proc { |x| x * 10 }").unwrap().value();
            let list = array::rb_ary_new_from_args(2, fixnum(1), fixnum(2));
            let mapped =
                rb_funcall_with_block_kw(list, internal_id("map"), 0, std::ptr::null(), block, 0);
            assert_eq!(inspect(mapped), "[10, 20]");
            let missing =
                object::rb_check_funcall_kw(target, internal_id("nope"), 0, std::ptr::null(), 0);
            assert!(missing.is_undef());

            let hash_value = VM::eval("{ a: 1, b: 2 }").unwrap().value();
            assert_eq!(hash::rb_hash_size_num(hash_value), 2);

            let pair = array::rb_assoc_new(fixnum(1), fixnum(2));
            let copy = array::rb_ary_resurrect(pair);
            assert_eq!(inspect(copy), "[1, 2]");
            let ptr = array::rb_ary_ptr_use_start(copy);
            array::rb_mem_clear(ptr, 2);
            array::rb_ary_ptr_use_end(copy);
            assert_eq!(inspect(copy), "[nil, nil]");
            assert_eq!(inspect(pair), "[1, 2]");
            let _ = array::rb_ary_shared_with_p(pair, copy);

            let error = exception::rb_syserr_new_str(2, RString::new_utf8("file").value());
            assert!(inspect(error).starts_with("#<Errno::ENOENT"));

            let mut begin = 0;
            let mut length = 0;
            let mut step = 0;
            let sequence = VM::eval("((1..10) % 3)").unwrap().value();
            let result = range::rb_arithmetic_sequence_beg_len_step(
                sequence,
                &mut begin,
                &mut length,
                &mut step,
                20,
                0,
            );
            assert!(result.is_true());
            assert_eq!((begin, length, step), (1, 10, 3));
        });
    }

    #[test]
    fn test_raw_struct_and_wrapped_eval_functions() {
        crate::on_ruby_thread(|| unsafe {
            let point = rstruct::rb_struct_define_without_accessor(
                std::ptr::null(),
                rstruct::rb_cStruct,
                None,
                b"x\0".as_ptr() as *const c_char,
                b"y\0".as_ptr() as *const c_char,
                std::ptr::null::<c_char>(),
            );
            let instance = rstruct::rb_struct_alloc_noinit(point);
            assert!(!AnyObject::from(instance).respond_to("x"));
            rstruct::rb_struct_initialize(
                instance,
                array::rb_ary_new_from_args(2, fixnum(3), fixnum(4)),
            );
            assert_eq!(inspect(rstruct::rb_struct_aref(instance, fixnum(1))), "4");

            let mut state = 0;
            let value = rb_eval_string_wrap(b"1 + 1\0".as_ptr() as *const c_char, &mut state);
            assert_eq!((state, inspect(value)), (0, "2".to_string()));

            assert!(rb_get_argv().value != 0);
            assert!(rb_make_exception(0, std::ptr::null()).is_nil());

            let frozen = VM::eval("Object.new.freeze").unwrap().value();
            let copy = crate::binding::vm::protect_value(|| {
                exception::rb_check_copyable(frozen, rb_cObject);
                frozen
            });
            assert!(copy.is_err());
            let _ = Symbol::new("unused");
        });
    }

    // The version globals match what Ruby reports.
    #[test]
    fn test_version_globals() {
        use std::ffi::CStr;

        crate::on_ruby_thread(|| unsafe {
            let read = |string: &[c_char; 0]| CStr::from_ptr(string.as_ptr()).to_str().unwrap();
            let eval = |code: &str| VM::eval(code).unwrap().try_convert_to::<RString>().unwrap();

            assert_eq!(read(&ruby_version), eval("RUBY_VERSION").to_str());
            assert_eq!(read(&ruby_release_date), eval("RUBY_RELEASE_DATE").to_str());
            assert_eq!(read(&ruby_platform), eval("RUBY_PLATFORM").to_str());
            assert_eq!(read(&ruby_copyright), eval("RUBY_COPYRIGHT").to_str());
            assert_eq!(read(&ruby_engine), "ruby");
            assert!(read(&ruby_description).starts_with("ruby 4.0"));

            let patchlevel = VM::eval("RUBY_PATCHLEVEL")
                .unwrap()
                .try_convert_to::<Fixnum>();
            assert_eq!(patchlevel.unwrap().to_i64(), ruby_patchlevel as i64);
            assert_eq!(&ruby_api_version[..2], &[4, 0]);
        });
    }
}