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