The Ruby Cross Reference

Implementation: mri jruby rubinius
Version: 1.8.7-p374 1.9.1-p431 1.9.2-p381 1.9.3-p547 2.0.0-p481 2.1.0 2.1.1 2.1.2 HEAD
001 /**********************************************************************
002 
003   eval.c -
004 
005   $Author$
006   created at: Thu Jun 10 14:22:17 JST 1993
007 
008   Copyright (C) 1993-2007 Yukihiro Matsumoto
009   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
010   Copyright (C) 2000  Information-technology Promotion Agency, Japan
011 
012 **********************************************************************/
013 
014 #include "eval_intern.h"
015 #include "iseq.h"
016 #include "gc.h"
017 #include "ruby/vm.h"
018 #include "ruby/encoding.h"
019 #include "internal.h"
020 #include "vm_core.h"
021 #include "probes_helper.h"
022 
023 NORETURN(void rb_raise_jump(VALUE));
024 
025 NODE *rb_vm_get_cref(const rb_iseq_t *, const VALUE *);
026 
027 VALUE rb_eLocalJumpError;
028 VALUE rb_eSysStackError;
029 
030 #define exception_error GET_VM()->special_exceptions[ruby_error_reenter]
031 
032 #include "eval_error.c"
033 #include "eval_jump.c"
034 
035 #define CLASS_OR_MODULE_P(obj) \
036     (!SPECIAL_CONST_P(obj) && \
037      (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
038 
039 /* Initializes the Ruby VM and builtin libraries.
040  * @retval 0 if succeeded.
041  * @retval non-zero an error occurred.
042  */
043 int
044 ruby_setup(void)
045 {
046     static int initialized = 0;
047     int state;
048 
049     if (initialized)
050         return 0;
051     initialized = 1;
052 
053     ruby_init_stack((void *)&state);
054     Init_BareVM();
055     Init_heap();
056 
057     PUSH_TAG();
058     if ((state = EXEC_TAG()) == 0) {
059         rb_call_inits();
060         ruby_prog_init();
061         GET_VM()->running = 1;
062     }
063     POP_TAG();
064 
065     return state;
066 }
067 
068 /* Calls ruby_setup() and check error.
069  *
070  * Prints errors and calls exit(3) if an error occurred.
071  */
072 void
073 ruby_init(void)
074 {
075     int state = ruby_setup();
076     if (state) {
077         error_print();
078         exit(EXIT_FAILURE);
079     }
080 }
081 
082 /*! Processes command line arguments and compiles the Ruby source to execute.
083  *
084  * This function does:
085  * \li  Processes the given command line flags and arguments for ruby(1)
086  * \li compiles the source code from the given argument, -e or stdin, and
087  * \li returns the compiled source as an opaque pointer to an internal data structure
088  *
089  * @return an opaque pointer to the compiled source or an internal special value.
090  * @sa ruby_executable_node().
091  */
092 void *
093 ruby_options(int argc, char **argv)
094 {
095     int state;
096     void *volatile iseq = 0;
097 
098     ruby_init_stack((void *)&iseq);
099     PUSH_TAG();
100     if ((state = EXEC_TAG()) == 0) {
101         SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv));
102     }
103     else {
104         rb_clear_trace_func();
105         state = error_handle(state);
106         iseq = (void *)INT2FIX(state);
107     }
108     POP_TAG();
109     return iseq;
110 }
111 
112 static void
113 ruby_finalize_0(void)
114 {
115     PUSH_TAG();
116     if (EXEC_TAG() == 0) {
117         rb_trap_exit();
118     }
119     POP_TAG();
120     rb_exec_end_proc();
121     rb_clear_trace_func();
122 }
123 
124 static void
125 ruby_finalize_1(void)
126 {
127     ruby_sig_finalize();
128     GET_THREAD()->errinfo = Qnil;
129     rb_gc_call_finalizer_at_exit();
130 }
131 
132 /** Runs the VM finalization processes.
133  *
134  * <code>END{}</code> and procs registered by <code>Kernel.#at_exit</code> are
135  * executed here. See the Ruby language spec for more details.
136  *
137  * @note This function is allowed to raise an exception if an error occurred.
138  */
139 void
140 ruby_finalize(void)
141 {
142     ruby_finalize_0();
143     ruby_finalize_1();
144 }
145 
146 /** Destructs the VM.
147  *
148  * Runs the VM finalization processes as well as ruby_finalize(), and frees
149  * resources used by the VM.
150  *
151  * @param ex Default value to the return value.
152  * @return If an error occurred returns a non-zero. If otherwise, returns the
153  *         given ex.
154  * @note This function does not raise any exception.
155  */
156 int
157 ruby_cleanup(volatile int ex)
158 {
159     int state;
160     volatile VALUE errs[2];
161     rb_thread_t *th = GET_THREAD();
162     int nerr;
163 
164     rb_threadptr_interrupt(th);
165     rb_threadptr_check_signal(th);
166     PUSH_TAG();
167     if ((state = EXEC_TAG()) == 0) {
168         SAVE_ROOT_JMPBUF(th, { RUBY_VM_CHECK_INTS(th); });
169     }
170     POP_TAG();
171 
172     errs[1] = th->errinfo;
173     th->safe_level = 0;
174     ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]);
175 
176     PUSH_TAG();
177     if ((state = EXEC_TAG()) == 0) {
178         SAVE_ROOT_JMPBUF(th, ruby_finalize_0());
179     }
180     POP_TAG();
181 
182     /* protect from Thread#raise */
183     th->status = THREAD_KILLED;
184 
185     errs[0] = th->errinfo;
186     PUSH_TAG();
187     if ((state = EXEC_TAG()) == 0) {
188         SAVE_ROOT_JMPBUF(th, rb_thread_terminate_all());
189     }
190     else if (ex == 0) {
191         ex = state;
192     }
193     th->errinfo = errs[1];
194     ex = error_handle(ex);
195     ruby_finalize_1();
196 
197     /* unlock again if finalizer took mutexes. */
198     rb_threadptr_unlock_all_locking_mutexes(GET_THREAD());
199     POP_TAG();
200     rb_thread_stop_timer_thread(1);
201 
202 #if EXIT_SUCCESS != 0 || EXIT_FAILURE != 1
203     switch (ex) {
204 #if EXIT_SUCCESS != 0
205       case 0: ex = EXIT_SUCCESS; break;
206 #endif
207 #if EXIT_FAILURE != 1
208       case 1: ex = EXIT_FAILURE; break;
209 #endif
210     }
211 #endif
212 
213     state = 0;
214     for (nerr = 0; nerr < numberof(errs); ++nerr) {
215         VALUE err = errs[nerr];
216 
217         if (!RTEST(err)) continue;
218 
219         /* th->errinfo contains a NODE while break'ing */
220         if (RB_TYPE_P(err, T_NODE)) continue;
221 
222         if (rb_obj_is_kind_of(err, rb_eSystemExit)) {
223             ex = sysexit_status(err);
224             break;
225         }
226         else if (rb_obj_is_kind_of(err, rb_eSignal)) {
227             VALUE sig = rb_iv_get(err, "signo");
228             state = NUM2INT(sig);
229             break;
230         }
231         else if (ex == EXIT_SUCCESS) {
232             ex = EXIT_FAILURE;
233         }
234     }
235     ruby_vm_destruct(GET_VM());
236     if (state) ruby_default_signal(state);
237 
238     return ex;
239 }
240 
241 static int
242 ruby_exec_internal(void *n)
243 {
244     volatile int state;
245     VALUE iseq = (VALUE)n;
246     rb_thread_t *th = GET_THREAD();
247 
248     if (!n) return 0;
249 
250     PUSH_TAG();
251     if ((state = EXEC_TAG()) == 0) {
252         SAVE_ROOT_JMPBUF(th, {
253             th->base_block = 0;
254             rb_iseq_eval_main(iseq);
255         });
256     }
257     POP_TAG();
258     return state;
259 }
260 
261 /*! Calls ruby_cleanup() and exits the process */
262 void
263 ruby_stop(int ex)
264 {
265     exit(ruby_cleanup(ex));
266 }
267 
268 /*! Checks the return value of ruby_options().
269  * @param n return value of ruby_options().
270  * @param status pointer to the exit status of this process.
271  *
272  * ruby_options() sometimes returns a special value to indicate this process
273  * should immediately exit. This function checks if the case. Also stores the
274  * exit status that the caller have to pass to exit(3) into
275  * <code>*status</code>.
276  *
277  * @retval non-zero if the given opaque pointer is actually a compiled source.
278  * @retval 0 if the given value is such a special value.
279  */
280 int
281 ruby_executable_node(void *n, int *status)
282 {
283     VALUE v = (VALUE)n;
284     int s;
285 
286     switch (v) {
287       case Qtrue:  s = EXIT_SUCCESS; break;
288       case Qfalse: s = EXIT_FAILURE; break;
289       default:
290         if (!FIXNUM_P(v)) return TRUE;
291         s = FIX2INT(v);
292     }
293     if (status) *status = s;
294     return FALSE;
295 }
296 
297 /*! Runs the given compiled source and exits this process.
298  * @retval 0 if successfully run the source
299  * @retval non-zero if an error occurred.
300 */
301 int
302 ruby_run_node(void *n)
303 {
304     int status;
305     if (!ruby_executable_node(n, &status)) {
306         ruby_cleanup(0);
307         return status;
308     }
309     return ruby_cleanup(ruby_exec_node(n));
310 }
311 
312 /*! Runs the given compiled source */
313 int
314 ruby_exec_node(void *n)
315 {
316     ruby_init_stack((void *)&n);
317     return ruby_exec_internal(n);
318 }
319 
320 /*
321  *  call-seq:
322  *     Module.nesting    -> array
323  *
324  *  Returns the list of +Modules+ nested at the point of call.
325  *
326  *     module M1
327  *       module M2
328  *         $a = Module.nesting
329  *       end
330  *     end
331  *     $a           #=> [M1::M2, M1]
332  *     $a[0].name   #=> "M1::M2"
333  */
334 
335 static VALUE
336 rb_mod_nesting(void)
337 {
338     VALUE ary = rb_ary_new();
339     const NODE *cref = rb_vm_cref();
340 
341     while (cref && cref->nd_next) {
342         VALUE klass = cref->nd_clss;
343         if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) &&
344             !NIL_P(klass)) {
345             rb_ary_push(ary, klass);
346         }
347         cref = cref->nd_next;
348     }
349     return ary;
350 }
351 
352 /*
353  *  call-seq:
354  *     Module.constants   -> array
355  *     Module.constants(inherited)   -> array
356  *
357  *  In the first form, returns an array of the names of all
358  *  constants accessible from the point of call.
359  *  This list includes the names of all modules and classes
360  *  defined in the global scope.
361  *
362  *     Module.constants.first(4)
363  *        # => [:ARGF, :ARGV, :ArgumentError, :Array]
364  *
365  *     Module.constants.include?(:SEEK_SET)   # => false
366  *
367  *     class IO
368  *       Module.constants.include?(:SEEK_SET) # => true
369  *     end
370  *
371  *  The second form calls the instance method +constants+.
372  */
373 
374 static VALUE
375 rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
376 {
377     const NODE *cref = rb_vm_cref();
378     VALUE klass;
379     VALUE cbase = 0;
380     void *data = 0;
381 
382     if (argc > 0) {
383         return rb_mod_constants(argc, argv, rb_cModule);
384     }
385 
386     while (cref) {
387         klass = cref->nd_clss;
388         if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) &&
389             !NIL_P(klass)) {
390             data = rb_mod_const_at(cref->nd_clss, data);
391             if (!cbase) {
392                 cbase = klass;
393             }
394         }
395         cref = cref->nd_next;
396     }
397 
398     if (cbase) {
399         data = rb_mod_const_of(cbase, data);
400     }
401     return rb_const_list(data);
402 }
403 
404 void
405 rb_frozen_class_p(VALUE klass)
406 {
407     if (SPECIAL_CONST_P(klass)) {
408       noclass:
409         Check_Type(klass, T_CLASS);
410     }
411     if (OBJ_FROZEN(klass)) {
412         const char *desc;
413 
414         if (FL_TEST(klass, FL_SINGLETON))
415             desc = "object";
416         else {
417             switch (BUILTIN_TYPE(klass)) {
418               case T_MODULE:
419               case T_ICLASS:
420                 desc = "module";
421                 break;
422               case T_CLASS:
423                 desc = "class";
424                 break;
425               default:
426                 goto noclass;
427             }
428         }
429         rb_error_frozen(desc);
430     }
431 }
432 
433 NORETURN(static void rb_longjmp(int, volatile VALUE));
434 
435 static void
436 setup_exception(rb_thread_t *th, int tag, volatile VALUE mesg)
437 {
438     VALUE at;
439     VALUE e;
440     const char *file;
441     volatile int line = 0;
442 
443     if (NIL_P(mesg)) {
444         mesg = th->errinfo;
445         if (INTERNAL_EXCEPTION_P(mesg)) JUMP_TAG(TAG_FATAL);
446     }
447     if (NIL_P(mesg)) {
448         mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
449     }
450 
451     file = rb_sourcefile();
452     if (file) line = rb_sourceline();
453     if (file && !NIL_P(mesg)) {
454         if (mesg == sysstack_error) {
455             at = rb_enc_sprintf(rb_usascii_encoding(), "%s:%d", file, line);
456             at = rb_ary_new3(1, at);
457             rb_iv_set(mesg, "bt", at);
458         }
459         else {
460             at = get_backtrace(mesg);
461             if (NIL_P(at)) {
462                 at = rb_vm_backtrace_object();
463                 if (OBJ_FROZEN(mesg)) {
464                     mesg = rb_obj_dup(mesg);
465                 }
466                 set_backtrace(mesg, at);
467             }
468         }
469     }
470     if (!NIL_P(mesg)) {
471         th->errinfo = mesg;
472     }
473 
474     if (RTEST(ruby_debug) && !NIL_P(e = th->errinfo) &&
475         !rb_obj_is_kind_of(e, rb_eSystemExit)) {
476         int status;
477 
478         PUSH_TAG();
479         if ((status = EXEC_TAG()) == 0) {
480             RB_GC_GUARD(e) = rb_obj_as_string(e);
481             if (file && line) {
482                 warn_printf("Exception `%s' at %s:%d - %"PRIsVALUE"\n",
483                             rb_obj_classname(th->errinfo), file, line, e);
484             }
485             else if (file) {
486                 warn_printf("Exception `%s' at %s - %"PRIsVALUE"\n",
487                             rb_obj_classname(th->errinfo), file, e);
488             }
489             else {
490                 warn_printf("Exception `%s' - %"PRIsVALUE"\n",
491                             rb_obj_classname(th->errinfo), e);
492             }
493         }
494         POP_TAG();
495         if (status == TAG_FATAL && th->errinfo == exception_error) {
496             th->errinfo = mesg;
497         }
498         else if (status) {
499             rb_threadptr_reset_raised(th);
500             JUMP_TAG(status);
501         }
502     }
503 
504     if (rb_threadptr_set_raised(th)) {
505         th->errinfo = exception_error;
506         rb_threadptr_reset_raised(th);
507         JUMP_TAG(TAG_FATAL);
508     }
509 
510     if (tag != TAG_FATAL) {
511         if (RUBY_DTRACE_RAISE_ENABLED()) {
512             RUBY_DTRACE_RAISE(rb_obj_classname(th->errinfo),
513                               rb_sourcefile(),
514                               rb_sourceline());
515         }
516         EXEC_EVENT_HOOK(th, RUBY_EVENT_RAISE, th->cfp->self, 0, 0, mesg);
517     }
518 }
519 
520 static void
521 rb_longjmp(int tag, volatile VALUE mesg)
522 {
523     rb_thread_t *th = GET_THREAD();
524     setup_exception(th, tag, mesg);
525     rb_thread_raised_clear(th);
526     JUMP_TAG(tag);
527 }
528 
529 static VALUE make_exception(int argc, VALUE *argv, int isstr);
530 
531 void
532 rb_exc_raise(VALUE mesg)
533 {
534     if (!NIL_P(mesg)) {
535         mesg = make_exception(1, &mesg, FALSE);
536     }
537     rb_longjmp(TAG_RAISE, mesg);
538 }
539 
540 void
541 rb_exc_fatal(VALUE mesg)
542 {
543     if (!NIL_P(mesg)) {
544         mesg = make_exception(1, &mesg, FALSE);
545     }
546     rb_longjmp(TAG_FATAL, mesg);
547 }
548 
549 void
550 rb_interrupt(void)
551 {
552     rb_raise(rb_eInterrupt, "%s", "");
553 }
554 
555 static VALUE get_errinfo(void);
556 
557 /*
558  *  call-seq:
559  *     raise
560  *     raise(string)
561  *     raise(exception [, string [, array]])
562  *     fail
563  *     fail(string)
564  *     fail(exception [, string [, array]])
565  *
566  *  With no arguments, raises the exception in <code>$!</code> or raises
567  *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
568  *  With a single +String+ argument, raises a
569  *  +RuntimeError+ with the string as a message. Otherwise,
570  *  the first parameter should be the name of an +Exception+
571  *  class (or an object that returns an +Exception+ object when sent
572  *  an +exception+ message). The optional second parameter sets the
573  *  message associated with the exception, and the third parameter is an
574  *  array of callback information. Exceptions are caught by the
575  *  +rescue+ clause of <code>begin...end</code> blocks.
576  *
577  *     raise "Failed to create socket"
578  *     raise ArgumentError, "No parameters", caller
579  */
580 
581 static VALUE
582 rb_f_raise(int argc, VALUE *argv)
583 {
584     VALUE err;
585     if (argc == 0) {
586         err = get_errinfo();
587         if (!NIL_P(err)) {
588             argc = 1;
589             argv = &err;
590         }
591     }
592     rb_raise_jump(rb_make_exception(argc, argv));
593 
594     UNREACHABLE;
595 }
596 
597 static VALUE
598 make_exception(int argc, VALUE *argv, int isstr)
599 {
600     VALUE mesg, exc;
601     ID exception;
602     int n;
603 
604     mesg = Qnil;
605     switch (argc) {
606       case 0:
607         break;
608       case 1:
609         exc = argv[0];
610         if (NIL_P(exc))
611             break;
612         if (isstr) {
613             mesg = rb_check_string_type(exc);
614             if (!NIL_P(mesg)) {
615                 mesg = rb_exc_new3(rb_eRuntimeError, mesg);
616                 break;
617             }
618         }
619         n = 0;
620         goto exception_call;
621 
622       case 2:
623       case 3:
624         exc = argv[0];
625         n = 1;
626       exception_call:
627         if (exc == sysstack_error) return exc;
628         CONST_ID(exception, "exception");
629         mesg = rb_check_funcall(exc, exception, n, argv+1);
630         if (mesg == Qundef) {
631             rb_raise(rb_eTypeError, "exception class/object expected");
632         }
633         break;
634       default:
635         rb_check_arity(argc, 0, 3);
636         break;
637     }
638     if (argc > 0) {
639         if (!rb_obj_is_kind_of(mesg, rb_eException))
640             rb_raise(rb_eTypeError, "exception object expected");
641         if (argc > 2)
642             set_backtrace(mesg, argv[2]);
643     }
644 
645     return mesg;
646 }
647 
648 VALUE
649 rb_make_exception(int argc, VALUE *argv)
650 {
651     return make_exception(argc, argv, TRUE);
652 }
653 
654 void
655 rb_raise_jump(VALUE mesg)
656 {
657     rb_thread_t *th = GET_THREAD();
658     rb_control_frame_t *cfp = th->cfp;
659     VALUE klass = cfp->me->klass;
660     VALUE self = cfp->self;
661     ID mid = cfp->me->called_id;
662 
663     th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp);
664 
665     setup_exception(th, TAG_RAISE, mesg);
666 
667     EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, self, mid, klass, Qnil);
668     rb_thread_raised_clear(th);
669     JUMP_TAG(TAG_RAISE);
670 }
671 
672 void
673 rb_jump_tag(int tag)
674 {
675     JUMP_TAG(tag);
676 }
677 
678 int
679 rb_block_given_p(void)
680 {
681     rb_thread_t *th = GET_THREAD();
682 
683     if (rb_vm_control_frame_block_ptr(th->cfp)) {
684         return TRUE;
685     }
686     else {
687         return FALSE;
688     }
689 }
690 
691 int
692 rb_iterator_p(void)
693 {
694     return rb_block_given_p();
695 }
696 
697 VALUE rb_eThreadError;
698 
699 void
700 rb_need_block(void)
701 {
702     if (!rb_block_given_p()) {
703         rb_vm_localjump_error("no block given", Qnil, 0);
704     }
705 }
706 
707 VALUE
708 rb_rescue2(VALUE (* b_proc) (ANYARGS), VALUE data1,
709            VALUE (* r_proc) (ANYARGS), VALUE data2, ...)
710 {
711     int state;
712     rb_thread_t *th = GET_THREAD();
713     rb_control_frame_t *cfp = th->cfp;
714     volatile VALUE result;
715     volatile VALUE e_info = th->errinfo;
716     va_list args;
717 
718     TH_PUSH_TAG(th);
719     if ((state = TH_EXEC_TAG()) == 0) {
720       retry_entry:
721         result = (*b_proc) (data1);
722     }
723     else {
724         th->cfp = cfp; /* restore */
725 
726         if (state == TAG_RAISE) {
727             int handle = FALSE;
728             VALUE eclass;
729 
730             va_init_list(args, data2);
731             while ((eclass = va_arg(args, VALUE)) != 0) {
732                 if (rb_obj_is_kind_of(th->errinfo, eclass)) {
733                     handle = TRUE;
734                     break;
735                 }
736             }
737             va_end(args);
738 
739             if (handle) {
740                 if (r_proc) {
741                     PUSH_TAG();
742                     if ((state = EXEC_TAG()) == 0) {
743                         result = (*r_proc) (data2, th->errinfo);
744                     }
745                     POP_TAG();
746                     if (state == TAG_RETRY) {
747                         state = 0;
748                         th->errinfo = Qnil;
749                         goto retry_entry;
750                     }
751                 }
752                 else {
753                     result = Qnil;
754                     state = 0;
755                 }
756                 if (state == 0) {
757                     th->errinfo = e_info;
758                 }
759             }
760         }
761     }
762     TH_POP_TAG();
763     if (state)
764         JUMP_TAG(state);
765 
766     return result;
767 }
768 
769 VALUE
770 rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1,
771           VALUE (* r_proc)(ANYARGS), VALUE data2)
772 {
773     return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
774                       (VALUE)0);
775 }
776 
777 VALUE
778 rb_protect(VALUE (* proc) (VALUE), VALUE data, int * state)
779 {
780     volatile VALUE result = Qnil;
781     int status;
782     rb_thread_t *th = GET_THREAD();
783     rb_control_frame_t *cfp = th->cfp;
784     struct rb_vm_protect_tag protect_tag;
785     rb_jmpbuf_t org_jmpbuf;
786 
787     protect_tag.prev = th->protect_tag;
788 
789     TH_PUSH_TAG(th);
790     th->protect_tag = &protect_tag;
791     MEMCPY(&org_jmpbuf, &(th)->root_jmpbuf, rb_jmpbuf_t, 1);
792     if ((status = TH_EXEC_TAG()) == 0) {
793         SAVE_ROOT_JMPBUF(th, result = (*proc) (data));
794     }
795     MEMCPY(&(th)->root_jmpbuf, &org_jmpbuf, rb_jmpbuf_t, 1);
796     th->protect_tag = protect_tag.prev;
797     TH_POP_TAG();
798 
799     if (state) {
800         *state = status;
801     }
802     if (status != 0) {
803         th->cfp = cfp;
804         return Qnil;
805     }
806 
807     return result;
808 }
809 
810 VALUE
811 rb_ensure(VALUE (*b_proc)(ANYARGS), VALUE data1, VALUE (*e_proc)(ANYARGS), VALUE data2)
812 {
813     int state;
814     volatile VALUE result = Qnil;
815     volatile VALUE errinfo;
816     rb_thread_t *const th = GET_THREAD();
817 
818     PUSH_TAG();
819     if ((state = EXEC_TAG()) == 0) {
820         result = (*b_proc) (data1);
821     }
822     POP_TAG();
823     /* TODO: fix me */
824     /* retval = prot_tag ? prot_tag->retval : Qnil; */     /* save retval */
825     errinfo = th->errinfo;
826     (*e_proc) (data2);
827     th->errinfo = errinfo;
828     if (state)
829         JUMP_TAG(state);
830     return result;
831 }
832 
833 static const rb_method_entry_t *
834 method_entry_of_iseq(rb_control_frame_t *cfp, rb_iseq_t *iseq)
835 {
836     rb_thread_t *th = GET_THREAD();
837     rb_control_frame_t *cfp_limit;
838 
839     cfp_limit = (rb_control_frame_t *)(th->stack + th->stack_size);
840     while (cfp_limit > cfp) {
841         if (cfp->iseq == iseq)
842             return cfp->me;
843         cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
844     }
845     return 0;
846 }
847 
848 static ID
849 frame_func_id(rb_control_frame_t *cfp)
850 {
851     const rb_method_entry_t *me_local;
852     rb_iseq_t *iseq = cfp->iseq;
853     if (cfp->me) {
854         return cfp->me->def->original_id;
855     }
856     while (iseq) {
857         if (RUBY_VM_IFUNC_P(iseq)) {
858             NODE *ifunc = (NODE *)iseq;
859             if (ifunc->nd_aid) return ifunc->nd_aid;
860             return idIFUNC;
861         }
862         me_local = method_entry_of_iseq(cfp, iseq);
863         if (me_local) {
864             cfp->me = me_local;
865             return me_local->def->original_id;
866         }
867         if (iseq->defined_method_id) {
868             return iseq->defined_method_id;
869         }
870         if (iseq->local_iseq == iseq) {
871             break;
872         }
873         iseq = iseq->parent_iseq;
874     }
875     return 0;
876 }
877 
878 static ID
879 frame_called_id(rb_control_frame_t *cfp)
880 {
881     const rb_method_entry_t *me_local;
882     rb_iseq_t *iseq = cfp->iseq;
883     if (cfp->me) {
884         return cfp->me->called_id;
885     }
886     while (iseq) {
887         if (RUBY_VM_IFUNC_P(iseq)) {
888             NODE *ifunc = (NODE *)iseq;
889             if (ifunc->nd_aid) return ifunc->nd_aid;
890             return idIFUNC;
891         }
892         me_local = method_entry_of_iseq(cfp, iseq);
893         if (me_local) {
894             cfp->me = me_local;
895             return me_local->called_id;
896         }
897         if (iseq->defined_method_id) {
898             return iseq->defined_method_id;
899         }
900         if (iseq->local_iseq == iseq) {
901             break;
902         }
903         iseq = iseq->parent_iseq;
904     }
905     return 0;
906 }
907 
908 ID
909 rb_frame_this_func(void)
910 {
911     return frame_func_id(GET_THREAD()->cfp);
912 }
913 
914 ID
915 rb_frame_callee(void)
916 {
917     return frame_called_id(GET_THREAD()->cfp);
918 }
919 
920 static rb_control_frame_t *
921 previous_frame(rb_thread_t *th)
922 {
923     rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp);
924     /* check if prev_cfp can be accessible */
925     if ((void *)(th->stack + th->stack_size) == (void *)(prev_cfp)) {
926         return 0;
927     }
928     return prev_cfp;
929 }
930 
931 static ID
932 prev_frame_callee(void)
933 {
934     rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD());
935     if (!prev_cfp) return 0;
936     return frame_called_id(prev_cfp);
937 }
938 
939 static ID
940 prev_frame_func(void)
941 {
942     rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD());
943     if (!prev_cfp) return 0;
944     return frame_func_id(prev_cfp);
945 }
946 
947 void
948 rb_frame_pop(void)
949 {
950     rb_thread_t *th = GET_THREAD();
951     th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp);
952 }
953 
954 /*
955  *  call-seq:
956  *     append_features(mod)   -> mod
957  *
958  *  When this module is included in another, Ruby calls
959  *  <code>append_features</code> in this module, passing it the
960  *  receiving module in _mod_. Ruby's default implementation is
961  *  to add the constants, methods, and module variables of this module
962  *  to _mod_ if this module has not already been added to
963  *  _mod_ or one of its ancestors. See also <code>Module#include</code>.
964  */
965 
966 static VALUE
967 rb_mod_append_features(VALUE module, VALUE include)
968 {
969     if (!CLASS_OR_MODULE_P(include)) {
970         Check_Type(include, T_CLASS);
971     }
972     rb_include_module(include, module);
973 
974     return module;
975 }
976 
977 /*
978  *  call-seq:
979  *     include(module, ...)    -> self
980  *
981  *  Invokes <code>Module.append_features</code> on each parameter in reverse order.
982  */
983 
984 static VALUE
985 rb_mod_include(int argc, VALUE *argv, VALUE module)
986 {
987     int i;
988     ID id_append_features, id_included;
989 
990     CONST_ID(id_append_features, "append_features");
991     CONST_ID(id_included, "included");
992 
993     for (i = 0; i < argc; i++)
994         Check_Type(argv[i], T_MODULE);
995     while (argc--) {
996         rb_funcall(argv[argc], id_append_features, 1, module);
997         rb_funcall(argv[argc], id_included, 1, module);
998     }
999     return module;
1000 }
1001 
1002 /*
1003  *  call-seq:
1004  *     prepend_features(mod)   -> mod
1005  *
1006  *  When this module is prepended in another, Ruby calls
1007  *  <code>prepend_features</code> in this module, passing it the
1008  *  receiving module in _mod_. Ruby's default implementation is
1009  *  to overlay the constants, methods, and module variables of this module
1010  *  to _mod_ if this module has not already been added to
1011  *  _mod_ or one of its ancestors. See also <code>Module#prepend</code>.
1012  */
1013 
1014 static VALUE
1015 rb_mod_prepend_features(VALUE module, VALUE prepend)
1016 {
1017     if (!CLASS_OR_MODULE_P(prepend)) {
1018         Check_Type(prepend, T_CLASS);
1019     }
1020     rb_prepend_module(prepend, module);
1021 
1022     return module;
1023 }
1024 
1025 /*
1026  *  call-seq:
1027  *     prepend(module, ...)    -> self
1028  *
1029  *  Invokes <code>Module.prepend_features</code> on each parameter in reverse order.
1030  */
1031 
1032 static VALUE
1033 rb_mod_prepend(int argc, VALUE *argv, VALUE module)
1034 {
1035     int i;
1036     ID id_prepend_features, id_prepended;
1037 
1038     CONST_ID(id_prepend_features, "prepend_features");
1039     CONST_ID(id_prepended, "prepended");
1040     for (i = 0; i < argc; i++)
1041         Check_Type(argv[i], T_MODULE);
1042     while (argc--) {
1043         rb_funcall(argv[argc], id_prepend_features, 1, module);
1044         rb_funcall(argv[argc], id_prepended, 1, module);
1045     }
1046     return module;
1047 }
1048 
1049 static void
1050 warn_refinements_once()
1051 {
1052     static int warned = 0;
1053 
1054     if (warned)
1055         return;
1056     rb_warn("Refinements are experimental, and the behavior may change in future versions of Ruby!");
1057     warned = 1;
1058 }
1059 
1060 static VALUE
1061 hidden_identity_hash_new()
1062 {
1063     VALUE hash = rb_hash_new();
1064 
1065     rb_funcall(hash, rb_intern("compare_by_identity"), 0);
1066     RBASIC_CLEAR_CLASS(hash); /* hide from ObjectSpace */
1067     return hash;
1068 }
1069 
1070 void
1071 rb_using_refinement(NODE *cref, VALUE klass, VALUE module)
1072 {
1073     VALUE iclass, c, superclass = klass;
1074 
1075     Check_Type(klass, T_CLASS);
1076     Check_Type(module, T_MODULE);
1077     if (NIL_P(cref->nd_refinements)) {
1078         cref->nd_refinements = hidden_identity_hash_new();
1079     }
1080     else {
1081         if (cref->flags & NODE_FL_CREF_OMOD_SHARED) {
1082             cref->nd_refinements = rb_hash_dup(cref->nd_refinements);
1083             cref->flags &= ~NODE_FL_CREF_OMOD_SHARED;
1084         }
1085         if (!NIL_P(c = rb_hash_lookup(cref->nd_refinements, klass))) {
1086             superclass = c;
1087             while (c && RB_TYPE_P(c, T_ICLASS)) {
1088                 if (RBASIC(c)->klass == module) {
1089                     /* already used refinement */
1090                     return;
1091                 }
1092                 c = RCLASS_SUPER(c);
1093             }
1094         }
1095     }
1096     FL_SET(module, RMODULE_IS_OVERLAID);
1097     c = iclass = rb_include_class_new(module, superclass);
1098     RCLASS_REFINED_CLASS(c) = klass;
1099 
1100     RCLASS_M_TBL(OBJ_WB_UNPROTECT(c)) = RCLASS_M_TBL(OBJ_WB_UNPROTECT(module));
1101 
1102     module = RCLASS_SUPER(module);
1103     while (module && module != klass) {
1104         FL_SET(module, RMODULE_IS_OVERLAID);
1105         c = RCLASS_SET_SUPER(c, rb_include_class_new(module, RCLASS_SUPER(c)));
1106         RCLASS_REFINED_CLASS(c) = klass;
1107         module = RCLASS_SUPER(module);
1108     }
1109     rb_hash_aset(cref->nd_refinements, klass, iclass);
1110 }
1111 
1112 static int
1113 using_refinement(VALUE klass, VALUE module, VALUE arg)
1114 {
1115     NODE *cref = (NODE *) arg;
1116 
1117     rb_using_refinement(cref, klass, module);
1118     return ST_CONTINUE;
1119 }
1120 
1121 static void
1122 using_module_recursive(NODE *cref, VALUE klass)
1123 {
1124     ID id_refinements;
1125     VALUE super, module, refinements;
1126 
1127     super = RCLASS_SUPER(klass);
1128     if (super) {
1129         using_module_recursive(cref, super);
1130     }
1131     switch (BUILTIN_TYPE(klass)) {
1132     case T_MODULE:
1133         module = klass;
1134         break;
1135 
1136     case T_ICLASS:
1137         module = RBASIC(klass)->klass;
1138         break;
1139 
1140     default:
1141         rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)",
1142                  rb_obj_classname(klass));
1143         break;
1144     }
1145     CONST_ID(id_refinements, "__refinements__");
1146     refinements = rb_attr_get(module, id_refinements);
1147     if (NIL_P(refinements)) return;
1148     rb_hash_foreach(refinements, using_refinement, (VALUE) cref);
1149 }
1150 
1151 void
1152 rb_using_module(NODE *cref, VALUE module)
1153 {
1154     Check_Type(module, T_MODULE);
1155     using_module_recursive(cref, module);
1156 }
1157 
1158 VALUE rb_refinement_module_get_refined_class(VALUE module)
1159 {
1160     ID id_refined_class;
1161 
1162     CONST_ID(id_refined_class, "__refined_class__");
1163     return rb_attr_get(module, id_refined_class);
1164 }
1165 
1166 static void
1167 add_activated_refinement(VALUE activated_refinements,
1168                          VALUE klass, VALUE refinement)
1169 {
1170     VALUE iclass, c, superclass = klass;
1171 
1172     if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) {
1173         superclass = c;
1174         while (c && RB_TYPE_P(c, T_ICLASS)) {
1175             if (RBASIC(c)->klass == refinement) {
1176                 /* already used refinement */
1177                 return;
1178             }
1179             c = RCLASS_SUPER(c);
1180         }
1181     }
1182     FL_SET(refinement, RMODULE_IS_OVERLAID);
1183     c = iclass = rb_include_class_new(refinement, superclass);
1184     RCLASS_REFINED_CLASS(c) = klass;
1185     refinement = RCLASS_SUPER(refinement);
1186     while (refinement) {
1187         FL_SET(refinement, RMODULE_IS_OVERLAID);
1188         c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c)));
1189         RCLASS_REFINED_CLASS(c) = klass;
1190         refinement = RCLASS_SUPER(refinement);
1191     }
1192     rb_hash_aset(activated_refinements, klass, iclass);
1193 }
1194 
1195 VALUE rb_yield_refine_block(VALUE refinement, VALUE refinements);
1196 
1197 /*
1198  *  call-seq:
1199  *     refine(klass) { block }   -> module
1200  *
1201  *  Refine <i>klass</i> in the receiver.
1202  *
1203  *  Returns an overlaid module.
1204  */
1205 
1206 static VALUE
1207 rb_mod_refine(VALUE module, VALUE klass)
1208 {
1209     VALUE refinement;
1210     ID id_refinements, id_activated_refinements,
1211        id_refined_class, id_defined_at;
1212     VALUE refinements, activated_refinements;
1213     rb_thread_t *th = GET_THREAD();
1214     rb_block_t *block = rb_vm_control_frame_block_ptr(th->cfp);
1215 
1216     warn_refinements_once();
1217     if (!block) {
1218         rb_raise(rb_eArgError, "no block given");
1219     }
1220     if (block->proc) {
1221         rb_raise(rb_eArgError,
1222                  "can't pass a Proc as a block to Module#refine");
1223     }
1224     Check_Type(klass, T_CLASS);
1225     CONST_ID(id_refinements, "__refinements__");
1226     refinements = rb_attr_get(module, id_refinements);
1227     if (NIL_P(refinements)) {
1228         refinements = hidden_identity_hash_new();
1229         rb_ivar_set(module, id_refinements, refinements);
1230     }
1231     CONST_ID(id_activated_refinements, "__activated_refinements__");
1232     activated_refinements = rb_attr_get(module, id_activated_refinements);
1233     if (NIL_P(activated_refinements)) {
1234         activated_refinements = hidden_identity_hash_new();
1235         rb_ivar_set(module, id_activated_refinements,
1236                     activated_refinements);
1237     }
1238     refinement = rb_hash_lookup(refinements, klass);
1239     if (NIL_P(refinement)) {
1240         refinement = rb_module_new();
1241         RCLASS_SET_SUPER(refinement, klass);
1242         FL_SET(refinement, RMODULE_IS_REFINEMENT);
1243         CONST_ID(id_refined_class, "__refined_class__");
1244         rb_ivar_set(refinement, id_refined_class, klass);
1245         CONST_ID(id_defined_at, "__defined_at__");
1246         rb_ivar_set(refinement, id_defined_at, module);
1247         rb_hash_aset(refinements, klass, refinement);
1248         add_activated_refinement(activated_refinements, klass, refinement);
1249     }
1250     rb_yield_refine_block(refinement, activated_refinements);
1251     return refinement;
1252 }
1253 
1254 /*
1255  *  call-seq:
1256  *     using(module)    -> self
1257  *
1258  *  Import class refinements from <i>module</i> into the current class or
1259  *  module definition.
1260  */
1261 
1262 static VALUE
1263 mod_using(VALUE self, VALUE module)
1264 {
1265     NODE *cref = rb_vm_cref();
1266     rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD());
1267 
1268     warn_refinements_once();
1269     if (prev_frame_func()) {
1270         rb_raise(rb_eRuntimeError,
1271                  "Module#using is not permitted in methods");
1272     }
1273     if (prev_cfp && prev_cfp->self != self) {
1274         rb_raise(rb_eRuntimeError, "Module#using is not called on self");
1275     }
1276     Check_Type(module, T_MODULE);
1277     rb_using_module(cref, module);
1278     rb_clear_cache();
1279     return self;
1280 }
1281 
1282 void
1283 rb_obj_call_init(VALUE obj, int argc, VALUE *argv)
1284 {
1285     PASS_PASSED_BLOCK();
1286     rb_funcall2(obj, idInitialize, argc, argv);
1287 }
1288 
1289 void
1290 rb_extend_object(VALUE obj, VALUE module)
1291 {
1292     rb_include_module(rb_singleton_class(obj), module);
1293 }
1294 
1295 /*
1296  *  call-seq:
1297  *     extend_object(obj)    -> obj
1298  *
1299  *  Extends the specified object by adding this module's constants and
1300  *  methods (which are added as singleton methods). This is the callback
1301  *  method used by <code>Object#extend</code>.
1302  *
1303  *     module Picky
1304  *       def Picky.extend_object(o)
1305  *         if String === o
1306  *           puts "Can't add Picky to a String"
1307  *         else
1308  *           puts "Picky added to #{o.class}"
1309  *           super
1310  *         end
1311  *       end
1312  *     end
1313  *     (s = Array.new).extend Picky  # Call Object.extend
1314  *     (s = "quick brown fox").extend Picky
1315  *
1316  *  <em>produces:</em>
1317  *
1318  *     Picky added to Array
1319  *     Can't add Picky to a String
1320  */
1321 
1322 static VALUE
1323 rb_mod_extend_object(VALUE mod, VALUE obj)
1324 {
1325     rb_extend_object(obj, mod);
1326     return obj;
1327 }
1328 
1329 /*
1330  *  call-seq:
1331  *     obj.extend(module, ...)    -> obj
1332  *
1333  *  Adds to _obj_ the instance methods from each module given as a
1334  *  parameter.
1335  *
1336  *     module Mod
1337  *       def hello
1338  *         "Hello from Mod.\n"
1339  *       end
1340  *     end
1341  *
1342  *     class Klass
1343  *       def hello
1344  *         "Hello from Klass.\n"
1345  *       end
1346  *     end
1347  *
1348  *     k = Klass.new
1349  *     k.hello         #=> "Hello from Klass.\n"
1350  *     k.extend(Mod)   #=> #<Klass:0x401b3bc8>
1351  *     k.hello         #=> "Hello from Mod.\n"
1352  */
1353 
1354 static VALUE
1355 rb_obj_extend(int argc, VALUE *argv, VALUE obj)
1356 {
1357     int i;
1358     ID id_extend_object, id_extended;
1359 
1360     CONST_ID(id_extend_object, "extend_object");
1361     CONST_ID(id_extended, "extended");
1362 
1363     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1364     for (i = 0; i < argc; i++)
1365         Check_Type(argv[i], T_MODULE);
1366     while (argc--) {
1367         rb_funcall(argv[argc], id_extend_object, 1, obj);
1368         rb_funcall(argv[argc], id_extended, 1, obj);
1369     }
1370     return obj;
1371 }
1372 
1373 /*
1374  *  call-seq:
1375  *     include(module, ...)   -> self
1376  *
1377  *  Invokes <code>Module.append_features</code>
1378  *  on each parameter in turn. Effectively adds the methods and constants
1379  *  in each module to the receiver.
1380  */
1381 
1382 static VALUE
1383 top_include(int argc, VALUE *argv, VALUE self)
1384 {
1385     rb_thread_t *th = GET_THREAD();
1386 
1387     if (th->top_wrapper) {
1388         rb_warning("main.include in the wrapped load is effective only in wrapper module");
1389         return rb_mod_include(argc, argv, th->top_wrapper);
1390     }
1391     return rb_mod_include(argc, argv, rb_cObject);
1392 }
1393 
1394 /*
1395  *  call-seq:
1396  *     using(module)    -> self
1397  *
1398  *  Import class refinements from <i>module</i> into the scope where
1399  *  <code>using</code> is called.
1400  */
1401 
1402 static VALUE
1403 top_using(VALUE self, VALUE module)
1404 {
1405     NODE *cref = rb_vm_cref();
1406     rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD());
1407 
1408     warn_refinements_once();
1409     if (cref->nd_next || (prev_cfp && prev_cfp->me)) {
1410         rb_raise(rb_eRuntimeError,
1411                  "main.using is permitted only at toplevel");
1412     }
1413     Check_Type(module, T_MODULE);
1414     rb_using_module(cref, module);
1415     rb_clear_cache();
1416     return self;
1417 }
1418 
1419 static VALUE *
1420 errinfo_place(rb_thread_t *th)
1421 {
1422     rb_control_frame_t *cfp = th->cfp;
1423     rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(th);
1424 
1425     while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) {
1426         if (RUBY_VM_NORMAL_ISEQ_P(cfp->iseq)) {
1427             if (cfp->iseq->type == ISEQ_TYPE_RESCUE) {
1428                 return &cfp->ep[-2];
1429             }
1430             else if (cfp->iseq->type == ISEQ_TYPE_ENSURE &&
1431                      !RB_TYPE_P(cfp->ep[-2], T_NODE) &&
1432                      !FIXNUM_P(cfp->ep[-2])) {
1433                 return &cfp->ep[-2];
1434             }
1435         }
1436         cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1437     }
1438     return 0;
1439 }
1440 
1441 static VALUE
1442 get_thread_errinfo(rb_thread_t *th)
1443 {
1444     VALUE *ptr = errinfo_place(th);
1445     if (ptr) {
1446         return *ptr;
1447     }
1448     else {
1449         return th->errinfo;
1450     }
1451 }
1452 
1453 static VALUE
1454 get_errinfo(void)
1455 {
1456     return get_thread_errinfo(GET_THREAD());
1457 }
1458 
1459 static VALUE
1460 errinfo_getter(ID id)
1461 {
1462     return get_errinfo();
1463 }
1464 
1465 #if 0
1466 static void
1467 errinfo_setter(VALUE val, ID id, VALUE *var)
1468 {
1469     if (!NIL_P(val) && !rb_obj_is_kind_of(val, rb_eException)) {
1470         rb_raise(rb_eTypeError, "assigning non-exception to $!");
1471     }
1472     else {
1473         VALUE *ptr = errinfo_place(GET_THREAD());
1474         if (ptr) {
1475             *ptr = val;
1476         }
1477         else {
1478             rb_raise(rb_eRuntimeError, "errinfo_setter: not in rescue clause.");
1479         }
1480     }
1481 }
1482 #endif
1483 
1484 VALUE
1485 rb_errinfo(void)
1486 {
1487     rb_thread_t *th = GET_THREAD();
1488     return th->errinfo;
1489 }
1490 
1491 void
1492 rb_set_errinfo(VALUE err)
1493 {
1494     if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) {
1495         rb_raise(rb_eTypeError, "assigning non-exception to $!");
1496     }
1497     GET_THREAD()->errinfo = err;
1498 }
1499 
1500 VALUE
1501 rb_rubylevel_errinfo(void)
1502 {
1503     return get_errinfo();
1504 }
1505 
1506 static VALUE
1507 errat_getter(ID id)
1508 {
1509     VALUE err = get_errinfo();
1510     if (!NIL_P(err)) {
1511         return get_backtrace(err);
1512     }
1513     else {
1514         return Qnil;
1515     }
1516 }
1517 
1518 static void
1519 errat_setter(VALUE val, ID id, VALUE *var)
1520 {
1521     VALUE err = get_errinfo();
1522     if (NIL_P(err)) {
1523         rb_raise(rb_eArgError, "$! not set");
1524     }
1525     set_backtrace(err, val);
1526 }
1527 
1528 /*
1529  *  call-seq:
1530  *     __method__         -> symbol
1531  *
1532  *  Returns the name at the definition of the current method as a
1533  *  Symbol.
1534  *  If called outside of a method, it returns <code>nil</code>.
1535  *
1536  */
1537 
1538 static VALUE
1539 rb_f_method_name(void)
1540 {
1541     ID fname = prev_frame_func(); /* need *method* ID */
1542 
1543     if (fname) {
1544         return ID2SYM(fname);
1545     }
1546     else {
1547         return Qnil;
1548     }
1549 }
1550 
1551 /*
1552  *  call-seq:
1553  *     __callee__         -> symbol
1554  *
1555  *  Returns the called name of the current method as a Symbol.
1556  *  If called outside of a method, it returns <code>nil</code>.
1557  *
1558  */
1559 
1560 static VALUE
1561 rb_f_callee_name(void)
1562 {
1563     ID fname = prev_frame_callee(); /* need *callee* ID */
1564 
1565     if (fname) {
1566         return ID2SYM(fname);
1567     }
1568     else {
1569         return Qnil;
1570     }
1571 }
1572 
1573 /*
1574  *  call-seq:
1575  *     __dir__         -> string
1576  *
1577  *  Returns the canonicalized absolute path of the directory of the file from
1578  *  which this method is called. It means symlinks in the path is resolved.
1579  *  If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>.
1580  *  The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>.
1581  *
1582  */
1583 static VALUE
1584 f_current_dirname(void)
1585 {
1586     VALUE base = rb_current_realfilepath();
1587     if (NIL_P(base)) {
1588         return Qnil;
1589     }
1590     base = rb_file_dirname(base);
1591     return base;
1592 }
1593 
1594 void
1595 Init_eval(void)
1596 {
1597     rb_define_virtual_variable("$@", errat_getter, errat_setter);
1598     rb_define_virtual_variable("$!", errinfo_getter, 0);
1599 
1600     rb_define_global_function("raise", rb_f_raise, -1);
1601     rb_define_global_function("fail", rb_f_raise, -1);
1602 
1603     rb_define_global_function("global_variables", rb_f_global_variables, 0);    /* in variable.c */
1604 
1605     rb_define_global_function("__method__", rb_f_method_name, 0);
1606     rb_define_global_function("__callee__", rb_f_callee_name, 0);
1607     rb_define_global_function("__dir__", f_current_dirname, 0);
1608 
1609     rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
1610     rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
1611     rb_define_private_method(rb_cModule, "include", rb_mod_include, -1);
1612     rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1);
1613     rb_define_private_method(rb_cModule, "prepend", rb_mod_prepend, -1);
1614     rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1);
1615     rb_define_private_method(rb_cModule, "using", mod_using, 1);
1616     rb_undef_method(rb_cClass, "refine");
1617 
1618     rb_undef_method(rb_cClass, "module_function");
1619 
1620     Init_vm_eval();
1621     Init_eval_method();
1622 
1623     rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
1624     rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1);
1625 
1626     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
1627                              "include", top_include, -1);
1628     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
1629                              "using", top_using, 1);
1630 
1631     rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
1632 
1633     rb_define_global_function("trace_var", rb_f_trace_var, -1); /* in variable.c */
1634     rb_define_global_function("untrace_var", rb_f_untrace_var, -1);     /* in variable.c */
1635 
1636     exception_error = rb_exc_new3(rb_eFatal,
1637                                   rb_obj_freeze(rb_str_new2("exception reentered")));
1638     OBJ_TAINT(exception_error);
1639     OBJ_FREEZE(exception_error);
1640 }