Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
eval.c
1/**********************************************************************
2
3 eval.c -
4
5 $Author$
6 created at: Thu Jun 10 14:22:17 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
16#ifdef HAVE_SYS_PRCTL_H
17#include <sys/prctl.h>
18#endif
19
20#include "eval_intern.h"
21#include "internal.h"
22#include "internal/class.h"
23#include "internal/cont.h"
24#include "internal/error.h"
25#include "internal/eval.h"
26#include "internal/gc.h"
27#include "internal/hash.h"
28#include "internal/inits.h"
29#include "internal/io.h"
30#include "internal/object.h"
31#include "internal/thread.h"
32#include "internal/variable.h"
34#include "iseq.h"
35#include "probes.h"
36#include "probes_helper.h"
37#include "ruby/vm.h"
38#include "vm_core.h"
39#include "ractor_core.h"
40
41NORETURN(static void rb_raise_jump(VALUE, VALUE));
42void rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec);
43void rb_ec_clear_all_trace_func(const rb_execution_context_t *ec);
44
45static int rb_ec_cleanup(rb_execution_context_t *ec, enum ruby_tag_type ex);
46static int rb_ec_exec_node(rb_execution_context_t *ec, void *n);
47
50
51ID ruby_static_id_signo, ruby_static_id_status;
52extern ID ruby_static_id_cause;
53#define id_cause ruby_static_id_cause
54
55#define exception_error GET_VM()->special_exceptions[ruby_error_reenter]
56
57#include "eval_error.c"
58#include "eval_jump.c"
59
60#define CLASS_OR_MODULE_P(obj) \
61 (!SPECIAL_CONST_P(obj) && \
62 (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
63
64int
66{
67 enum ruby_tag_type state;
68
69 if (GET_VM())
70 return 0;
71
72 /*
73 * Disable THP early before mallocs happen because we want this to
74 * affect as many future pages as possible for CoW-friendliness
75 */
76#if defined(__linux__) && defined(PR_SET_THP_DISABLE)
77 prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);
78#endif
79 Init_BareVM();
80 rb_vm_encoded_insn_data_table_init();
81 Init_enable_box();
82 Init_vm_objects();
83 Init_master_box();
84 Init_fstring_table();
85
86 EC_PUSH_TAG(GET_EC());
87 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
88 rb_call_inits();
90 GET_VM()->running = 1;
91 }
92 EC_POP_TAG();
93
94 return state;
95}
96
97void
99{
100 int state = ruby_setup();
101 if (state) {
102 if (RTEST(ruby_debug)) {
103 rb_execution_context_t *ec = GET_EC();
104 rb_ec_error_print(ec, ec->errinfo);
105 }
106 exit(EXIT_FAILURE);
107 }
108}
109
110void *
111ruby_options(int argc, char **argv)
112{
113 rb_execution_context_t *ec = GET_EC();
114 enum ruby_tag_type state;
115 void *volatile iseq = 0;
116
117 EC_PUSH_TAG(ec);
118 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
119 iseq = ruby_process_options(argc, argv);
120 }
121 else {
122 rb_ec_clear_current_thread_trace_func(ec);
123 int exitcode = error_handle(ec, ec->errinfo, state);
124 ec->errinfo = Qnil; /* just been handled */
125 iseq = (void *)INT2FIX(exitcode);
126 }
127 EC_POP_TAG();
128 return iseq;
129}
130
131static void
132rb_ec_fiber_scheduler_finalize(rb_execution_context_t *ec)
133{
134 enum ruby_tag_type state;
135
136 EC_PUSH_TAG(ec);
137 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
139 }
140 else {
141 state = error_handle(ec, ec->errinfo, state);
142 }
143 EC_POP_TAG();
144}
145
146static void
147rb_ec_teardown(rb_execution_context_t *ec)
148{
149 enum ruby_tag_type state = TAG_NONE;
150 volatile VALUE trap_errinfo = Qnil;
151
152 // If the user code defined a scheduler for the top level thread, run it:
153 rb_ec_fiber_scheduler_finalize(ec);
154
155 EC_PUSH_TAG(ec);
156 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
157 rb_vm_trap_exit(rb_ec_vm_ptr(ec));
158 }
159 else {
160 trap_errinfo = ec->errinfo;
161 ec->errinfo = Qnil;
162 }
163 EC_POP_TAG();
164 rb_ec_exec_end_proc(ec);
165 if (!NIL_P(trap_errinfo)) {
166 error_handle(ec, trap_errinfo, state);
167 ec->errinfo = trap_errinfo;
168 }
169 rb_ec_clear_all_trace_func(ec);
170}
171
172static void
173rb_ec_finalize(rb_execution_context_t *ec)
174{
176 ec->errinfo = Qnil;
177 rb_objspace_call_finalizer();
178}
179
180void
182{
183 rb_execution_context_t *ec = GET_EC();
184 rb_ec_teardown(ec);
185 rb_ec_finalize(ec);
186}
187
188int
190{
191 return rb_ec_cleanup(GET_EC(), (enum ruby_tag_type)ex);
192}
193
194static int
195rb_ec_cleanup(rb_execution_context_t *ec, enum ruby_tag_type ex)
196{
197 int state;
198 volatile VALUE save_error = Qundef;
199 volatile int sysex = EXIT_SUCCESS;
200 volatile int signaled = 0;
201 rb_thread_t *th = rb_ec_thread_ptr(ec);
202 rb_thread_t *const volatile th0 = th;
203 volatile int step = 0;
204 volatile VALUE message = Qnil;
205 VALUE buf;
206
207 rb_threadptr_interrupt(th);
208 rb_threadptr_check_signal(th);
209
210 EC_PUSH_TAG(ec);
211 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
212 RUBY_VM_CHECK_INTS(ec);
213
214 step_0: step++;
215 save_error = ec->errinfo;
216 if (THROW_DATA_P(ec->errinfo)) ec->errinfo = Qnil;
217
218 /* exits with failure but silently when an exception raised
219 * here */
220 rb_ec_teardown(ec);
221
222 step_1: step++;
223 VALUE err = ec->errinfo;
224 volatile int mode0 = 0, mode1 = 0;
225 if (err != save_error && !NIL_P(err)) {
226 mode0 = exiting_split(err, &sysex, &signaled);
227 }
228
229 /* exceptions after here will be ignored */
230
231 /* build error message including causes */
232 err = ATOMIC_VALUE_EXCHANGE(save_error, Qnil);
233
234 if (!NIL_P(err) && !THROW_DATA_P(err)) {
235 mode1 = exiting_split(err, (mode0 & EXITING_WITH_STATUS) ? NULL : &sysex, &signaled);
236 if (mode1 & EXITING_WITH_MESSAGE) {
237 buf = rb_str_new(NULL, 0);
238 rb_ec_error_print_detailed(ec, err, buf, Qundef);
239 message = buf;
240 }
241 }
242
243 step_2: step++;
244 /* protect from Thread#raise */
245 th->status = THREAD_KILLED;
246
247 rb_ractor_terminate_all();
248
249 step_3: step++;
250 if (!NIL_P(buf = message)) {
251 warn_print_str(buf);
252 }
253 else if (!NIL_OR_UNDEF_P(err = save_error) ||
254 (ex != TAG_NONE && !((mode0|mode1) & EXITING_WITH_STATUS))) {
255 sysex = error_handle(ec, err, ex);
256 }
257 }
258 else {
259 th = th0;
260 switch (step) {
261 case 0: goto step_0;
262 case 1: goto step_1;
263 case 2: goto step_2;
264 case 3: goto step_3;
265 }
266 }
267
268 rb_ec_finalize(ec);
269
270 /* unlock again if finalizer took mutexes. */
271 rb_threadptr_unlock_all_locking_mutexes(th);
272 th = th0;
273 EC_POP_TAG();
274 th = th0;
275 rb_thread_stop_timer_thread();
276 ruby_vm_destruct(th->vm);
277 // For YJIT, call this after ruby_vm_destruct() frees jit_cont for the root fiber.
278 rb_jit_cont_finish();
279
280 if (signaled) ruby_default_signal(signaled);
281
282 return sysex;
283}
284
285static int
286rb_ec_exec_node(rb_execution_context_t *ec, void *n)
287{
288 volatile int state;
289 rb_iseq_t *iseq = (rb_iseq_t *)n;
290 if (!n) return 0;
291
292 EC_PUSH_TAG(ec);
293 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
294 rb_iseq_eval_main(iseq);
295 }
296 EC_POP_TAG();
297 return state;
298}
299
300void
302{
303 exit(ruby_cleanup(ex));
304}
305
306int
307ruby_executable_node(void *n, int *status)
308{
309 VALUE v = (VALUE)n;
310 int s;
311
312 switch (v) {
313 case Qtrue: s = EXIT_SUCCESS; break;
314 case Qfalse: s = EXIT_FAILURE; break;
315 default:
316 if (!FIXNUM_P(v)) return TRUE;
317 s = FIX2INT(v);
318 }
319 if (status) *status = s;
320 return FALSE;
321}
322
323int
324ruby_run_node(void *n)
325{
326 rb_execution_context_t *ec = GET_EC();
327 int status;
328 if (!ruby_executable_node(n, &status)) {
329 rb_ec_cleanup(ec, (NIL_P(ec->errinfo) ? TAG_NONE : TAG_RAISE));
330 return status;
331 }
332 return rb_ec_cleanup(ec, rb_ec_exec_node(ec, n));
333}
334
335int
337{
338 return rb_ec_exec_node(GET_EC(), n);
339}
340
341/*
342 * call-seq:
343 * Module.nesting -> array
344 *
345 * Returns the list of +Modules+ nested at the point of call.
346 *
347 * module M1
348 * module M2
349 * $a = Module.nesting
350 * end
351 * end
352 * $a #=> [M1::M2, M1]
353 * $a[0].name #=> "M1::M2"
354 */
355
356static VALUE
357rb_mod_nesting(VALUE _)
358{
359 VALUE ary = rb_ary_new();
360 const rb_cref_t *cref = rb_vm_cref();
361
362 while (cref && CREF_NEXT(cref)) {
363 VALUE klass = CREF_CLASS(cref);
364 if (!CREF_PUSHED_BY_EVAL(cref) &&
365 !NIL_P(klass)) {
366 rb_ary_push(ary, klass);
367 }
368 cref = CREF_NEXT(cref);
369 }
370 return ary;
371}
372
373/*
374 * call-seq:
375 * Module.constants -> array
376 * Module.constants(inherited) -> array
377 *
378 * In the first form, returns an array of the names of all
379 * constants accessible from the point of call.
380 * This list includes the names of all modules and classes
381 * defined in the global scope.
382 *
383 * Module.constants.first(4)
384 * # => [:ARGF, :ARGV, :ArgumentError, :Array]
385 *
386 * Module.constants.include?(:SEEK_SET) # => false
387 *
388 * class IO
389 * Module.constants.include?(:SEEK_SET) # => true
390 * end
391 *
392 * The second form calls the instance method +constants+.
393 */
394
395static VALUE
396rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
397{
398 const rb_cref_t *cref = rb_vm_cref();
399 VALUE klass;
400 VALUE cbase = 0;
401 void *data = 0;
402
403 if (argc > 0 || mod != rb_cModule) {
404 return rb_mod_constants(argc, argv, mod);
405 }
406
407 while (cref) {
408 klass = CREF_CLASS(cref);
409 if (!CREF_PUSHED_BY_EVAL(cref) &&
410 !NIL_P(klass)) {
411 data = rb_mod_const_at(CREF_CLASS(cref), data);
412 if (!cbase) {
413 cbase = klass;
414 }
415 }
416 cref = CREF_NEXT(cref);
417 }
418
419 if (cbase) {
420 data = rb_mod_const_of(cbase, data);
421 }
422 return rb_const_list(data);
423}
424
431void
433{
434 if (SPECIAL_CONST_P(klass)) {
435 Check_Type(klass, T_CLASS);
436 }
437 if (RB_TYPE_P(klass, T_MODULE)) {
438 // TODO: shouldn't this only happen in a few places?
439 rb_class_set_initialized(klass);
440 }
441 if (OBJ_FROZEN(klass)) {
442 if (RCLASS_SINGLETON_P(klass)) {
443 klass = RCLASS_ATTACHED_OBJECT(klass);
444 }
446 }
447}
448
449NORETURN(static void rb_longjmp(rb_execution_context_t *, enum ruby_tag_type, volatile VALUE, VALUE));
450static VALUE get_errinfo(void);
451#define get_ec_errinfo(ec) rb_ec_get_errinfo(ec)
452
453static VALUE
454exc_setup_cause(VALUE exc, VALUE cause)
455{
456#if OPT_SUPPORT_JOKE
457 if (NIL_P(cause)) {
458 ID id_true_cause;
459 CONST_ID(id_true_cause, "true_cause");
460
461 cause = rb_attr_get(rb_eFatal, id_true_cause);
462 if (NIL_P(cause)) {
463 cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby");
464 rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */
465 OBJ_FREEZE(cause);
466 rb_ivar_set(rb_eFatal, id_true_cause, cause);
467 }
468 }
469#endif
470 if (!NIL_P(cause) && cause != exc) {
471 rb_ivar_set(exc, id_cause, cause);
472 if (!rb_ivar_defined(cause, id_cause)) {
473 rb_ivar_set(cause, id_cause, Qnil);
474 }
475 }
476 return exc;
477}
478
479static inline VALUE
480exc_setup_message(const rb_execution_context_t *ec, VALUE mesg, VALUE *cause)
481{
482 int nocause = 0;
483 int nocircular = 0;
484
485 if (NIL_P(mesg)) {
486 mesg = ec->errinfo;
487 if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL);
488 nocause = 1;
489 }
490 if (NIL_P(mesg)) {
491 mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
492 nocause = 0;
493 nocircular = 1;
494 }
495 if (UNDEF_P(*cause)) {
496 if (nocause) {
497 *cause = Qnil;
498 nocircular = 1;
499 }
500 else if (!rb_ivar_defined(mesg, id_cause)) {
501 *cause = get_ec_errinfo(ec);
502 }
503 else {
504 nocircular = 1;
505 }
506 }
507 else if (!NIL_P(*cause) && !rb_obj_is_kind_of(*cause, rb_eException)) {
508 rb_raise(rb_eTypeError, "exception object expected");
509 }
510
511 if (!nocircular && !NIL_P(*cause) && !UNDEF_P(*cause) && *cause != mesg) {
512#if 0 /* maybe critical for some cases */
513 rb_exc_check_circular_cause(*cause);
514#else
515 VALUE c = *cause;
516 while (!NIL_P(c)) {
517 if (c == mesg) {
518 rb_raise(rb_eArgError, "circular causes");
519 }
520 if (THROW_DATA_P(c)) {
521 break;
522 }
523 c = rb_attr_get(c, id_cause);
524 }
525#endif
526 }
527 return mesg;
528}
529
530static void
531setup_exception(rb_execution_context_t *ec, enum ruby_tag_type tag, volatile VALUE mesg, VALUE cause)
532{
533 VALUE e;
534 int line;
535 const char *file = rb_source_location_cstr(&line);
536 const char *const volatile file0 = file;
537
538 if ((file && !NIL_P(mesg)) || !UNDEF_P(cause)) {
539 volatile int state = 0;
540
541 EC_PUSH_TAG(ec);
542 if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) {
543 VALUE bt = rb_get_backtrace(mesg);
544 if (!NIL_P(bt) || UNDEF_P(cause)) {
545 if (OBJ_FROZEN(mesg)) {
546 mesg = rb_obj_dup(mesg);
547 }
548 }
549 if (!UNDEF_P(cause) && !THROW_DATA_P(cause)) {
550 exc_setup_cause(mesg, cause);
551 }
552 if (NIL_P(bt)) {
553 VALUE at = rb_ec_backtrace_object(ec);
554 rb_ivar_set(mesg, idBt_locations, at);
555 set_backtrace(mesg, at);
556 }
557 rb_ec_reset_raised(ec);
558 }
559 EC_POP_TAG();
560 file = file0;
561 if (state) goto fatal;
562 }
563
564 if (!NIL_P(mesg)) {
565 ec->errinfo = mesg;
566 }
567
568 if (RTEST(ruby_debug) && !NIL_P(e = ec->errinfo) &&
570 enum ruby_tag_type state;
571
572 mesg = e;
573 EC_PUSH_TAG(ec);
574 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
575 ec->errinfo = Qnil;
576 e = rb_obj_as_string(mesg);
577 ec->errinfo = mesg;
578 if (file && line) {
579 e = rb_sprintf("Exception '%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n",
580 rb_obj_class(mesg), file, line, e);
581 }
582 else if (file) {
583 e = rb_sprintf("Exception '%"PRIsVALUE"' at %s - %"PRIsVALUE"\n",
584 rb_obj_class(mesg), file, e);
585 }
586 else {
587 e = rb_sprintf("Exception '%"PRIsVALUE"' - %"PRIsVALUE"\n",
588 rb_obj_class(mesg), e);
589 }
590 warn_print_str(e);
591 }
592 EC_POP_TAG();
593 if (state == TAG_FATAL && ec->errinfo == exception_error) {
594 ec->errinfo = mesg;
595 }
596 else if (state) {
597 rb_ec_reset_raised(ec);
598 EC_JUMP_TAG(ec, state);
599 }
600 }
601
602 if (rb_ec_set_raised(ec)) {
603 goto fatal;
604 }
605
606 if (tag != TAG_FATAL) {
607 RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo));
608 EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg);
609 }
610 return;
611
612 fatal:
613 ec->errinfo = exception_error;
614 rb_ec_reset_raised(ec);
615 EC_JUMP_TAG(ec, TAG_FATAL);
616}
617
619void
620rb_ec_setup_exception(const rb_execution_context_t *ec, VALUE mesg, VALUE cause)
621{
622 if (UNDEF_P(cause)) {
623 cause = get_ec_errinfo(ec);
624 }
625 if (cause != mesg) {
626 if (THROW_DATA_P(cause)) {
627 cause = Qnil;
628 }
629
630 rb_ivar_set(mesg, id_cause, cause);
631 }
632}
633
634static void
635rb_longjmp(rb_execution_context_t *ec, enum ruby_tag_type tag, volatile VALUE mesg, VALUE cause)
636{
637 mesg = exc_setup_message(ec, mesg, &cause);
638 setup_exception(ec, tag, mesg, cause);
639 rb_ec_raised_clear(ec);
640 EC_JUMP_TAG(ec, tag);
641}
642
643static VALUE make_exception(int argc, const VALUE *argv, int isstr);
644
645NORETURN(static void rb_exc_exception(VALUE mesg, enum ruby_tag_type tag, VALUE cause));
646
647static void
648rb_exc_exception(VALUE mesg, enum ruby_tag_type tag, VALUE cause)
649{
650 if (!NIL_P(mesg)) {
651 mesg = make_exception(1, &mesg, FALSE);
652 }
653 rb_longjmp(GET_EC(), tag, mesg, cause);
654}
655
663void
665{
666 rb_exc_exception(mesg, TAG_RAISE, Qundef);
667}
668
676void
678{
679 rb_exc_exception(mesg, TAG_FATAL, Qnil);
680}
681
682void
683rb_interrupt(void)
684{
686}
687
688static int
689extract_raise_options(int argc, VALUE *argv, VALUE *cause)
690{
691 // Keyword arguments:
692 static ID keywords[1] = {0};
693 if (!keywords[0]) {
694 CONST_ID(keywords[0], "cause");
695 }
696
697 if (argc > 0) {
698 VALUE options;
699 argc = rb_scan_args(argc, argv, "*:", NULL, &options);
700
701 if (!NIL_P(options)) {
702 if (!RHASH_EMPTY_P(options)) {
703 // Extract optional cause keyword argument, leaving any other options alone:
704 rb_get_kwargs(options, keywords, 0, -2, cause);
705
706 // If there were any other options, add them back to the arguments:
707 if (!RHASH_EMPTY_P(options)) argv[argc++] = options;
708 }
709 }
710 }
711
712 return argc;
713}
714
723VALUE
724rb_exception_setup(int argc, VALUE *argv)
725{
726 rb_execution_context_t *ec = GET_EC();
727
728 // Extract cause keyword argument:
729 VALUE cause = Qundef;
730 argc = extract_raise_options(argc, argv, &cause);
731
732 // Validate cause-only case:
733 if (argc == 0 && !UNDEF_P(cause)) {
734 rb_raise(rb_eArgError, "only cause is given with no arguments");
735 }
736
737 // Create exception:
738 VALUE exception;
739 if (argc == 0) {
740 exception = rb_exc_new(rb_eRuntimeError, 0, 0);
741 }
742 else {
743 exception = rb_make_exception(argc, argv);
744 }
745
746 VALUE resolved_cause = Qnil;
747
748 // Resolve cause with validation:
749 if (UNDEF_P(cause)) {
750 // No explicit cause - use automatic cause chaining from calling context:
751 resolved_cause = rb_ec_get_errinfo(ec);
752
753 // Prevent self-referential cause (e.g. `raise $!`):
754 if (resolved_cause == exception) {
755 resolved_cause = Qnil;
756 }
757
758 // A non-local exit in flight keeps its throw data in errinfo, and
759 // throw data is not an exception:
760 if (THROW_DATA_P(resolved_cause)) {
761 resolved_cause = Qnil;
762 }
763 }
764 else if (NIL_P(cause)) {
765 // Explicit nil cause - prevent chaining:
766 resolved_cause = Qnil;
767 }
768 else {
769 // Explicit cause - validate and assign:
770 if (!rb_obj_is_kind_of(cause, rb_eException)) {
771 rb_raise(rb_eTypeError, "exception object expected");
772 }
773
774 if (cause == exception) {
775 // Prevent self-referential cause (e.g. `raise error, cause: error`) - although I'm not sure this is good behaviour, it's inherited from `Kernel#raise`.
776 resolved_cause = Qnil;
777 }
778 else {
779 // Check for circular causes:
780 VALUE current_cause = cause;
781 while (!NIL_P(current_cause)) {
782 // We guarantee that the cause chain is always terminated. Then, creating an exception with an existing cause is not circular as long as exception is not an existing cause of any other exception.
783 if (current_cause == exception) {
784 rb_raise(rb_eArgError, "circular causes");
785 }
786 if (THROW_DATA_P(current_cause)) {
787 break;
788 }
789 current_cause = rb_attr_get(current_cause, id_cause);
790 }
791 resolved_cause = cause;
792 }
793 }
794
795 // Apply cause to exception object (duplicate if frozen):
796 if (!UNDEF_P(resolved_cause)) {
797 if (OBJ_FROZEN(exception)) {
798 exception = rb_obj_dup(exception);
799 }
800 rb_ivar_set(exception, id_cause, resolved_cause);
801 }
802
803 return exception;
804}
805
806VALUE
807rb_f_raise(int argc, VALUE *argv)
808{
809 VALUE cause = Qundef;
810 argc = extract_raise_options(argc, argv, &cause);
811
812 VALUE exception;
813
814 // Bare re-raise case:
815 if (argc == 0) {
816 // Cause was extracted, but no arguments were provided:
817 if (!UNDEF_P(cause)) {
818 rb_raise(rb_eArgError, "only cause is given with no arguments");
819 }
820
821 // Otherwise, re-raise the current exception:
822 exception = get_errinfo();
823 if (!NIL_P(exception)) {
824 argc = 1;
825 argv = &exception;
826 }
827 }
828
829 rb_raise_jump(rb_make_exception(argc, argv), cause);
830
832}
833
834/*
835 * call-seq:
836 * raise(exception, message = exception.to_s, backtrace = nil, cause: $!)
837 * raise(message = nil, cause: $!)
838 *
839 * Raises an exception;
840 * see {Exceptions}[rdoc-ref:exceptions.md].
841 *
842 * Argument +exception+ sets the class of the new exception;
843 * it should be class Exception or one of its subclasses
844 * (most commonly, RuntimeError or StandardError),
845 * or an instance of one of those classes:
846 *
847 * begin
848 * raise(StandardError)
849 * rescue => x
850 * p x.class
851 * end
852 * # => StandardError
853 *
854 * Argument +message+ sets the stored message in the new exception,
855 * which may be retrieved by method Exception#message;
856 * the message must be
857 * a {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects]
858 * or +nil+:
859 *
860 * begin
861 * raise(StandardError, 'Boom')
862 * rescue => x
863 * p x.message
864 * end
865 * # => "Boom"
866 *
867 * If argument +message+ is not given,
868 * the message is the exception class name.
869 *
870 * See {Messages}[rdoc-ref:exceptions.md@Messages].
871 *
872 * Argument +backtrace+ might be used to modify the backtrace of the new exception,
873 * as reported by Exception#backtrace and Exception#backtrace_locations;
874 * the backtrace must be an array of Thread::Backtrace::Location, an array of
875 * strings, a single string, or +nil+.
876 *
877 * Using the array of Thread::Backtrace::Location instances is the most consistent option
878 * and should be preferred when possible. The necessary value might be obtained
879 * from #caller_locations, or copied from Exception#backtrace_locations of another
880 * error:
881 *
882 * begin
883 * do_some_work()
884 * rescue ZeroDivisionError => ex
885 * raise(LogicalError, "You have an error in your math", ex.backtrace_locations)
886 * end
887 *
888 * The ways, both Exception#backtrace and Exception#backtrace_locations of the
889 * raised error are set to the same backtrace.
890 *
891 * When the desired stack of locations is not available and should
892 * be constructed from scratch, an array of strings or a singular
893 * string can be used. In this case, only Exception#backtrace is set:
894 *
895 * begin
896 * raise(StandardError, 'Boom', %w[dsl.rb:3 framework.rb:1])
897 * rescue => ex
898 * p ex.backtrace
899 * # => ["dsl.rb:3", "framework.rb:1"]
900 * p ex.backtrace_locations
901 * # => nil
902 * end
903 *
904 * If argument +backtrace+ is not given,
905 * the backtrace is set according to an array of Thread::Backtrace::Location objects,
906 * as derived from the call stack.
907 *
908 * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
909 *
910 * Keyword argument +cause+ sets the stored cause in the new exception,
911 * which may be retrieved by method Exception#cause;
912 * the cause must be an exception object (Exception or one of its subclasses),
913 * or +nil+:
914 *
915 * begin
916 * raise(StandardError, cause: RuntimeError.new)
917 * rescue => x
918 * p x.cause
919 * end
920 * # => #<RuntimeError: RuntimeError>
921 *
922 * If keyword argument +cause+ is not given,
923 * the cause is the value of <tt>$!</tt>.
924 *
925 * See {Cause}[rdoc-ref:exceptions.md@Cause].
926 *
927 * In the alternate calling sequence,
928 * where argument +exception+ _not_ given,
929 * raises a new exception of the class given by <tt>$!</tt>,
930 * or of class RuntimeError if <tt>$!</tt> is +nil+:
931 *
932 * begin
933 * raise
934 * rescue => x
935 * p x
936 * end
937 * # => RuntimeError
938 *
939 * With argument +exception+ not given,
940 * argument +message+ and keyword argument +cause+ may be given,
941 * but argument +backtrace+ may not be given.
942 *
943 * +cause+ can not be given as an only argument.
944 *
945 */
946
947static VALUE
948f_raise(int c, VALUE *v, VALUE _)
949{
950 return rb_f_raise(c, v);
951}
952
953static VALUE
954make_exception(int argc, const VALUE *argv, int isstr)
955{
956 VALUE mesg, exc;
957
958 mesg = Qnil;
959 switch (argc) {
960 case 0:
961 return Qnil;
962 case 1:
963 exc = argv[0];
964 if (isstr &&! NIL_P(exc)) {
965 mesg = rb_check_string_type(exc);
966 if (!NIL_P(mesg)) {
967 return rb_exc_new3(rb_eRuntimeError, mesg);
968 }
969 }
970
971 case 2:
972 case 3:
973 break;
974 default:
975 rb_error_arity(argc, 0, 3);
976 }
977 if (NIL_P(mesg)) {
978 mesg = rb_check_funcall(argv[0], idException, argc != 1, &argv[1]);
979 }
980 if (UNDEF_P(mesg)) {
981 rb_raise(rb_eTypeError, "exception class/object expected");
982 }
983 if (!rb_obj_is_kind_of(mesg, rb_eException)) {
984 rb_raise(rb_eTypeError, "exception object expected");
985 }
986 if (argc == 3) {
987 set_backtrace(mesg, argv[2]);
988 }
989
990 return mesg;
991}
992
993VALUE
994rb_make_exception(int argc, const VALUE *argv)
995{
996 return make_exception(argc, argv, TRUE);
997}
998
1001static void
1002rb_raise_jump(VALUE mesg, VALUE cause)
1003{
1004 rb_execution_context_t *ec = GET_EC();
1005 const rb_control_frame_t *cfp = ec->cfp;
1006 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1007 VALUE klass = me->owner;
1008 VALUE self = cfp->self;
1009 ID mid = me->called_id;
1010
1011 rb_vm_pop_frame(ec);
1012 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, self, me->def->original_id, mid, klass, Qnil);
1013
1014 rb_longjmp(ec, TAG_RAISE, mesg, cause);
1015}
1016
1017void
1018rb_jump_tag(int tag)
1019{
1020 if (UNLIKELY(tag < TAG_RETURN || tag > TAG_FATAL)) {
1021 unknown_longjmp_status(tag);
1022 }
1023 EC_JUMP_TAG(GET_EC(), tag);
1024}
1025
1026int
1028{
1029 if (rb_vm_frame_block_handler(GET_EC()->cfp) == VM_BLOCK_HANDLER_NONE) {
1030 return FALSE;
1031 }
1032 else {
1033 return TRUE;
1034 }
1035}
1036
1037int rb_vm_cframe_keyword_p(const rb_control_frame_t *cfp);
1038
1039int
1041{
1042 return rb_vm_cframe_keyword_p(GET_EC()->cfp);
1043}
1044
1046
1047void
1049{
1050 if (!rb_block_given_p()) {
1051 rb_vm_localjump_error("no block given", Qnil, 0);
1052 }
1053}
1054
1055VALUE
1056rb_rescue2(VALUE (* b_proc) (VALUE), VALUE data1,
1057 VALUE (* r_proc) (VALUE, VALUE), VALUE data2, ...)
1058{
1059 va_list ap;
1060 va_start(ap, data2);
1061 VALUE ret = rb_vrescue2(b_proc, data1, r_proc, data2, ap);
1062 va_end(ap);
1063 return ret;
1064}
1065
1066VALUE
1067rb_vrescue2(VALUE (* b_proc) (VALUE), VALUE data1,
1068 VALUE (* r_proc) (VALUE, VALUE), VALUE data2,
1069 va_list args)
1070{
1071 enum ruby_tag_type state;
1072 rb_execution_context_t * volatile ec = GET_EC();
1073 rb_control_frame_t *volatile cfp = ec->cfp;
1074 volatile VALUE result = Qfalse;
1075 volatile VALUE e_info = ec->errinfo;
1076
1077 EC_PUSH_TAG(ec);
1078 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1079 retry_entry:
1080 result = (*b_proc) (data1);
1081 }
1082 else if (result) {
1083 /* escape from r_proc */
1084 if (state == TAG_RETRY) {
1085 state = TAG_NONE;
1086 ec->errinfo = Qnil;
1087 result = Qfalse;
1088 goto retry_entry;
1089 }
1090 }
1091 else {
1092 rb_vm_rewind_cfp(ec, cfp);
1093
1094 if (state == TAG_RAISE) {
1095 int handle = FALSE;
1096 VALUE eclass;
1097 va_list ap;
1098
1099 result = Qnil;
1100 /* reuses args when raised again after retrying in r_proc */
1101 va_copy(ap, args);
1102 while ((eclass = va_arg(ap, VALUE)) != 0) {
1103 if (rb_obj_is_kind_of(ec->errinfo, eclass)) {
1104 handle = TRUE;
1105 break;
1106 }
1107 }
1108 va_end(ap);
1109
1110 if (handle) {
1111 state = TAG_NONE;
1112 if (r_proc) {
1113 result = (*r_proc) (data2, ec->errinfo);
1114 }
1115 ec->errinfo = e_info;
1116 }
1117 }
1118 }
1119 EC_POP_TAG();
1120 if (state)
1121 EC_JUMP_TAG(ec, state);
1122
1123 return result;
1124}
1125
1126VALUE
1127rb_rescue(VALUE (* b_proc)(VALUE), VALUE data1,
1128 VALUE (* r_proc)(VALUE, VALUE), VALUE data2)
1129{
1130 return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
1131 (VALUE)0);
1132}
1133
1134VALUE
1135rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate)
1136{
1137 volatile VALUE result = Qnil;
1138 volatile enum ruby_tag_type state;
1139 rb_execution_context_t * volatile ec = GET_EC();
1140 rb_control_frame_t *volatile cfp = ec->cfp;
1141
1142 EC_PUSH_TAG(ec);
1143 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1144 result = (*proc)(data);
1145 }
1146 else {
1147 rb_vm_rewind_cfp(ec, cfp);
1148 }
1149 EC_POP_TAG();
1150
1151 if (pstate != NULL) *pstate = state;
1152 return result;
1153}
1154
1155VALUE
1156rb_ec_ensure(rb_execution_context_t *ec, VALUE (*b_proc)(VALUE), VALUE data1, VALUE (*e_proc)(VALUE), VALUE data2)
1157{
1158 enum ruby_tag_type state;
1159 volatile VALUE result = Qnil;
1160 VALUE errinfo;
1161 EC_PUSH_TAG(ec);
1162 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1163 result = (*b_proc) (data1);
1164 }
1165 EC_POP_TAG();
1166 errinfo = ec->errinfo;
1167 if (!NIL_P(errinfo) && !RB_TYPE_P(errinfo, T_OBJECT)) {
1168 ec->errinfo = Qnil;
1169 }
1170 (*e_proc)(data2);
1171 ec->errinfo = errinfo;
1172 if (state)
1173 EC_JUMP_TAG(ec, state);
1174 return result;
1175}
1176
1177VALUE
1178rb_ensure(VALUE (*b_proc)(VALUE), VALUE data1, VALUE (*e_proc)(VALUE), VALUE data2)
1179{
1180 return rb_ec_ensure(GET_EC(), b_proc, data1, e_proc, data2);
1181}
1182
1183static ID
1184frame_func_id(const rb_control_frame_t *cfp)
1185{
1186 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1187
1188 if (me) {
1189 return me->def->original_id;
1190 }
1191 else {
1192 return 0;
1193 }
1194}
1195
1196static ID
1197frame_called_id(rb_control_frame_t *cfp)
1198{
1199 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1200
1201 if (me) {
1202 return me->called_id;
1203 }
1204 else {
1205 return 0;
1206 }
1207}
1208
1209ID
1210rb_frame_this_func(void)
1211{
1212 return frame_func_id(GET_EC()->cfp);
1213}
1214
1215ID
1216rb_frame_callee(void)
1217{
1218 return frame_called_id(GET_EC()->cfp);
1219}
1220
1221static rb_control_frame_t *
1222previous_frame(const rb_execution_context_t *ec)
1223{
1224 rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
1225 /* check if prev_cfp can be accessible */
1226 if ((void *)(ec->vm_stack + ec->vm_stack_size) == (void *)(prev_cfp)) {
1227 return 0;
1228 }
1229 return prev_cfp;
1230}
1231
1232static ID
1233prev_frame_callee(void)
1234{
1235 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1236 if (!prev_cfp) return 0;
1237 return frame_called_id(prev_cfp);
1238}
1239
1240static ID
1241prev_frame_func(void)
1242{
1243 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1244 if (!prev_cfp) return 0;
1245 return frame_func_id(prev_cfp);
1246}
1247
1254ID
1255rb_frame_last_func(void)
1256{
1257 const rb_execution_context_t *ec = GET_EC();
1258 const rb_control_frame_t *cfp = ec->cfp;
1259 ID mid;
1260
1261 while (!(mid = frame_func_id(cfp)) &&
1262 (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp),
1263 !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)));
1264 return mid;
1265}
1266
1267/*
1268 * call-seq:
1269 * append_features(mod) -> mod
1270 *
1271 * When this module is included in another, Ruby calls
1272 * #append_features in this module, passing it the receiving module
1273 * in _mod_. Ruby's default implementation is to add the constants,
1274 * methods, and module variables of this module to _mod_ if this
1275 * module has not already been added to _mod_ or one of its
1276 * ancestors. See also Module#include.
1277 */
1278
1279static VALUE
1280rb_mod_append_features(VALUE module, VALUE include)
1281{
1282 if (!CLASS_OR_MODULE_P(include)) {
1283 Check_Type(include, T_CLASS);
1284 }
1285 rb_include_module(include, module);
1286
1287 return module;
1288}
1289
1290static VALUE refinement_import_methods(int argc, VALUE *argv, VALUE refinement);
1291
1292/*
1293 * call-seq:
1294 * include(module, ...) -> self
1295 *
1296 * Invokes Module.append_features on each parameter in reverse order.
1297 */
1298
1299static VALUE
1300rb_mod_include(int argc, VALUE *argv, VALUE module)
1301{
1302 int i;
1303 ID id_append_features, id_included;
1304
1305 CONST_ID(id_append_features, "append_features");
1306 CONST_ID(id_included, "included");
1307
1308 if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1309 rb_raise(rb_eTypeError, "Refinement#include has been removed");
1310 }
1311
1312 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1313 for (i = 0; i < argc; i++) {
1314 Check_Type(argv[i], T_MODULE);
1315 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1316 rb_raise(rb_eTypeError, "Cannot include refinement");
1317 }
1318 }
1319 while (argc--) {
1320 rb_funcall(argv[argc], id_append_features, 1, module);
1321 rb_funcall(argv[argc], id_included, 1, module);
1322 }
1323 return module;
1324}
1325
1326/*
1327 * call-seq:
1328 * prepend_features(mod) -> mod
1329 *
1330 * When this module is prepended in another, Ruby calls
1331 * #prepend_features in this module, passing it the receiving module
1332 * in _mod_. Ruby's default implementation is to overlay the
1333 * constants, methods, and module variables of this module to _mod_
1334 * if this module has not already been added to _mod_ or one of its
1335 * ancestors. See also Module#prepend.
1336 */
1337
1338static VALUE
1339rb_mod_prepend_features(VALUE module, VALUE prepend)
1340{
1341 if (!CLASS_OR_MODULE_P(prepend)) {
1342 Check_Type(prepend, T_CLASS);
1343 }
1344 rb_prepend_module(prepend, module);
1345
1346 return module;
1347}
1348
1349/*
1350 * call-seq:
1351 * prepend(module, ...) -> self
1352 *
1353 * Invokes Module.prepend_features on each parameter in reverse order.
1354 */
1355
1356static VALUE
1357rb_mod_prepend(int argc, VALUE *argv, VALUE module)
1358{
1359 int i;
1360 ID id_prepend_features, id_prepended;
1361
1362 if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1363 rb_raise(rb_eTypeError, "Refinement#prepend has been removed");
1364 }
1365
1366 CONST_ID(id_prepend_features, "prepend_features");
1367 CONST_ID(id_prepended, "prepended");
1368
1369 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1370 for (i = 0; i < argc; i++) {
1371 Check_Type(argv[i], T_MODULE);
1372 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1373 rb_raise(rb_eTypeError, "Cannot prepend refinement");
1374 }
1375 }
1376 while (argc--) {
1377 rb_funcall(argv[argc], id_prepend_features, 1, module);
1378 rb_funcall(argv[argc], id_prepended, 1, module);
1379 }
1380 return module;
1381}
1382
1383static void
1384ensure_class_or_module(VALUE obj)
1385{
1386 if (!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE)) {
1387 rb_raise(rb_eTypeError,
1388 "wrong argument type %"PRIsVALUE" (expected Class or Module)",
1389 rb_obj_class(obj));
1390 }
1391}
1392
1393static VALUE
1394hidden_identity_hash_new(void)
1395{
1396 VALUE hash = rb_ident_hash_new();
1397
1398 RBASIC_CLEAR_CLASS(hash); /* hide from ObjectSpace */
1399 return hash;
1400}
1401
1402static VALUE
1403refinement_superclass(VALUE superclass)
1404{
1405 if (RB_TYPE_P(superclass, T_MODULE)) {
1406 /* FIXME: Should ancestors of superclass be used here? */
1407 return rb_include_class_new(RCLASS_ORIGIN(superclass), rb_cBasicObject);
1408 }
1409 else {
1410 return superclass;
1411 }
1412}
1413
1417static void
1418rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module)
1419{
1420 VALUE iclass, c, superclass = klass;
1421
1422 ensure_class_or_module(klass);
1423 Check_Type(module, T_MODULE);
1424 if (NIL_P(CREF_REFINEMENTS(cref))) {
1425 CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new());
1426 }
1427 else {
1428 if (CREF_OMOD_SHARED(cref)) {
1429 CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref)));
1430 CREF_OMOD_SHARED_UNSET(cref);
1431 }
1432 if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) {
1433 superclass = c;
1434 while (c && RB_TYPE_P(c, T_ICLASS)) {
1435 if (RBASIC(c)->klass == module) {
1436 /* already used refinement */
1437 return;
1438 }
1439 c = RCLASS_SUPER(c);
1440 }
1441 }
1442 }
1443 superclass = refinement_superclass(superclass);
1444 c = iclass = rb_include_class_new(module, superclass);
1445 RCLASS_SET_REFINED_CLASS(c, klass);
1446
1447 RCLASS_WRITE_M_TBL(c, RCLASS_M_TBL(module));
1448
1449 rb_class_subclass_add(klass, iclass);
1450
1451 rb_hash_aset(CREF_REFINEMENTS(cref), klass, iclass);
1452}
1453
1454static int
1455using_refinement(VALUE klass, VALUE module, VALUE arg)
1456{
1457 rb_cref_t *cref = (rb_cref_t *) arg;
1458
1459 rb_using_refinement(cref, klass, module);
1460 return ST_CONTINUE;
1461}
1462
1463static void
1464using_module_recursive(const rb_cref_t *cref, VALUE klass)
1465{
1466 ID id_refinements;
1467 VALUE super, module, refinements;
1468
1469 super = RCLASS_SUPER(klass);
1470 if (super) {
1471 using_module_recursive(cref, super);
1472 }
1473 switch (BUILTIN_TYPE(klass)) {
1474 case T_MODULE:
1475 module = klass;
1476 break;
1477
1478 case T_ICLASS:
1479 module = RBASIC(klass)->klass;
1480 break;
1481
1482 default:
1483 rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)",
1484 rb_obj_classname(klass));
1485 break;
1486 }
1487 CONST_ID(id_refinements, "__refinements__");
1488 refinements = rb_attr_get(module, id_refinements);
1489 if (NIL_P(refinements)) return;
1490 rb_hash_foreach(refinements, using_refinement, (VALUE) cref);
1491}
1492
1496static void
1497rb_using_module(const rb_cref_t *cref, VALUE module)
1498{
1499 Check_Type(module, T_MODULE);
1500 using_module_recursive(cref, module);
1501 rb_clear_all_refinement_method_cache();
1502}
1503
1504void
1505rb_vm_using_module(VALUE module)
1506{
1507 rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1508}
1509
1510/*
1511 * call-seq:
1512 * target -> class_or_module
1513 *
1514 * Return the class or module refined by the receiver.
1515 *
1516 * module M
1517 * refine String do
1518 * end
1519 * end
1520 *
1521 * M.refinements[0].target # => String
1522 */
1523VALUE
1524rb_refinement_module_get_refined_class(VALUE module)
1525{
1526 ID id_refined_class;
1527
1528 CONST_ID(id_refined_class, "__refined_class__");
1529 return rb_attr_get(module, id_refined_class);
1530}
1531
1532static void
1533add_activated_refinement(VALUE activated_refinements,
1534 VALUE klass, VALUE refinement)
1535{
1536 VALUE iclass, c, superclass = klass;
1537
1538 if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) {
1539 superclass = c;
1540 while (c && RB_TYPE_P(c, T_ICLASS)) {
1541 if (RBASIC(c)->klass == refinement) {
1542 /* already used refinement */
1543 return;
1544 }
1545 c = RCLASS_SUPER(c);
1546 }
1547 }
1548 superclass = refinement_superclass(superclass);
1549 c = iclass = rb_include_class_new(refinement, superclass);
1550 RCLASS_SET_REFINED_CLASS(c, klass);
1551 rb_class_subclass_add(klass, iclass);
1552 refinement = RCLASS_SUPER(refinement);
1553 while (refinement && refinement != klass) {
1554 c = rb_class_set_super(c, rb_include_class_new(refinement, RCLASS_SUPER(c)));
1555 RCLASS_SET_REFINED_CLASS(c, klass);
1556 rb_class_subclass_add(klass, c);
1557 refinement = RCLASS_SUPER(refinement);
1558 }
1559 rb_hash_aset(activated_refinements, klass, iclass);
1560}
1561
1562void
1563rb_refinement_setup(struct rb_refinements_data *data, VALUE module, VALUE klass)
1564{
1565 VALUE refinement;
1566 ID id_refinements, id_activated_refinements,
1567 id_refined_class, id_defined_at;
1568 VALUE refinements, activated_refinements;
1569
1570 CONST_ID(id_refinements, "__refinements__");
1571 refinements = rb_attr_get(module, id_refinements);
1572 if (NIL_P(refinements)) {
1573 refinements = hidden_identity_hash_new();
1574 rb_ivar_set(module, id_refinements, refinements);
1575 }
1576 CONST_ID(id_activated_refinements, "__activated_refinements__");
1577 activated_refinements = rb_attr_get(module, id_activated_refinements);
1578 if (NIL_P(activated_refinements)) {
1579 activated_refinements = hidden_identity_hash_new();
1580 rb_ivar_set(module, id_activated_refinements,
1581 activated_refinements);
1582 }
1583 refinement = rb_hash_lookup(refinements, klass);
1584 if (NIL_P(refinement)) {
1585 VALUE superclass = refinement_superclass(klass);
1586 refinement = rb_refinement_new();
1587 rb_class_set_super(refinement, superclass);
1588 RUBY_ASSERT(BUILTIN_TYPE(refinement) == T_MODULE);
1589 FL_SET(refinement, RMODULE_IS_REFINEMENT);
1590 CONST_ID(id_refined_class, "__refined_class__");
1591 rb_ivar_set(refinement, id_refined_class, klass);
1592 CONST_ID(id_defined_at, "__defined_at__");
1593 rb_ivar_set(refinement, id_defined_at, module);
1594 rb_hash_aset(refinements, klass, refinement);
1595 add_activated_refinement(activated_refinements, klass, refinement);
1596 }
1597
1598 data->refinement = refinement;
1599 data->refinements = activated_refinements;
1600}
1601
1602/*
1603 * call-seq:
1604 * refine(mod) { block } -> module
1605 *
1606 * Refine <i>mod</i> in the receiver.
1607 *
1608 * Returns a module, where refined methods are defined.
1609 */
1610
1611static VALUE
1612rb_mod_refine(VALUE module, VALUE klass)
1613{
1614 /* module is the receiver of #refine, klass is a module to be refined (`mod` in the doc) */
1615 rb_thread_t *th = GET_THREAD();
1616 VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
1617 struct rb_refinements_data data;
1618
1619 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1620 rb_raise(rb_eArgError, "no block given");
1621 }
1622 if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
1623 rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
1624 }
1625
1626 ensure_class_or_module(klass);
1627
1628 rb_refinement_setup(&data, module, klass);
1629
1630 rb_yield_refine_block(data.refinement, data.refinements);
1631 return data.refinement;
1632}
1633
1634static void
1635ignored_block(VALUE module, const char *klass)
1636{
1637 const char *anon = "";
1638 Check_Type(module, T_MODULE);
1639 if (!RTEST(rb_search_class_path(module))) {
1640 anon = ", maybe for Module.new";
1641 }
1642 rb_warn("%s""using doesn't call the given block""%s.", klass, anon);
1643}
1644
1645/*
1646 * call-seq:
1647 * using(module) -> self
1648 *
1649 * Import class refinements from <i>module</i> into the current class or
1650 * module definition.
1651 */
1652
1653static VALUE
1654mod_using(VALUE self, VALUE module)
1655{
1656 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1657
1658 if (prev_frame_func()) {
1659 rb_raise(rb_eRuntimeError,
1660 "Module#using is not permitted in methods");
1661 }
1662 if (prev_cfp && prev_cfp->self != self) {
1663 rb_raise(rb_eRuntimeError, "Module#using is not called on self");
1664 }
1665 if (rb_block_given_p()) {
1666 ignored_block(module, "Module#");
1667 }
1668 rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1669 return self;
1670}
1671
1672
1673/*
1674 * call-seq:
1675 * refinements -> array
1676 *
1677 * Returns an array of +Refinement+ defined within the receiver.
1678 *
1679 * module A
1680 * refine Integer do
1681 * end
1682 *
1683 * refine String do
1684 * end
1685 * end
1686 *
1687 * p A.refinements
1688 *
1689 * <em>produces:</em>
1690 *
1691 * [#<refinement:Integer@A>, #<refinement:String@A>]
1692 */
1693static VALUE
1694mod_refinements(VALUE self)
1695{
1696 ID id_refinements;
1697 VALUE refinements;
1698
1699 CONST_ID(id_refinements, "__refinements__");
1700 refinements = rb_attr_get(self, id_refinements);
1701 if (NIL_P(refinements)) {
1702 return rb_ary_new();
1703 }
1704 return rb_hash_values(refinements);
1705}
1706
1707static int
1708used_modules_i(VALUE _, VALUE mod, VALUE ary)
1709{
1710 ID id_defined_at;
1711 CONST_ID(id_defined_at, "__defined_at__");
1712 while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1713 rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at));
1714 mod = RCLASS_SUPER(mod);
1715 }
1716 return ST_CONTINUE;
1717}
1718
1719/*
1720 * call-seq:
1721 * used_modules -> array
1722 *
1723 * Returns an array of all modules used in the current scope. The ordering
1724 * of modules in the resulting array is not defined.
1725 *
1726 * module A
1727 * refine Object do
1728 * end
1729 * end
1730 *
1731 * module B
1732 * refine Object do
1733 * end
1734 * end
1735 *
1736 * using A
1737 * using B
1738 * p Module.used_modules
1739 *
1740 * <em>produces:</em>
1741 *
1742 * [B, A]
1743 */
1744static VALUE
1745rb_mod_s_used_modules(VALUE _)
1746{
1747 const rb_cref_t *cref = rb_vm_cref();
1748 VALUE ary = rb_ary_new();
1749
1750 while (cref) {
1751 if (!NIL_P(CREF_REFINEMENTS(cref))) {
1752 rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
1753 }
1754 cref = CREF_NEXT(cref);
1755 }
1756
1757 return rb_funcall(ary, rb_intern("uniq"), 0);
1758}
1759
1760static int
1761used_refinements_i(VALUE _, VALUE mod, VALUE ary)
1762{
1763 while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1764 rb_ary_push(ary, rb_class_of(mod));
1765 mod = RCLASS_SUPER(mod);
1766 }
1767 return ST_CONTINUE;
1768}
1769
1770/*
1771 * call-seq:
1772 * used_refinements -> array
1773 *
1774 * Returns an array of all modules used in the current scope. The ordering
1775 * of modules in the resulting array is not defined.
1776 *
1777 * module A
1778 * refine Object do
1779 * end
1780 * end
1781 *
1782 * module B
1783 * refine Object do
1784 * end
1785 * end
1786 *
1787 * using A
1788 * using B
1789 * p Module.used_refinements
1790 *
1791 * <em>produces:</em>
1792 *
1793 * [#<refinement:Object@B>, #<refinement:Object@A>]
1794 */
1795static VALUE
1796rb_mod_s_used_refinements(VALUE _)
1797{
1798 const rb_cref_t *cref = rb_vm_cref();
1799 VALUE ary = rb_ary_new();
1800
1801 while (cref) {
1802 if (!NIL_P(CREF_REFINEMENTS(cref))) {
1803 rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary);
1804 }
1805 cref = CREF_NEXT(cref);
1806 }
1807
1808 return ary;
1809}
1810
1812 rb_cref_t *cref;
1813 VALUE refinement;
1814 VALUE module;
1815};
1816
1817/* vm.c */
1818rb_cref_t *rb_vm_cref_dup_without_refinements(const rb_cref_t *cref);
1819
1820static enum rb_id_table_iterator_result
1821refinement_import_methods_i(ID key, VALUE value, void *data)
1822{
1823 const rb_method_entry_t *me = (const rb_method_entry_t *)value;
1825
1826 if (me->def->type != VM_METHOD_TYPE_ISEQ) {
1827 rb_raise(rb_eArgError, "Can't import method which is not defined with Ruby code: %"PRIsVALUE"#%"PRIsVALUE, rb_class_path(arg->module), rb_id2str(key));
1828 }
1829 rb_cref_t *new_cref = rb_vm_cref_dup_without_refinements(me->def->body.iseq.cref);
1830 CREF_REFINEMENTS_SET(new_cref, CREF_REFINEMENTS(arg->cref));
1831 rb_add_method_iseq(arg->refinement, key, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me));
1832 return ID_TABLE_CONTINUE;
1833}
1834
1835/*
1836 * Note: docs for the method are in class.c
1837 */
1838
1839static VALUE
1840refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
1841{
1842 int i;
1844
1845 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1846 for (i = 0; i < argc; i++) {
1847 Check_Type(argv[i], T_MODULE);
1848 if (RCLASS_SUPER(argv[i])) {
1849 rb_warn("%"PRIsVALUE" has ancestors, but Refinement#import_methods doesn't import their methods", rb_class_path(argv[i]));
1850 }
1851 }
1852 arg.cref = rb_vm_cref_replace_with_duplicated_cref();
1853 arg.refinement = refinement;
1854 for (i = 0; i < argc; i++) {
1855 arg.module = argv[i];
1856 struct rb_id_table *m_tbl = RCLASS_M_TBL(argv[i]);
1857 if (!m_tbl) continue;
1858 rb_id_table_foreach(m_tbl, refinement_import_methods_i, &arg);
1859 }
1860 return refinement;
1861}
1862
1863void
1864rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
1865{
1866 rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
1867}
1868
1869void
1870rb_obj_call_init_kw(VALUE obj, int argc, const VALUE *argv, int kw_splat)
1871{
1872 PASS_PASSED_BLOCK_HANDLER();
1873 rb_funcallv_kw(obj, idInitialize, argc, argv, kw_splat);
1874}
1875
1876void
1878{
1880}
1881
1882/*
1883 * call-seq:
1884 * extend_object(obj) -> obj
1885 *
1886 * Extends the specified object by adding this module's constants and
1887 * methods (which are added as singleton methods). This is the callback
1888 * method used by Object#extend.
1889 *
1890 * module Picky
1891 * def Picky.extend_object(o)
1892 * if String === o
1893 * puts "Can't add Picky to a String"
1894 * else
1895 * puts "Picky added to #{o.class}"
1896 * super
1897 * end
1898 * end
1899 * end
1900 * (s = Array.new).extend Picky # Call Object.extend
1901 * (s = "quick brown fox").extend Picky
1902 *
1903 * <em>produces:</em>
1904 *
1905 * Picky added to Array
1906 * Can't add Picky to a String
1907 */
1908
1909static VALUE
1910rb_mod_extend_object(VALUE mod, VALUE obj)
1911{
1912 rb_extend_object(obj, mod);
1913 return obj;
1914}
1915
1916/*
1917 * call-seq:
1918 * obj.extend(module, ...) -> obj
1919 *
1920 * Adds to _obj_ the instance methods from each module given as a
1921 * parameter.
1922 *
1923 * module Mod
1924 * def hello
1925 * "Hello from Mod.\n"
1926 * end
1927 * end
1928 *
1929 * class Klass
1930 * def hello
1931 * "Hello from Klass.\n"
1932 * end
1933 * end
1934 *
1935 * k = Klass.new
1936 * k.hello #=> "Hello from Klass.\n"
1937 * k.extend(Mod) #=> #<Klass:0x401b3bc8>
1938 * k.hello #=> "Hello from Mod.\n"
1939 */
1940
1941static VALUE
1942rb_obj_extend(int argc, VALUE *argv, VALUE obj)
1943{
1944 int i;
1945 ID id_extend_object, id_extended;
1946
1947 CONST_ID(id_extend_object, "extend_object");
1948 CONST_ID(id_extended, "extended");
1949
1950 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1951 for (i = 0; i < argc; i++) {
1952 Check_Type(argv[i], T_MODULE);
1953 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1954 rb_raise(rb_eTypeError, "Cannot extend object with refinement");
1955 }
1956 }
1957 while (argc--) {
1958 rb_funcall(argv[argc], id_extend_object, 1, obj);
1959 rb_funcall(argv[argc], id_extended, 1, obj);
1960 }
1961 return obj;
1962}
1963
1964VALUE
1965rb_top_main_class(const char *method)
1966{
1967 VALUE klass = GET_THREAD()->top_wrapper;
1968
1969 if (!klass) return rb_cObject;
1970 rb_warning("main.%s in the wrapped load is effective only in wrapper module", method);
1971 return klass;
1972}
1973
1974/*
1975 * call-seq:
1976 * include(module, ...) -> self
1977 *
1978 * Invokes Module.append_features on each parameter in turn.
1979 * Effectively adds the methods and constants in each module to the
1980 * receiver.
1981 */
1982
1983static VALUE
1984top_include(int argc, VALUE *argv, VALUE self)
1985{
1986 return rb_mod_include(argc, argv, rb_top_main_class("include"));
1987}
1988
1989/*
1990 * call-seq:
1991 * using(module) -> self
1992 *
1993 * Import class refinements from <i>module</i> into the scope where
1994 * #using is called.
1995 */
1996
1997static VALUE
1998top_using(VALUE self, VALUE module)
1999{
2000 const rb_cref_t *cref = CREF_NEXT(rb_vm_cref());
2001 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
2002 rb_thread_t *th = GET_THREAD();
2003
2004 if ((th->top_wrapper ? CREF_NEXT(cref) : cref) ||
2005 (prev_cfp && rb_vm_frame_method_entry(prev_cfp))) {
2006 rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel");
2007 }
2008 if (rb_block_given_p()) {
2009 ignored_block(module, "main.");
2010 }
2011 rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
2012 return self;
2013}
2014
2015static const VALUE *
2016errinfo_place(const rb_execution_context_t *ec)
2017{
2018 const rb_control_frame_t *cfp = ec->cfp;
2019 const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
2020
2021 while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) {
2022 if (VM_FRAME_RUBYFRAME_P(cfp)) {
2023 if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_RESCUE) {
2024 return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
2025 }
2026 else if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_ENSURE &&
2027 !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) &&
2028 !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) {
2029 return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
2030 }
2031 }
2032 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
2033 }
2034 return 0;
2035}
2036
2037VALUE
2038rb_ec_get_errinfo(const rb_execution_context_t *ec)
2039{
2040 const VALUE *ptr = errinfo_place(ec);
2041 if (ptr) {
2042 return *ptr;
2043 }
2044 else {
2045 return ec->errinfo;
2046 }
2047}
2048
2049static VALUE
2050get_errinfo(void)
2051{
2052 return get_ec_errinfo(GET_EC());
2053}
2054
2055static VALUE
2056errinfo_getter(ID id, VALUE *_)
2057{
2058 return get_errinfo();
2059}
2060
2061VALUE
2062rb_errinfo(void)
2063{
2064 return GET_EC()->errinfo;
2065}
2066
2067void
2068rb_set_errinfo(VALUE err)
2069{
2070 if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) {
2071 rb_raise(rb_eTypeError, "assigning non-exception to $!");
2072 }
2073 GET_EC()->errinfo = err;
2074}
2075
2076static VALUE
2077errat_getter(ID id, VALUE *_)
2078{
2079 VALUE err = get_errinfo();
2080 if (!NIL_P(err)) {
2081 return rb_get_backtrace(err);
2082 }
2083 else {
2084 return Qnil;
2085 }
2086}
2087
2088static void
2089errat_setter(VALUE val, ID id, VALUE *var)
2090{
2091 VALUE err = get_errinfo();
2092 if (NIL_P(err)) {
2093 rb_raise(rb_eArgError, "$! not set");
2094 }
2095 set_backtrace(err, val);
2096}
2097
2098/*
2099 * call-seq:
2100 * __method__ -> symbol
2101 *
2102 * Returns the name at the definition of the current method as a
2103 * Symbol.
2104 * If called outside of a method, it returns <code>nil</code>.
2105 *
2106 */
2107
2108static VALUE
2109rb_f_method_name(VALUE _)
2110{
2111 ID fname = prev_frame_func(); /* need *method* ID */
2112
2113 if (fname) {
2114 return ID2SYM(fname);
2115 }
2116 else {
2117 return Qnil;
2118 }
2119}
2120
2121/*
2122 * call-seq:
2123 * __callee__ -> symbol
2124 *
2125 * Returns the called name of the current method as a Symbol.
2126 * If called outside of a method, it returns <code>nil</code>.
2127 *
2128 */
2129
2130static VALUE
2131rb_f_callee_name(VALUE _)
2132{
2133 ID fname = prev_frame_callee(); /* need *callee* ID */
2134
2135 if (fname) {
2136 return ID2SYM(fname);
2137 }
2138 else {
2139 return Qnil;
2140 }
2141}
2142
2143/*
2144 * call-seq:
2145 * __dir__ -> string
2146 *
2147 * Returns the canonicalized absolute path of the directory of the file from
2148 * which this method is called. It means symlinks in the path is resolved.
2149 * If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>.
2150 * The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>.
2151 *
2152 */
2153static VALUE
2154f_current_dirname(VALUE _)
2155{
2156 VALUE base = rb_current_realfilepath();
2157 if (NIL_P(base)) {
2158 return Qnil;
2159 }
2160 base = rb_file_dirname(base);
2161 return base;
2162}
2163
2164/*
2165 * call-seq:
2166 * global_variables -> array
2167 *
2168 * Returns an array of the names of global variables. This includes
2169 * special regexp global variables such as <tt>$~</tt> and <tt>$+</tt>,
2170 * but does not include the numbered regexp global variables (<tt>$1</tt>,
2171 * <tt>$2</tt>, etc.).
2172 *
2173 * global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
2174 */
2175
2176static VALUE
2177f_global_variables(VALUE _)
2178{
2179 return rb_f_global_variables();
2180}
2181
2182/*
2183 * call-seq:
2184 * trace_var(symbol, cmd ) -> nil
2185 * trace_var(symbol) {|val| block } -> nil
2186 *
2187 * Controls tracing of assignments to global variables. The parameter
2188 * +symbol+ identifies the variable (as either a string name or a
2189 * symbol identifier). _cmd_ (which may be a string or a
2190 * +Proc+ object) or block is executed whenever the variable
2191 * is assigned. The block or +Proc+ object receives the
2192 * variable's new value as a parameter. Also see
2193 * #untrace_var.
2194 *
2195 * trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
2196 * $_ = "hello"
2197 * $_ = ' there'
2198 *
2199 * <em>produces:</em>
2200 *
2201 * $_ is now 'hello'
2202 * $_ is now ' there'
2203 */
2204
2205static VALUE
2206f_trace_var(int c, const VALUE *a, VALUE _)
2207{
2208 return rb_f_trace_var(c, a);
2209}
2210
2211/*
2212 * call-seq:
2213 * untrace_var(symbol [, cmd] ) -> array or nil
2214 *
2215 * Removes tracing for the specified command on the given global
2216 * variable and returns +nil+. If no command is specified,
2217 * removes all tracing for that variable and returns an array
2218 * containing the commands actually removed.
2219 */
2220
2221static VALUE
2222f_untrace_var(int c, const VALUE *a, VALUE _)
2223{
2224 return rb_f_untrace_var(c, a);
2225}
2226
2227void
2228Init_eval(void)
2229{
2230 rb_define_virtual_variable("$@", errat_getter, errat_setter);
2231 rb_define_virtual_variable("$!", errinfo_getter, 0);
2232
2233 rb_gvar_ractor_local("$@");
2234 rb_gvar_ractor_local("$!");
2235
2236 rb_gvar_box_dynamic("$@");
2237 rb_gvar_box_dynamic("$!");
2238
2239 rb_define_global_function("raise", f_raise, -1);
2240 rb_define_global_function("fail", f_raise, -1);
2241
2242 rb_define_global_function("global_variables", f_global_variables, 0);
2243
2244 rb_define_global_function("__method__", rb_f_method_name, 0);
2245 rb_define_global_function("__callee__", rb_f_callee_name, 0);
2246 rb_define_global_function("__dir__", f_current_dirname, 0);
2247
2248 rb_define_method(rb_cModule, "include", rb_mod_include, -1);
2249 rb_define_method(rb_cModule, "prepend", rb_mod_prepend, -1);
2250
2251 rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
2252 rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
2253 rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1);
2254 rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1);
2255 rb_define_private_method(rb_cModule, "using", mod_using, 1);
2256 rb_define_method(rb_cModule, "refinements", mod_refinements, 0);
2257 rb_define_singleton_method(rb_cModule, "used_modules",
2258 rb_mod_s_used_modules, 0);
2259 rb_define_singleton_method(rb_cModule, "used_refinements",
2260 rb_mod_s_used_refinements, 0);
2261 rb_undef_method(rb_cClass, "refine");
2262 rb_define_private_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
2263 rb_define_method(rb_cRefinement, "target", rb_refinement_module_get_refined_class, 0);
2264 rb_undef_method(rb_cRefinement, "append_features");
2265 rb_undef_method(rb_cRefinement, "prepend_features");
2266 rb_undef_method(rb_cRefinement, "extend_object");
2267
2268 rb_undef_method(rb_cClass, "module_function");
2269
2270 Init_vm_eval();
2271 Init_eval_method();
2272
2273 rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
2274 rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1);
2275
2277 "include", top_include, -1);
2279 "using", top_using, 1);
2280
2281 rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
2282
2283 rb_define_global_function("trace_var", f_trace_var, -1);
2284 rb_define_global_function("untrace_var", f_untrace_var, -1);
2285
2286 rb_vm_register_special_exception(ruby_error_reenter, rb_eFatal, "exception reentered");
2287 rb_vm_register_special_exception(ruby_error_stackfatal, rb_eFatal, "machine stack overflow in critical region");
2288
2289 id_signo = rb_intern_const("signo");
2290 id_status = rb_intern_const("status");
2291}
2292
2293int
2294rb_errno(void)
2295{
2296 return *rb_orig_errno_ptr();
2297}
2298
2299void
2300rb_errno_set(int e)
2301{
2302 *rb_orig_errno_ptr() = e;
2303}
2304
2305int *
2306rb_errno_ptr(void)
2307{
2308 return rb_orig_errno_ptr();
2309}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EVENT_RAISE
Encountered a raise statement.
Definition event.h:45
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition event.h:44
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1695
VALUE rb_refinement_new(void)
Creates a new, anonymous refinement.
Definition class.c:1588
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1877
void rb_prepend_module(VALUE klass, VALUE module)
Identical to rb_include_module(), except it "prepends" the passed module to the klass,...
Definition class.c:1949
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2825
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:432
void rb_need_block(void)
Declares that the current method needs a block.
Definition eval.c:1048
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2680
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3158
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1040
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1027
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2947
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:136
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:130
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:301
int ruby_exec_node(void *n)
Identical to ruby_run_node(), except it returns an opaque execution status.
Definition eval.c:336
int ruby_setup(void)
Initializes the VM and builtin libraries.
Definition eval.c:65
void ruby_finalize(void)
Runs the VM finalization processes.
Definition eval.c:181
int ruby_cleanup(int ex)
Destructs the VM.
Definition eval.c:189
void * ruby_process_options(int argc, char **argv)
Identical to ruby_options(), except it raises ruby-level exceptions on failure.
Definition ruby.c:3228
void ruby_prog_init(void)
Defines built-in variables.
Definition ruby.c:3181
void ruby_sig_finalize(void)
Clear signal handlers.
Definition signal.c:1471
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:486
VALUE rb_eLocalJumpError
LocalJumpError exception.
Definition eval.c:48
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition eval.c:1056
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
VALUE rb_eSystemExit
SystemExit exception.
Definition error.c:1424
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_vrescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2, va_list args)
Identical to rb_rescue2(), except it takes va_list instead of variadic number of arguments.
Definition eval.c:1067
VALUE rb_eFatal
fatal exception.
Definition error.c:1427
VALUE rb_eInterrupt
Interrupt exception.
Definition error.c:1425
void rb_exc_fatal(VALUE mesg)
Raises a fatal error in the current thread.
Definition eval.c:677
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
Definition error.c:1469
void rb_error_frozen_object(VALUE frozen_obj)
Identical to rb_error_frozen(), except it takes arbitrary Ruby object instead of C's string.
Definition error.c:4163
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1423
VALUE rb_rescue(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2)
Identical to rb_rescue2(), except it does not take a list of exception classes.
Definition eval.c:1127
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1178
VALUE rb_eSysStackError
SystemStackError exception.
Definition eval.c:49
VALUE rb_eThreadError
ThreadError exception.
Definition eval.c:1045
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:497
VALUE rb_cClass
Class class.
Definition object.c:63
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_cRefinement
Refinement class.
Definition object.c:64
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:59
VALUE rb_cModule
Module class.
Definition object.c:62
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:923
void ruby_init(void)
Calls ruby_setup() and check error.
Definition eval.c:98
int ruby_executable_node(void *n, int *status)
Checks the return value of ruby_options().
Definition eval.c:307
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_funcallv(), except you can specify how to handle the last element of the given array.
Definition vm_eval.c:1086
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
void ruby_default_signal(int sig)
Pretends as if there was no custom signal handler.
Definition signal.c:411
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_exc_new_cstr(exc, str)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1671
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2981
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1868
VALUE rb_f_untrace_var(int argc, const VALUE *argv)
Deletes the passed tracer from the passed global variable, or if omitted, deletes everything.
Definition variable.c:924
VALUE rb_const_list(void *)
This is another mysterious API that comes with no documents at all.
Definition variable.c:3749
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
VALUE rb_f_trace_var(int argc, const VALUE *argv)
Traces a global variable.
Definition variable.c:878
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3781
void * rb_mod_const_of(VALUE, void *)
This is a variant of rb_mod_const_at().
Definition variable.c:3727
void * rb_mod_const_at(VALUE, void *)
This API is mysterious.
Definition variable.c:3712
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2109
VALUE rb_f_global_variables(void)
Queries the list of global variables.
Definition variable.c:1133
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:688
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
int ruby_vm_destruct(ruby_vm_t *vm)
Destructs the passed VM.
Definition vm.c:3393
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
Scheduler APIs.
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
Definition scheduler.c:433
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40