* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / eval.c
blobd91440676fbd0bccc6af6be719c6a3e97bbb52ac
1 /**********************************************************************
3 eval.c -
5 $Author$
6 created at: Thu Jun 10 14:22:17 JST 1993
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
12 **********************************************************************/
14 #include "ruby/internal/config.h"
16 #ifdef HAVE_SYS_PRCTL_H
17 #include <sys/prctl.h>
18 #endif
20 #include "eval_intern.h"
21 #include "gc.h"
22 #include "internal.h"
23 #include "internal/class.h"
24 #include "internal/error.h"
25 #include "internal/eval.h"
26 #include "internal/hash.h"
27 #include "internal/inits.h"
28 #include "internal/io.h"
29 #include "internal/object.h"
30 #include "internal/thread.h"
31 #include "internal/variable.h"
32 #include "ruby/fiber/scheduler.h"
33 #include "iseq.h"
34 #include "mjit.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"
41 NORETURN(static void rb_raise_jump(VALUE, VALUE));
42 void rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec);
43 void rb_ec_clear_all_trace_func(const rb_execution_context_t *ec);
45 static int rb_ec_cleanup(rb_execution_context_t *ec, int ex);
46 static int rb_ec_exec_node(rb_execution_context_t *ec, void *n);
48 VALUE rb_eLocalJumpError;
49 VALUE rb_eSysStackError;
51 ID ruby_static_id_signo, ruby_static_id_status;
52 extern ID ruby_static_id_cause;
53 #define id_cause ruby_static_id_cause
55 #define exception_error GET_VM()->special_exceptions[ruby_error_reenter]
57 #include "eval_error.c"
58 #include "eval_jump.c"
60 #define CLASS_OR_MODULE_P(obj) \
61 (!SPECIAL_CONST_P(obj) && \
62 (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
64 int
65 ruby_setup(void)
67 enum ruby_tag_type state;
69 if (GET_VM())
70 return 0;
72 ruby_init_stack((void *)&state);
75 * Disable THP early before mallocs happen because we want this to
76 * affect as many future pages as possible for CoW-friendliness
78 #if defined(__linux__) && defined(PR_SET_THP_DISABLE)
79 prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);
80 #endif
81 Init_BareVM();
82 Init_heap();
83 rb_vm_encoded_insn_data_table_init();
84 Init_vm_objects();
86 EC_PUSH_TAG(GET_EC());
87 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
88 rb_call_inits();
89 ruby_prog_init();
90 GET_VM()->running = 1;
92 EC_POP_TAG();
94 return state;
97 void
98 ruby_init(void)
100 int state = ruby_setup();
101 if (state) {
102 if (RTEST(ruby_debug))
103 error_print(GET_EC());
104 exit(EXIT_FAILURE);
108 void *
109 ruby_options(int argc, char **argv)
111 rb_execution_context_t *ec = GET_EC();
112 enum ruby_tag_type state;
113 void *volatile iseq = 0;
115 ruby_init_stack((void *)&iseq);
116 EC_PUSH_TAG(ec);
117 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
118 SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv));
120 else {
121 rb_ec_clear_current_thread_trace_func(ec);
122 state = error_handle(ec, state);
123 iseq = (void *)INT2FIX(state);
125 EC_POP_TAG();
126 return iseq;
129 static void
130 rb_ec_fiber_scheduler_finalize(rb_execution_context_t *ec)
132 enum ruby_tag_type state;
134 EC_PUSH_TAG(ec);
135 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
136 rb_fiber_scheduler_set(Qnil);
138 else {
139 state = error_handle(ec, state);
141 EC_POP_TAG();
144 static void
145 rb_ec_teardown(rb_execution_context_t *ec)
147 // If the user code defined a scheduler for the top level thread, run it:
148 rb_ec_fiber_scheduler_finalize(ec);
150 EC_PUSH_TAG(ec);
151 if (EC_EXEC_TAG() == TAG_NONE) {
152 rb_vm_trap_exit(rb_ec_vm_ptr(ec));
154 EC_POP_TAG();
155 rb_ec_exec_end_proc(ec);
156 rb_ec_clear_all_trace_func(ec);
159 static void
160 rb_ec_finalize(rb_execution_context_t *ec)
162 ruby_sig_finalize();
163 ec->errinfo = Qnil;
164 rb_objspace_call_finalizer(rb_ec_vm_ptr(ec)->objspace);
167 void
168 ruby_finalize(void)
170 rb_execution_context_t *ec = GET_EC();
171 rb_ec_teardown(ec);
172 rb_ec_finalize(ec);
176 ruby_cleanup(int ex)
178 return rb_ec_cleanup(GET_EC(), ex);
181 static int
182 rb_ec_cleanup(rb_execution_context_t *ec, int ex0)
184 int state;
185 volatile VALUE errs[2] = { Qundef, Qundef };
186 int nerr;
187 rb_thread_t *th = rb_ec_thread_ptr(ec);
188 rb_thread_t *const volatile th0 = th;
189 volatile int sysex = EXIT_SUCCESS;
190 volatile int step = 0;
191 volatile int ex = ex0;
193 rb_threadptr_interrupt(th);
194 rb_threadptr_check_signal(th);
196 EC_PUSH_TAG(ec);
197 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
198 SAVE_ROOT_JMPBUF(th, { RUBY_VM_CHECK_INTS(ec); });
200 step_0: step++;
201 errs[1] = ec->errinfo;
202 if (THROW_DATA_P(ec->errinfo)) ec->errinfo = Qnil;
203 ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]);
205 SAVE_ROOT_JMPBUF(th, rb_ec_teardown(ec));
207 step_1: step++;
208 /* protect from Thread#raise */
209 th->status = THREAD_KILLED;
211 errs[0] = ec->errinfo;
212 SAVE_ROOT_JMPBUF(th, rb_ractor_terminate_all());
214 else {
215 th = th0;
216 switch (step) {
217 case 0: goto step_0;
218 case 1: goto step_1;
220 if (ex == 0) ex = state;
222 ec->errinfo = errs[1];
223 sysex = error_handle(ec, ex);
225 state = 0;
226 for (nerr = 0; nerr < numberof(errs); ++nerr) {
227 VALUE err = ATOMIC_VALUE_EXCHANGE(errs[nerr], Qnil);
228 VALUE sig;
230 if (!RTEST(err)) continue;
232 /* ec->errinfo contains a NODE while break'ing */
233 if (THROW_DATA_P(err)) continue;
235 if (rb_obj_is_kind_of(err, rb_eSystemExit)) {
236 sysex = sysexit_status(err);
237 break;
239 else if (rb_obj_is_kind_of(err, rb_eSignal)) {
240 VALUE sig = rb_ivar_get(err, id_signo);
241 state = NUM2INT(sig);
242 break;
244 else if (rb_obj_is_kind_of(err, rb_eSystemCallError) &&
245 FIXNUM_P(sig = rb_attr_get(err, id_signo))) {
246 state = NUM2INT(sig);
247 break;
249 else if (sysex == EXIT_SUCCESS) {
250 sysex = EXIT_FAILURE;
254 mjit_finish(true); // We still need ISeqs here.
256 rb_ec_finalize(ec);
258 /* unlock again if finalizer took mutexes. */
259 rb_threadptr_unlock_all_locking_mutexes(th);
260 th = th0;
261 EC_POP_TAG();
262 th = th0;
263 rb_thread_stop_timer_thread();
264 ruby_vm_destruct(th->vm);
265 if (state) ruby_default_signal(state);
267 return sysex;
270 static int
271 rb_ec_exec_node(rb_execution_context_t *ec, void *n)
273 volatile int state;
274 rb_iseq_t *iseq = (rb_iseq_t *)n;
275 if (!n) return 0;
277 EC_PUSH_TAG(ec);
278 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
279 rb_thread_t *const th = rb_ec_thread_ptr(ec);
280 SAVE_ROOT_JMPBUF(th, {
281 rb_iseq_eval_main(iseq);
284 EC_POP_TAG();
285 return state;
288 void
289 ruby_stop(int ex)
291 exit(ruby_cleanup(ex));
295 ruby_executable_node(void *n, int *status)
297 VALUE v = (VALUE)n;
298 int s;
300 switch (v) {
301 case Qtrue: s = EXIT_SUCCESS; break;
302 case Qfalse: s = EXIT_FAILURE; break;
303 default:
304 if (!FIXNUM_P(v)) return TRUE;
305 s = FIX2INT(v);
307 if (status) *status = s;
308 return FALSE;
312 ruby_run_node(void *n)
314 rb_execution_context_t *ec = GET_EC();
315 int status;
316 if (!ruby_executable_node(n, &status)) {
317 rb_ec_cleanup(ec, 0);
318 return status;
320 ruby_init_stack((void *)&status);
321 return rb_ec_cleanup(ec, rb_ec_exec_node(ec, n));
325 ruby_exec_node(void *n)
327 ruby_init_stack((void *)&n);
328 return rb_ec_exec_node(GET_EC(), n);
332 * call-seq:
333 * Module.nesting -> array
335 * Returns the list of +Modules+ nested at the point of call.
337 * module M1
338 * module M2
339 * $a = Module.nesting
340 * end
341 * end
342 * $a #=> [M1::M2, M1]
343 * $a[0].name #=> "M1::M2"
346 static VALUE
347 rb_mod_nesting(VALUE _)
349 VALUE ary = rb_ary_new();
350 const rb_cref_t *cref = rb_vm_cref();
352 while (cref && CREF_NEXT(cref)) {
353 VALUE klass = CREF_CLASS(cref);
354 if (!CREF_PUSHED_BY_EVAL(cref) &&
355 !NIL_P(klass)) {
356 rb_ary_push(ary, klass);
358 cref = CREF_NEXT(cref);
360 return ary;
364 * call-seq:
365 * Module.constants -> array
366 * Module.constants(inherited) -> array
368 * In the first form, returns an array of the names of all
369 * constants accessible from the point of call.
370 * This list includes the names of all modules and classes
371 * defined in the global scope.
373 * Module.constants.first(4)
374 * # => [:ARGF, :ARGV, :ArgumentError, :Array]
376 * Module.constants.include?(:SEEK_SET) # => false
378 * class IO
379 * Module.constants.include?(:SEEK_SET) # => true
380 * end
382 * The second form calls the instance method +constants+.
385 static VALUE
386 rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
388 const rb_cref_t *cref = rb_vm_cref();
389 VALUE klass;
390 VALUE cbase = 0;
391 void *data = 0;
393 if (argc > 0 || mod != rb_cModule) {
394 return rb_mod_constants(argc, argv, mod);
397 while (cref) {
398 klass = CREF_CLASS(cref);
399 if (!CREF_PUSHED_BY_EVAL(cref) &&
400 !NIL_P(klass)) {
401 data = rb_mod_const_at(CREF_CLASS(cref), data);
402 if (!cbase) {
403 cbase = klass;
406 cref = CREF_NEXT(cref);
409 if (cbase) {
410 data = rb_mod_const_of(cbase, data);
412 return rb_const_list(data);
416 * Asserts that \a klass is not a frozen class.
417 * \param[in] klass a \c Module object
418 * \exception RuntimeError if \a klass is not a class or frozen.
419 * \ingroup class
421 void
422 rb_class_modify_check(VALUE klass)
424 if (SPECIAL_CONST_P(klass)) {
425 Check_Type(klass, T_CLASS);
427 if (RB_TYPE_P(klass, T_MODULE)) {
428 rb_module_set_initialized(klass);
430 if (OBJ_FROZEN(klass)) {
431 const char *desc;
433 if (FL_TEST(klass, FL_SINGLETON)) {
434 desc = "object";
435 klass = rb_ivar_get(klass, id__attached__);
436 if (!SPECIAL_CONST_P(klass)) {
437 switch (BUILTIN_TYPE(klass)) {
438 case T_MODULE:
439 case T_ICLASS:
440 desc = "Module";
441 break;
442 case T_CLASS:
443 desc = "Class";
444 break;
445 default:
446 break;
450 else {
451 switch (BUILTIN_TYPE(klass)) {
452 case T_MODULE:
453 case T_ICLASS:
454 desc = "module";
455 break;
456 case T_CLASS:
457 desc = "class";
458 break;
459 default:
460 Check_Type(klass, T_CLASS);
461 UNREACHABLE;
464 rb_frozen_error_raise(klass, "can't modify frozen %s: %"PRIsVALUE, desc, klass);
468 NORETURN(static void rb_longjmp(rb_execution_context_t *, int, volatile VALUE, VALUE));
469 static VALUE get_errinfo(void);
470 #define get_ec_errinfo(ec) rb_ec_get_errinfo(ec)
472 static VALUE
473 exc_setup_cause(VALUE exc, VALUE cause)
475 #if OPT_SUPPORT_JOKE
476 if (NIL_P(cause)) {
477 ID id_true_cause;
478 CONST_ID(id_true_cause, "true_cause");
480 cause = rb_attr_get(rb_eFatal, id_true_cause);
481 if (NIL_P(cause)) {
482 cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby");
483 rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */
484 OBJ_FREEZE(cause);
485 rb_ivar_set(rb_eFatal, id_true_cause, cause);
488 #endif
489 if (!NIL_P(cause) && cause != exc) {
490 rb_ivar_set(exc, id_cause, cause);
491 if (!rb_ivar_defined(cause, id_cause)) {
492 rb_ivar_set(cause, id_cause, Qnil);
495 return exc;
498 static inline VALUE
499 exc_setup_message(const rb_execution_context_t *ec, VALUE mesg, VALUE *cause)
501 int nocause = 0;
502 int nocircular = 0;
504 if (NIL_P(mesg)) {
505 mesg = ec->errinfo;
506 if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL);
507 nocause = 1;
509 if (NIL_P(mesg)) {
510 mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
511 nocause = 0;
512 nocircular = 1;
514 if (*cause == Qundef) {
515 if (nocause) {
516 *cause = Qnil;
517 nocircular = 1;
519 else if (!rb_ivar_defined(mesg, id_cause)) {
520 *cause = get_ec_errinfo(ec);
522 else {
523 nocircular = 1;
526 else if (!NIL_P(*cause) && !rb_obj_is_kind_of(*cause, rb_eException)) {
527 rb_raise(rb_eTypeError, "exception object expected");
530 if (!nocircular && !NIL_P(*cause) && *cause != Qundef && *cause != mesg) {
531 VALUE c = *cause;
532 while (!NIL_P(c = rb_attr_get(c, id_cause))) {
533 if (c == mesg) {
534 rb_raise(rb_eArgError, "circular causes");
538 return mesg;
541 static void
542 setup_exception(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE cause)
544 VALUE e;
545 int line;
546 const char *file = rb_source_location_cstr(&line);
547 const char *const volatile file0 = file;
549 if ((file && !NIL_P(mesg)) || (cause != Qundef)) {
550 volatile int state = 0;
552 EC_PUSH_TAG(ec);
553 if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) {
554 VALUE bt = rb_get_backtrace(mesg);
555 if (!NIL_P(bt) || cause == Qundef) {
556 if (OBJ_FROZEN(mesg)) {
557 mesg = rb_obj_dup(mesg);
560 if (cause != Qundef && !THROW_DATA_P(cause)) {
561 exc_setup_cause(mesg, cause);
563 if (NIL_P(bt)) {
564 VALUE at = rb_ec_backtrace_object(ec);
565 rb_ivar_set(mesg, idBt_locations, at);
566 set_backtrace(mesg, at);
568 rb_ec_reset_raised(ec);
570 EC_POP_TAG();
571 file = file0;
572 if (state) goto fatal;
575 if (!NIL_P(mesg)) {
576 ec->errinfo = mesg;
579 if (RTEST(ruby_debug) && !NIL_P(e = ec->errinfo) &&
580 !rb_obj_is_kind_of(e, rb_eSystemExit)) {
581 enum ruby_tag_type state;
583 mesg = e;
584 EC_PUSH_TAG(ec);
585 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
586 ec->errinfo = Qnil;
587 e = rb_obj_as_string(mesg);
588 ec->errinfo = mesg;
589 if (file && line) {
590 e = rb_sprintf("Exception `%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n",
591 rb_obj_class(mesg), file, line, e);
593 else if (file) {
594 e = rb_sprintf("Exception `%"PRIsVALUE"' at %s - %"PRIsVALUE"\n",
595 rb_obj_class(mesg), file, e);
597 else {
598 e = rb_sprintf("Exception `%"PRIsVALUE"' - %"PRIsVALUE"\n",
599 rb_obj_class(mesg), e);
601 warn_print_str(e);
603 EC_POP_TAG();
604 if (state == TAG_FATAL && ec->errinfo == exception_error) {
605 ec->errinfo = mesg;
607 else if (state) {
608 rb_ec_reset_raised(ec);
609 EC_JUMP_TAG(ec, state);
613 if (rb_ec_set_raised(ec)) {
614 goto fatal;
617 if (tag != TAG_FATAL) {
618 RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo));
619 EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg);
621 return;
623 fatal:
624 ec->errinfo = exception_error;
625 rb_ec_reset_raised(ec);
626 EC_JUMP_TAG(ec, TAG_FATAL);
629 /*! \private */
630 void
631 rb_ec_setup_exception(const rb_execution_context_t *ec, VALUE mesg, VALUE cause)
633 if (cause == Qundef) {
634 cause = get_ec_errinfo(ec);
636 if (cause != mesg) {
637 rb_ivar_set(mesg, id_cause, cause);
641 static void
642 rb_longjmp(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE cause)
644 mesg = exc_setup_message(ec, mesg, &cause);
645 setup_exception(ec, tag, mesg, cause);
646 rb_ec_raised_clear(ec);
647 EC_JUMP_TAG(ec, tag);
650 static VALUE make_exception(int argc, const VALUE *argv, int isstr);
652 NORETURN(static void rb_exc_exception(VALUE mesg, int tag, VALUE cause));
654 static void
655 rb_exc_exception(VALUE mesg, int tag, VALUE cause)
657 if (!NIL_P(mesg)) {
658 mesg = make_exception(1, &mesg, FALSE);
660 rb_longjmp(GET_EC(), tag, mesg, cause);
664 * Raises an exception in the current thread.
665 * \param[in] mesg an Exception class or an \c Exception object.
666 * \exception always raises an instance of the given exception class or
667 * the given \c Exception object.
668 * \ingroup exception
670 void
671 rb_exc_raise(VALUE mesg)
673 rb_exc_exception(mesg, TAG_RAISE, Qundef);
677 * Raises a fatal error in the current thread.
679 * Same as rb_exc_raise() but raises a fatal error, which Ruby codes
680 * cannot rescue.
681 * \ingroup exception
683 void
684 rb_exc_fatal(VALUE mesg)
686 rb_exc_exception(mesg, TAG_FATAL, Qnil);
689 void
690 rb_interrupt(void)
692 rb_exc_raise(rb_exc_new(rb_eInterrupt, 0, 0));
695 enum {raise_opt_cause, raise_max_opt}; /*< \private */
697 static int
698 extract_raise_opts(int argc, const VALUE *argv, VALUE *opts)
700 int i;
701 if (argc > 0) {
702 VALUE opt = argv[argc-1];
703 if (RB_TYPE_P(opt, T_HASH)) {
704 if (!RHASH_EMPTY_P(opt)) {
705 ID keywords[1];
706 CONST_ID(keywords[0], "cause");
707 rb_get_kwargs(opt, keywords, 0, -1-raise_max_opt, opts);
708 if (RHASH_EMPTY_P(opt)) --argc;
709 return argc;
713 for (i = 0; i < raise_max_opt; ++i) {
714 opts[i] = Qundef;
716 return argc;
719 VALUE
720 rb_f_raise(int argc, VALUE *argv)
722 VALUE err;
723 VALUE opts[raise_max_opt], *const cause = &opts[raise_opt_cause];
725 argc = extract_raise_opts(argc, argv, opts);
726 if (argc == 0) {
727 if (*cause != Qundef) {
728 rb_raise(rb_eArgError, "only cause is given with no arguments");
730 err = get_errinfo();
731 if (!NIL_P(err)) {
732 argc = 1;
733 argv = &err;
736 rb_raise_jump(rb_make_exception(argc, argv), *cause);
738 UNREACHABLE_RETURN(Qnil);
742 * call-seq:
743 * raise
744 * raise(string, cause: $!)
745 * raise(exception [, string [, array]], cause: $!)
746 * fail
747 * fail(string, cause: $!)
748 * fail(exception [, string [, array]], cause: $!)
750 * With no arguments, raises the exception in <code>$!</code> or raises
751 * a RuntimeError if <code>$!</code> is +nil+. With a single +String+
752 * argument, raises a +RuntimeError+ with the string as a message. Otherwise,
753 * the first parameter should be an +Exception+ class (or another
754 * object that returns an +Exception+ object when sent an +exception+
755 * message). The optional second parameter sets the message associated with
756 * the exception (accessible via Exception#message), and the third parameter
757 * is an array of callback information (accessible via Exception#backtrace).
758 * The +cause+ of the generated exception (accessible via Exception#cause)
759 * is automatically set to the "current" exception (<code>$!</code>), if any.
760 * An alternative value, either an +Exception+ object or +nil+, can be
761 * specified via the +:cause+ argument.
763 * Exceptions are caught by the +rescue+ clause of
764 * <code>begin...end</code> blocks.
766 * raise "Failed to create socket"
767 * raise ArgumentError, "No parameters", caller
770 static VALUE
771 f_raise(int c, VALUE *v, VALUE _)
773 return rb_f_raise(c, v);
776 static VALUE
777 make_exception(int argc, const VALUE *argv, int isstr)
779 VALUE mesg, exc;
781 mesg = Qnil;
782 switch (argc) {
783 case 0:
784 return Qnil;
785 case 1:
786 exc = argv[0];
787 if (isstr &&! NIL_P(exc)) {
788 mesg = rb_check_string_type(exc);
789 if (!NIL_P(mesg)) {
790 return rb_exc_new3(rb_eRuntimeError, mesg);
794 case 2:
795 case 3:
796 break;
797 default:
798 rb_error_arity(argc, 0, 3);
800 if (NIL_P(mesg)) {
801 mesg = rb_check_funcall(argv[0], idException, argc != 1, &argv[1]);
803 if (mesg == Qundef) {
804 rb_raise(rb_eTypeError, "exception class/object expected");
806 if (!rb_obj_is_kind_of(mesg, rb_eException)) {
807 rb_raise(rb_eTypeError, "exception object expected");
809 if (argc == 3) {
810 set_backtrace(mesg, argv[2]);
813 return mesg;
816 VALUE
817 rb_make_exception(int argc, const VALUE *argv)
819 return make_exception(argc, argv, TRUE);
822 /*! \private
824 static void
825 rb_raise_jump(VALUE mesg, VALUE cause)
827 rb_execution_context_t *ec = GET_EC();
828 const rb_control_frame_t *cfp = ec->cfp;
829 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
830 VALUE klass = me->owner;
831 VALUE self = cfp->self;
832 ID mid = me->called_id;
834 rb_vm_pop_frame(ec);
835 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, self, me->def->original_id, mid, klass, Qnil);
837 rb_longjmp(ec, TAG_RAISE, mesg, cause);
840 void
841 rb_jump_tag(int tag)
843 if (UNLIKELY(tag < TAG_RETURN || tag > TAG_FATAL)) {
844 unknown_longjmp_status(tag);
846 EC_JUMP_TAG(GET_EC(), tag);
850 rb_block_given_p(void)
852 if (rb_vm_frame_block_handler(GET_EC()->cfp) == VM_BLOCK_HANDLER_NONE) {
853 return FALSE;
855 else {
856 return TRUE;
860 int rb_vm_cframe_keyword_p(const rb_control_frame_t *cfp);
863 rb_keyword_given_p(void)
865 return rb_vm_cframe_keyword_p(GET_EC()->cfp);
868 VALUE rb_eThreadError;
870 void
871 rb_need_block(void)
873 if (!rb_block_given_p()) {
874 rb_vm_localjump_error("no block given", Qnil, 0);
878 VALUE
879 rb_rescue2(VALUE (* b_proc) (VALUE), VALUE data1,
880 VALUE (* r_proc) (VALUE, VALUE), VALUE data2, ...)
882 va_list ap;
883 va_start(ap, data2);
884 VALUE ret = rb_vrescue2(b_proc, data1, r_proc, data2, ap);
885 va_end(ap);
886 return ret;
889 VALUE
890 rb_vrescue2(VALUE (* b_proc) (VALUE), VALUE data1,
891 VALUE (* r_proc) (VALUE, VALUE), VALUE data2,
892 va_list args)
894 enum ruby_tag_type state;
895 rb_execution_context_t * volatile ec = GET_EC();
896 rb_control_frame_t *volatile cfp = ec->cfp;
897 volatile VALUE result = Qfalse;
898 volatile VALUE e_info = ec->errinfo;
900 EC_PUSH_TAG(ec);
901 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
902 retry_entry:
903 result = (*b_proc) (data1);
905 else if (result) {
906 /* escape from r_proc */
907 if (state == TAG_RETRY) {
908 state = TAG_NONE;
909 ec->errinfo = Qnil;
910 result = Qfalse;
911 goto retry_entry;
914 else {
915 rb_vm_rewind_cfp(ec, cfp);
917 if (state == TAG_RAISE) {
918 int handle = FALSE;
919 VALUE eclass;
920 va_list ap;
922 result = Qnil;
923 /* reuses args when raised again after retrying in r_proc */
924 va_copy(ap, args);
925 while ((eclass = va_arg(ap, VALUE)) != 0) {
926 if (rb_obj_is_kind_of(ec->errinfo, eclass)) {
927 handle = TRUE;
928 break;
931 va_end(ap);
933 if (handle) {
934 state = TAG_NONE;
935 if (r_proc) {
936 result = (*r_proc) (data2, ec->errinfo);
938 ec->errinfo = e_info;
942 EC_POP_TAG();
943 if (state)
944 EC_JUMP_TAG(ec, state);
946 return result;
949 VALUE
950 rb_rescue(VALUE (* b_proc)(VALUE), VALUE data1,
951 VALUE (* r_proc)(VALUE, VALUE), VALUE data2)
953 return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
954 (VALUE)0);
957 VALUE
958 rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate)
960 volatile VALUE result = Qnil;
961 volatile enum ruby_tag_type state;
962 rb_execution_context_t * volatile ec = GET_EC();
963 rb_control_frame_t *volatile cfp = ec->cfp;
965 EC_PUSH_TAG(ec);
966 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
967 SAVE_ROOT_JMPBUF(rb_ec_thread_ptr(ec), result = (*proc) (data));
969 else {
970 rb_vm_rewind_cfp(ec, cfp);
972 EC_POP_TAG();
974 if (pstate != NULL) *pstate = state;
975 return result;
978 VALUE
979 rb_ensure(VALUE (*b_proc)(VALUE), VALUE data1, VALUE (*e_proc)(VALUE), VALUE data2)
981 int state;
982 volatile VALUE result = Qnil;
983 VALUE errinfo;
984 rb_execution_context_t * volatile ec = GET_EC();
985 rb_ensure_list_t ensure_list;
986 ensure_list.entry.marker = 0;
987 ensure_list.entry.e_proc = e_proc;
988 ensure_list.entry.data2 = data2;
989 ensure_list.next = ec->ensure_list;
990 ec->ensure_list = &ensure_list;
991 EC_PUSH_TAG(ec);
992 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
993 result = (*b_proc) (data1);
995 EC_POP_TAG();
996 errinfo = ec->errinfo;
997 if (!NIL_P(errinfo) && !RB_TYPE_P(errinfo, T_OBJECT)) {
998 ec->errinfo = Qnil;
1000 ec->ensure_list=ensure_list.next;
1001 (*ensure_list.entry.e_proc)(ensure_list.entry.data2);
1002 ec->errinfo = errinfo;
1003 if (state)
1004 EC_JUMP_TAG(ec, state);
1005 return result;
1008 static ID
1009 frame_func_id(const rb_control_frame_t *cfp)
1011 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1013 if (me) {
1014 return me->def->original_id;
1016 else {
1017 return 0;
1021 static ID
1022 frame_called_id(rb_control_frame_t *cfp)
1024 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1026 if (me) {
1027 return me->called_id;
1029 else {
1030 return 0;
1035 rb_frame_this_func(void)
1037 return frame_func_id(GET_EC()->cfp);
1041 rb_frame_callee(void)
1043 return frame_called_id(GET_EC()->cfp);
1046 static rb_control_frame_t *
1047 previous_frame(const rb_execution_context_t *ec)
1049 rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
1050 /* check if prev_cfp can be accessible */
1051 if ((void *)(ec->vm_stack + ec->vm_stack_size) == (void *)(prev_cfp)) {
1052 return 0;
1054 return prev_cfp;
1057 static ID
1058 prev_frame_callee(void)
1060 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1061 if (!prev_cfp) return 0;
1062 return frame_called_id(prev_cfp);
1065 static ID
1066 prev_frame_func(void)
1068 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1069 if (!prev_cfp) return 0;
1070 return frame_func_id(prev_cfp);
1074 * \private
1075 * Returns the ID of the last method in the call stack.
1076 * \sa rb_frame_this_func
1077 * \ingroup defmethod
1080 rb_frame_last_func(void)
1082 const rb_execution_context_t *ec = GET_EC();
1083 const rb_control_frame_t *cfp = ec->cfp;
1084 ID mid;
1086 while (!(mid = frame_func_id(cfp)) &&
1087 (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp),
1088 !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)));
1089 return mid;
1093 * call-seq:
1094 * append_features(mod) -> mod
1096 * When this module is included in another, Ruby calls
1097 * #append_features in this module, passing it the receiving module
1098 * in _mod_. Ruby's default implementation is to add the constants,
1099 * methods, and module variables of this module to _mod_ if this
1100 * module has not already been added to _mod_ or one of its
1101 * ancestors. See also Module#include.
1104 static VALUE
1105 rb_mod_append_features(VALUE module, VALUE include)
1107 if (!CLASS_OR_MODULE_P(include)) {
1108 Check_Type(include, T_CLASS);
1110 rb_include_module(include, module);
1112 return module;
1116 * call-seq:
1117 * include(module, ...) -> self
1119 * Invokes Module.append_features on each parameter in reverse order.
1122 static VALUE
1123 rb_mod_include(int argc, VALUE *argv, VALUE module)
1125 int i;
1126 ID id_append_features, id_included;
1128 CONST_ID(id_append_features, "append_features");
1129 CONST_ID(id_included, "included");
1131 if (FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1132 rb_raise(rb_eTypeError, "Refinement#include has been removed");
1135 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1136 for (i = 0; i < argc; i++) {
1137 Check_Type(argv[i], T_MODULE);
1138 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1139 rb_raise(rb_eTypeError, "Cannot include refinement");
1142 while (argc--) {
1143 rb_funcall(argv[argc], id_append_features, 1, module);
1144 rb_funcall(argv[argc], id_included, 1, module);
1146 return module;
1150 * call-seq:
1151 * prepend_features(mod) -> mod
1153 * When this module is prepended in another, Ruby calls
1154 * #prepend_features in this module, passing it the receiving module
1155 * in _mod_. Ruby's default implementation is to overlay the
1156 * constants, methods, and module variables of this module to _mod_
1157 * if this module has not already been added to _mod_ or one of its
1158 * ancestors. See also Module#prepend.
1161 static VALUE
1162 rb_mod_prepend_features(VALUE module, VALUE prepend)
1164 if (!CLASS_OR_MODULE_P(prepend)) {
1165 Check_Type(prepend, T_CLASS);
1167 rb_prepend_module(prepend, module);
1169 return module;
1173 * call-seq:
1174 * prepend(module, ...) -> self
1176 * Invokes Module.prepend_features on each parameter in reverse order.
1179 static VALUE
1180 rb_mod_prepend(int argc, VALUE *argv, VALUE module)
1182 int i;
1183 ID id_prepend_features, id_prepended;
1185 if (FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1186 rb_raise(rb_eTypeError, "Refinement#prepend has been removed");
1189 CONST_ID(id_prepend_features, "prepend_features");
1190 CONST_ID(id_prepended, "prepended");
1192 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1193 for (i = 0; i < argc; i++) {
1194 Check_Type(argv[i], T_MODULE);
1195 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1196 rb_raise(rb_eTypeError, "Cannot prepend refinement");
1199 while (argc--) {
1200 rb_funcall(argv[argc], id_prepend_features, 1, module);
1201 rb_funcall(argv[argc], id_prepended, 1, module);
1203 return module;
1206 static void
1207 ensure_class_or_module(VALUE obj)
1209 if (!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE)) {
1210 rb_raise(rb_eTypeError,
1211 "wrong argument type %"PRIsVALUE" (expected Class or Module)",
1212 rb_obj_class(obj));
1216 static VALUE
1217 hidden_identity_hash_new(void)
1219 VALUE hash = rb_ident_hash_new();
1221 RBASIC_CLEAR_CLASS(hash); /* hide from ObjectSpace */
1222 return hash;
1225 static VALUE
1226 refinement_superclass(VALUE superclass)
1228 if (RB_TYPE_P(superclass, T_MODULE)) {
1229 /* FIXME: Should ancestors of superclass be used here? */
1230 return rb_include_class_new(RCLASS_ORIGIN(superclass), rb_cBasicObject);
1232 else {
1233 return superclass;
1238 * \private
1240 static void
1241 rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module)
1243 VALUE iclass, c, superclass = klass;
1245 ensure_class_or_module(klass);
1246 Check_Type(module, T_MODULE);
1247 if (NIL_P(CREF_REFINEMENTS(cref))) {
1248 CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new());
1250 else {
1251 if (CREF_OMOD_SHARED(cref)) {
1252 CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref)));
1253 CREF_OMOD_SHARED_UNSET(cref);
1255 if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) {
1256 superclass = c;
1257 while (c && RB_TYPE_P(c, T_ICLASS)) {
1258 if (RBASIC(c)->klass == module) {
1259 /* already used refinement */
1260 return;
1262 c = RCLASS_SUPER(c);
1266 FL_SET(module, RMODULE_IS_OVERLAID);
1267 superclass = refinement_superclass(superclass);
1268 c = iclass = rb_include_class_new(module, superclass);
1269 RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1271 RCLASS_M_TBL(c) = RCLASS_M_TBL(module);
1273 module = RCLASS_SUPER(module);
1274 while (module && module != klass) {
1275 FL_SET(module, RMODULE_IS_OVERLAID);
1276 c = RCLASS_SET_SUPER(c, rb_include_class_new(module, RCLASS_SUPER(c)));
1277 RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1278 module = RCLASS_SUPER(module);
1280 rb_hash_aset(CREF_REFINEMENTS(cref), klass, iclass);
1283 static int
1284 using_refinement(VALUE klass, VALUE module, VALUE arg)
1286 rb_cref_t *cref = (rb_cref_t *) arg;
1288 rb_using_refinement(cref, klass, module);
1289 return ST_CONTINUE;
1292 static void
1293 using_module_recursive(const rb_cref_t *cref, VALUE klass)
1295 ID id_refinements;
1296 VALUE super, module, refinements;
1298 super = RCLASS_SUPER(klass);
1299 if (super) {
1300 using_module_recursive(cref, super);
1302 switch (BUILTIN_TYPE(klass)) {
1303 case T_MODULE:
1304 module = klass;
1305 break;
1307 case T_ICLASS:
1308 module = RBASIC(klass)->klass;
1309 break;
1311 default:
1312 rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)",
1313 rb_obj_classname(klass));
1314 break;
1316 CONST_ID(id_refinements, "__refinements__");
1317 refinements = rb_attr_get(module, id_refinements);
1318 if (NIL_P(refinements)) return;
1319 rb_hash_foreach(refinements, using_refinement, (VALUE) cref);
1323 * \private
1325 static void
1326 rb_using_module(const rb_cref_t *cref, VALUE module)
1328 Check_Type(module, T_MODULE);
1329 using_module_recursive(cref, module);
1330 rb_clear_method_cache_all();
1334 * call-seq:
1335 * refined_class -> class
1337 * Return the class refined by the receiver.
1339 VALUE
1340 rb_refinement_module_get_refined_class(VALUE module)
1342 ID id_refined_class;
1344 CONST_ID(id_refined_class, "__refined_class__");
1345 return rb_attr_get(module, id_refined_class);
1348 static void
1349 add_activated_refinement(VALUE activated_refinements,
1350 VALUE klass, VALUE refinement)
1352 VALUE iclass, c, superclass = klass;
1354 if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) {
1355 superclass = c;
1356 while (c && RB_TYPE_P(c, T_ICLASS)) {
1357 if (RBASIC(c)->klass == refinement) {
1358 /* already used refinement */
1359 return;
1361 c = RCLASS_SUPER(c);
1364 FL_SET(refinement, RMODULE_IS_OVERLAID);
1365 superclass = refinement_superclass(superclass);
1366 c = iclass = rb_include_class_new(refinement, superclass);
1367 RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1368 refinement = RCLASS_SUPER(refinement);
1369 while (refinement && refinement != klass) {
1370 FL_SET(refinement, RMODULE_IS_OVERLAID);
1371 c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c)));
1372 RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1373 refinement = RCLASS_SUPER(refinement);
1375 rb_hash_aset(activated_refinements, klass, iclass);
1379 * call-seq:
1380 * refine(mod) { block } -> module
1382 * Refine <i>mod</i> in the receiver.
1384 * Returns a module, where refined methods are defined.
1387 static VALUE
1388 rb_mod_refine(VALUE module, VALUE klass)
1390 VALUE refinement;
1391 ID id_refinements, id_activated_refinements,
1392 id_refined_class, id_defined_at;
1393 VALUE refinements, activated_refinements;
1394 rb_thread_t *th = GET_THREAD();
1395 VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
1397 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1398 rb_raise(rb_eArgError, "no block given");
1400 if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
1401 rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
1404 ensure_class_or_module(klass);
1405 CONST_ID(id_refinements, "__refinements__");
1406 refinements = rb_attr_get(module, id_refinements);
1407 if (NIL_P(refinements)) {
1408 refinements = hidden_identity_hash_new();
1409 rb_ivar_set(module, id_refinements, refinements);
1411 CONST_ID(id_activated_refinements, "__activated_refinements__");
1412 activated_refinements = rb_attr_get(module, id_activated_refinements);
1413 if (NIL_P(activated_refinements)) {
1414 activated_refinements = hidden_identity_hash_new();
1415 rb_ivar_set(module, id_activated_refinements,
1416 activated_refinements);
1418 refinement = rb_hash_lookup(refinements, klass);
1419 if (NIL_P(refinement)) {
1420 VALUE superclass = refinement_superclass(klass);
1421 refinement = rb_refinement_new();
1422 RCLASS_SET_SUPER(refinement, superclass);
1423 FL_SET(refinement, RMODULE_IS_REFINEMENT);
1424 CONST_ID(id_refined_class, "__refined_class__");
1425 rb_ivar_set(refinement, id_refined_class, klass);
1426 CONST_ID(id_defined_at, "__defined_at__");
1427 rb_ivar_set(refinement, id_defined_at, module);
1428 rb_hash_aset(refinements, klass, refinement);
1429 add_activated_refinement(activated_refinements, klass, refinement);
1431 rb_yield_refine_block(refinement, activated_refinements);
1432 return refinement;
1435 static void
1436 ignored_block(VALUE module, const char *klass)
1438 const char *anon = "";
1439 Check_Type(module, T_MODULE);
1440 if (!RTEST(rb_search_class_path(module))) {
1441 anon = ", maybe for Module.new";
1443 rb_warn("%s""using doesn't call the given block""%s.", klass, anon);
1447 * call-seq:
1448 * using(module) -> self
1450 * Import class refinements from <i>module</i> into the current class or
1451 * module definition.
1454 static VALUE
1455 mod_using(VALUE self, VALUE module)
1457 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1459 if (prev_frame_func()) {
1460 rb_raise(rb_eRuntimeError,
1461 "Module#using is not permitted in methods");
1463 if (prev_cfp && prev_cfp->self != self) {
1464 rb_raise(rb_eRuntimeError, "Module#using is not called on self");
1466 if (rb_block_given_p()) {
1467 ignored_block(module, "Module#");
1469 rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1470 return self;
1475 * call-seq:
1476 * refinements -> array
1478 * Returns an array of modules defined within the receiver.
1480 * module A
1481 * refine Integer do
1482 * end
1484 * refine String do
1485 * end
1486 * end
1488 * p A.refinements
1490 * <em>produces:</em>
1492 * [#<refinement:Integer@A>, #<refinement:String@A>]
1494 static VALUE
1495 mod_refinements(VALUE self)
1497 ID id_refinements;
1498 VALUE refinements;
1500 CONST_ID(id_refinements, "__refinements__");
1501 refinements = rb_attr_get(self, id_refinements);
1502 if (NIL_P(refinements)) {
1503 return rb_ary_new();
1505 return rb_hash_values(refinements);
1508 static int
1509 used_modules_i(VALUE _, VALUE mod, VALUE ary)
1511 ID id_defined_at;
1512 CONST_ID(id_defined_at, "__defined_at__");
1513 while (FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1514 rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at));
1515 mod = RCLASS_SUPER(mod);
1517 return ST_CONTINUE;
1521 * call-seq:
1522 * used_modules -> array
1524 * Returns an array of all modules used in the current scope. The ordering
1525 * of modules in the resulting array is not defined.
1527 * module A
1528 * refine Object do
1529 * end
1530 * end
1532 * module B
1533 * refine Object do
1534 * end
1535 * end
1537 * using A
1538 * using B
1539 * p Module.used_modules
1541 * <em>produces:</em>
1543 * [B, A]
1545 static VALUE
1546 rb_mod_s_used_modules(VALUE _)
1548 const rb_cref_t *cref = rb_vm_cref();
1549 VALUE ary = rb_ary_new();
1551 while (cref) {
1552 if (!NIL_P(CREF_REFINEMENTS(cref))) {
1553 rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
1555 cref = CREF_NEXT(cref);
1558 return rb_funcall(ary, rb_intern("uniq"), 0);
1561 static int
1562 used_refinements_i(VALUE _, VALUE mod, VALUE ary)
1564 while (FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1565 rb_ary_push(ary, rb_class_of(mod));
1566 mod = RCLASS_SUPER(mod);
1568 return ST_CONTINUE;
1572 * call-seq:
1573 * used_refinements -> array
1575 * Returns an array of all modules used in the current scope. The ordering
1576 * of modules in the resulting array is not defined.
1578 * module A
1579 * refine Object do
1580 * end
1581 * end
1583 * module B
1584 * refine Object do
1585 * end
1586 * end
1588 * using A
1589 * using B
1590 * p Module.used_refinements
1592 * <em>produces:</em>
1594 * [#<refinement:Object@B>, #<refinement:Object@A>]
1596 static VALUE
1597 rb_mod_s_used_refinements(VALUE _)
1599 const rb_cref_t *cref = rb_vm_cref();
1600 VALUE ary = rb_ary_new();
1602 while (cref) {
1603 if (!NIL_P(CREF_REFINEMENTS(cref))) {
1604 rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary);
1606 cref = CREF_NEXT(cref);
1609 return ary;
1612 struct refinement_import_methods_arg {
1613 rb_cref_t *cref;
1614 VALUE refinement;
1615 VALUE module;
1618 /* vm.c */
1619 rb_cref_t *rb_vm_cref_dup_without_refinements(const rb_cref_t *cref);
1621 static enum rb_id_table_iterator_result
1622 refinement_import_methods_i(ID key, VALUE value, void *data)
1624 const rb_method_entry_t *me = (const rb_method_entry_t *)value;
1625 struct refinement_import_methods_arg *arg = (struct refinement_import_methods_arg *)data;
1627 if (me->def->type != VM_METHOD_TYPE_ISEQ) {
1628 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));
1630 rb_cref_t *new_cref = rb_vm_cref_dup_without_refinements(me->def->body.iseq.cref);
1631 CREF_REFINEMENTS_SET(new_cref, CREF_REFINEMENTS(arg->cref));
1632 rb_add_method_iseq(arg->refinement, key, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me));
1633 return ID_TABLE_CONTINUE;
1637 * Note: docs for the method are in class.c
1640 static VALUE
1641 refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
1643 int i;
1644 struct refinement_import_methods_arg arg;
1646 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1647 for (i = 0; i < argc; i++) {
1648 Check_Type(argv[i], T_MODULE);
1649 if (RCLASS_SUPER(argv[i])) {
1650 rb_warn("%"PRIsVALUE" has ancestors, but Refinement#import_methods doesn't import their methods", rb_class_path(argv[i]));
1653 arg.cref = rb_vm_cref_replace_with_duplicated_cref();
1654 arg.refinement = refinement;
1655 for (i = 0; i < argc; i++) {
1656 arg.module = argv[i];
1657 struct rb_id_table *m_tbl = RCLASS_M_TBL(argv[i]);
1658 if (!m_tbl) continue;
1659 rb_id_table_foreach(m_tbl, refinement_import_methods_i, &arg);
1661 return refinement;
1664 void
1665 rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
1667 rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
1670 void
1671 rb_obj_call_init_kw(VALUE obj, int argc, const VALUE *argv, int kw_splat)
1673 PASS_PASSED_BLOCK_HANDLER();
1674 rb_funcallv_kw(obj, idInitialize, argc, argv, kw_splat);
1677 void
1678 rb_extend_object(VALUE obj, VALUE module)
1680 rb_include_module(rb_singleton_class(obj), module);
1684 * call-seq:
1685 * extend_object(obj) -> obj
1687 * Extends the specified object by adding this module's constants and
1688 * methods (which are added as singleton methods). This is the callback
1689 * method used by Object#extend.
1691 * module Picky
1692 * def Picky.extend_object(o)
1693 * if String === o
1694 * puts "Can't add Picky to a String"
1695 * else
1696 * puts "Picky added to #{o.class}"
1697 * super
1698 * end
1699 * end
1700 * end
1701 * (s = Array.new).extend Picky # Call Object.extend
1702 * (s = "quick brown fox").extend Picky
1704 * <em>produces:</em>
1706 * Picky added to Array
1707 * Can't add Picky to a String
1710 static VALUE
1711 rb_mod_extend_object(VALUE mod, VALUE obj)
1713 rb_extend_object(obj, mod);
1714 return obj;
1718 * call-seq:
1719 * obj.extend(module, ...) -> obj
1721 * Adds to _obj_ the instance methods from each module given as a
1722 * parameter.
1724 * module Mod
1725 * def hello
1726 * "Hello from Mod.\n"
1727 * end
1728 * end
1730 * class Klass
1731 * def hello
1732 * "Hello from Klass.\n"
1733 * end
1734 * end
1736 * k = Klass.new
1737 * k.hello #=> "Hello from Klass.\n"
1738 * k.extend(Mod) #=> #<Klass:0x401b3bc8>
1739 * k.hello #=> "Hello from Mod.\n"
1742 static VALUE
1743 rb_obj_extend(int argc, VALUE *argv, VALUE obj)
1745 int i;
1746 ID id_extend_object, id_extended;
1748 CONST_ID(id_extend_object, "extend_object");
1749 CONST_ID(id_extended, "extended");
1751 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1752 for (i = 0; i < argc; i++) {
1753 Check_Type(argv[i], T_MODULE);
1754 if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1755 rb_raise(rb_eTypeError, "Cannot extend object with refinement");
1758 while (argc--) {
1759 rb_funcall(argv[argc], id_extend_object, 1, obj);
1760 rb_funcall(argv[argc], id_extended, 1, obj);
1762 return obj;
1766 * call-seq:
1767 * include(module, ...) -> self
1769 * Invokes Module.append_features on each parameter in turn.
1770 * Effectively adds the methods and constants in each module to the
1771 * receiver.
1774 static VALUE
1775 top_include(int argc, VALUE *argv, VALUE self)
1777 rb_thread_t *th = GET_THREAD();
1779 if (th->top_wrapper) {
1780 rb_warning("main.include in the wrapped load is effective only in wrapper module");
1781 return rb_mod_include(argc, argv, th->top_wrapper);
1783 return rb_mod_include(argc, argv, rb_cObject);
1787 * call-seq:
1788 * using(module) -> self
1790 * Import class refinements from <i>module</i> into the scope where
1791 * #using is called.
1794 static VALUE
1795 top_using(VALUE self, VALUE module)
1797 const rb_cref_t *cref = rb_vm_cref();
1798 rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1800 if (CREF_NEXT(cref) || (prev_cfp && rb_vm_frame_method_entry(prev_cfp))) {
1801 rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel");
1803 if (rb_block_given_p()) {
1804 ignored_block(module, "main.");
1806 rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1807 return self;
1810 static const VALUE *
1811 errinfo_place(const rb_execution_context_t *ec)
1813 const rb_control_frame_t *cfp = ec->cfp;
1814 const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
1816 while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) {
1817 if (VM_FRAME_RUBYFRAME_P(cfp)) {
1818 if (cfp->iseq->body->type == ISEQ_TYPE_RESCUE) {
1819 return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1821 else if (cfp->iseq->body->type == ISEQ_TYPE_ENSURE &&
1822 !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) &&
1823 !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) {
1824 return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1827 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1829 return 0;
1832 VALUE
1833 rb_ec_get_errinfo(const rb_execution_context_t *ec)
1835 const VALUE *ptr = errinfo_place(ec);
1836 if (ptr) {
1837 return *ptr;
1839 else {
1840 return ec->errinfo;
1844 static VALUE
1845 get_errinfo(void)
1847 return get_ec_errinfo(GET_EC());
1850 static VALUE
1851 errinfo_getter(ID id, VALUE *_)
1853 return get_errinfo();
1856 VALUE
1857 rb_errinfo(void)
1859 return GET_EC()->errinfo;
1862 void
1863 rb_set_errinfo(VALUE err)
1865 if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) {
1866 rb_raise(rb_eTypeError, "assigning non-exception to $!");
1868 GET_EC()->errinfo = err;
1871 static VALUE
1872 errat_getter(ID id, VALUE *_)
1874 VALUE err = get_errinfo();
1875 if (!NIL_P(err)) {
1876 return rb_get_backtrace(err);
1878 else {
1879 return Qnil;
1883 static void
1884 errat_setter(VALUE val, ID id, VALUE *var)
1886 VALUE err = get_errinfo();
1887 if (NIL_P(err)) {
1888 rb_raise(rb_eArgError, "$! not set");
1890 set_backtrace(err, val);
1894 * call-seq:
1895 * __method__ -> symbol
1897 * Returns the name at the definition of the current method as a
1898 * Symbol.
1899 * If called outside of a method, it returns <code>nil</code>.
1903 static VALUE
1904 rb_f_method_name(VALUE _)
1906 ID fname = prev_frame_func(); /* need *method* ID */
1908 if (fname) {
1909 return ID2SYM(fname);
1911 else {
1912 return Qnil;
1917 * call-seq:
1918 * __callee__ -> symbol
1920 * Returns the called name of the current method as a Symbol.
1921 * If called outside of a method, it returns <code>nil</code>.
1925 static VALUE
1926 rb_f_callee_name(VALUE _)
1928 ID fname = prev_frame_callee(); /* need *callee* ID */
1930 if (fname) {
1931 return ID2SYM(fname);
1933 else {
1934 return Qnil;
1939 * call-seq:
1940 * __dir__ -> string
1942 * Returns the canonicalized absolute path of the directory of the file from
1943 * which this method is called. It means symlinks in the path is resolved.
1944 * If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>.
1945 * The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>.
1948 static VALUE
1949 f_current_dirname(VALUE _)
1951 VALUE base = rb_current_realfilepath();
1952 if (NIL_P(base)) {
1953 return Qnil;
1955 base = rb_file_dirname(base);
1956 return base;
1960 * call-seq:
1961 * global_variables -> array
1963 * Returns an array of the names of global variables. This includes
1964 * special regexp global variables such as <tt>$~</tt> and <tt>$+</tt>,
1965 * but does not include the numbered regexp global variables (<tt>$1</tt>,
1966 * <tt>$2</tt>, etc.).
1968 * global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
1971 static VALUE
1972 f_global_variables(VALUE _)
1974 return rb_f_global_variables();
1978 * call-seq:
1979 * trace_var(symbol, cmd ) -> nil
1980 * trace_var(symbol) {|val| block } -> nil
1982 * Controls tracing of assignments to global variables. The parameter
1983 * +symbol+ identifies the variable (as either a string name or a
1984 * symbol identifier). _cmd_ (which may be a string or a
1985 * +Proc+ object) or block is executed whenever the variable
1986 * is assigned. The block or +Proc+ object receives the
1987 * variable's new value as a parameter. Also see
1988 * Kernel::untrace_var.
1990 * trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
1991 * $_ = "hello"
1992 * $_ = ' there'
1994 * <em>produces:</em>
1996 * $_ is now 'hello'
1997 * $_ is now ' there'
2000 static VALUE
2001 f_trace_var(int c, const VALUE *a, VALUE _)
2003 return rb_f_trace_var(c, a);
2007 * call-seq:
2008 * untrace_var(symbol [, cmd] ) -> array or nil
2010 * Removes tracing for the specified command on the given global
2011 * variable and returns +nil+. If no command is specified,
2012 * removes all tracing for that variable and returns an array
2013 * containing the commands actually removed.
2016 static VALUE
2017 f_untrace_var(int c, const VALUE *a, VALUE _)
2019 return rb_f_untrace_var(c, a);
2022 void
2023 Init_eval(void)
2025 rb_define_virtual_variable("$@", errat_getter, errat_setter);
2026 rb_define_virtual_variable("$!", errinfo_getter, 0);
2028 rb_gvar_ractor_local("$@");
2029 rb_gvar_ractor_local("$!");
2031 rb_define_global_function("raise", f_raise, -1);
2032 rb_define_global_function("fail", f_raise, -1);
2034 rb_define_global_function("global_variables", f_global_variables, 0);
2036 rb_define_global_function("__method__", rb_f_method_name, 0);
2037 rb_define_global_function("__callee__", rb_f_callee_name, 0);
2038 rb_define_global_function("__dir__", f_current_dirname, 0);
2040 rb_define_method(rb_cModule, "include", rb_mod_include, -1);
2041 rb_define_method(rb_cModule, "prepend", rb_mod_prepend, -1);
2043 rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
2044 rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
2045 rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1);
2046 rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1);
2047 rb_define_private_method(rb_cModule, "using", mod_using, 1);
2048 rb_define_method(rb_cModule, "refinements", mod_refinements, 0);
2049 rb_define_singleton_method(rb_cModule, "used_modules",
2050 rb_mod_s_used_modules, 0);
2051 rb_define_singleton_method(rb_cModule, "used_refinements",
2052 rb_mod_s_used_refinements, 0);
2053 rb_undef_method(rb_cClass, "refine");
2054 rb_define_private_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
2055 rb_define_method(rb_cRefinement, "refined_class", rb_refinement_module_get_refined_class, 0);
2056 rb_undef_method(rb_cRefinement, "append_features");
2057 rb_undef_method(rb_cRefinement, "prepend_features");
2058 rb_undef_method(rb_cRefinement, "extend_object");
2060 rb_undef_method(rb_cClass, "module_function");
2062 Init_vm_eval();
2063 Init_eval_method();
2065 rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
2066 rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1);
2068 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
2069 "include", top_include, -1);
2070 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
2071 "using", top_using, 1);
2073 rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
2075 rb_define_global_function("trace_var", f_trace_var, -1);
2076 rb_define_global_function("untrace_var", f_untrace_var, -1);
2078 rb_vm_register_special_exception(ruby_error_reenter, rb_eFatal, "exception reentered");
2079 rb_vm_register_special_exception(ruby_error_stackfatal, rb_eFatal, "machine stack overflow in critical region");
2081 id_signo = rb_intern_const("signo");
2082 id_status = rb_intern_const("status");