Ruby  2.0.0p195(2013-05-14revision40734)
vm_eval.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  vm_eval.c -
4 
5  $Author: nagachika $
6  created at: Sat May 24 16:02:32 JST 2008
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9  Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10  Copyright (C) 2000 Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 static inline VALUE method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status);
15 static inline VALUE vm_yield_with_cref(rb_thread_t *th, int argc, const VALUE *argv, const NODE *cref);
16 static inline VALUE vm_yield(rb_thread_t *th, int argc, const VALUE *argv);
17 static NODE *vm_cref_push(rb_thread_t *th, VALUE klass, int noex, rb_block_t *blockptr);
18 static VALUE vm_exec(rb_thread_t *th);
19 static void vm_set_eval_stack(rb_thread_t * th, VALUE iseqval, const NODE *cref, rb_block_t *base_block);
21 
22 /* vm_backtrace.c */
23 VALUE vm_backtrace_str_ary(rb_thread_t *th, int lev, int n);
24 
25 typedef enum call_type {
30 } call_type;
31 
32 static VALUE send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope);
33 
34 static VALUE vm_call0_body(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv);
35 
36 static VALUE
37 vm_call0(rb_thread_t* th, VALUE recv, VALUE id, int argc, const VALUE *argv,
38  const rb_method_entry_t *me, VALUE defined_class)
39 {
40  rb_call_info_t ci_entry, *ci = &ci_entry;
41 
42  ci->flag = 0;
43  ci->mid = id;
44  ci->recv = recv;
45  ci->defined_class = defined_class;
46  ci->argc = argc;
47  ci->me = me;
48 
49  return vm_call0_body(th, ci, argv);
50 }
51 
52 #if OPT_CALL_CFUNC_WITHOUT_FRAME
53 static VALUE
55 {
56  VALUE val;
57 
59  EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, ci->recv, ci->mid, ci->defined_class, Qnil);
60  {
61  rb_control_frame_t *reg_cfp = th->cfp;
62  const rb_method_entry_t *me = ci->me;
63  const rb_method_cfunc_t *cfunc = &me->def->body.cfunc;
64  int len = cfunc->argc;
65 
66  if (len >= 0) rb_check_arity(ci->argc, len, len);
67 
68  th->passed_ci = ci;
69  ci->aux.inc_sp = 0;
70  VM_PROFILE_UP(2);
71  val = (*cfunc->invoker)(cfunc->func, ci, argv);
72 
73  if (reg_cfp == th->cfp) {
74  if (UNLIKELY(th->passed_ci != ci)) {
75  rb_bug("vm_call0_cfunc: passed_ci error (ci: %p, passed_ci: %p)", ci, th->passed_ci);
76  }
77  th->passed_ci = 0;
78  }
79  else {
80  if (reg_cfp != th->cfp + 1) {
81  rb_bug("vm_call0_cfunc: cfp consistency error");
82  }
83  VM_PROFILE_UP(3);
84  vm_pop_frame(th);
85  }
86  }
87  EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, ci->recv, ci->mid, ci->defined_class, val);
89 
90  return val;
91 }
92 #else
93 static VALUE
95 {
96  VALUE val;
97  const rb_method_entry_t *me = ci->me;
98  const rb_method_cfunc_t *cfunc = &me->def->body.cfunc;
99  int len = cfunc->argc;
100  VALUE recv = ci->recv;
101  VALUE defined_class = ci->defined_class;
102  int argc = ci->argc;
103  ID mid = ci->mid;
104  rb_block_t *blockptr = ci->blockptr;
105 
106  RUBY_DTRACE_CMETHOD_ENTRY_HOOK(th, defined_class, mid);
107  EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, recv, mid, defined_class, Qnil);
108  {
109  rb_control_frame_t *reg_cfp = th->cfp;
110 
111  vm_push_frame(th, 0, VM_FRAME_MAGIC_CFUNC, recv, defined_class,
112  VM_ENVVAL_BLOCK_PTR(blockptr), 0, reg_cfp->sp, 1, me);
113 
114  if (len >= 0) rb_check_arity(argc, len, len);
115 
116  VM_PROFILE_UP(2);
117  val = (*cfunc->invoker)(cfunc->func, recv, argc, argv);
118 
119  if (UNLIKELY(reg_cfp != th->cfp + 1)) {
120  rb_bug("vm_call0_cfunc_with_frame: cfp consistency error");
121  }
122  VM_PROFILE_UP(3);
123  vm_pop_frame(th);
124  }
125  EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, recv, mid, defined_class, val);
126  RUBY_DTRACE_CMETHOD_RETURN_HOOK(th, defined_class, mid);
127 
128  return val;
129 }
130 
131 static VALUE
133 {
134  return vm_call0_cfunc_with_frame(th, ci, argv);
135 }
136 #endif
137 
138 /* `ci' should point temporal value (on stack value) */
139 static VALUE
141 {
142  VALUE ret;
143 
144  if (!ci->me->def) return Qnil;
145 
146  if (th->passed_block) {
147  ci->blockptr = (rb_block_t *)th->passed_block;
148  th->passed_block = 0;
149  }
150  else {
151  ci->blockptr = 0;
152  }
153 
154  again:
155  switch (ci->me->def->type) {
156  case VM_METHOD_TYPE_ISEQ:
157  {
158  rb_control_frame_t *reg_cfp = th->cfp;
159  int i;
160 
161  CHECK_VM_STACK_OVERFLOW(reg_cfp, ci->argc + 1);
162 
163  *reg_cfp->sp++ = ci->recv;
164  for (i = 0; i < ci->argc; i++) {
165  *reg_cfp->sp++ = argv[i];
166  }
167 
168  vm_call_iseq_setup(th, reg_cfp, ci);
169  th->cfp->flag |= VM_FRAME_FLAG_FINISH;
170  return vm_exec(th); /* CHECK_INTS in this function */
171  }
174  ret = vm_call0_cfunc(th, ci, argv);
175  goto success;
177  rb_check_arity(ci->argc, 1, 1);
178  ret = rb_ivar_set(ci->recv, ci->me->def->body.attr.id, argv[0]);
179  goto success;
180  case VM_METHOD_TYPE_IVAR:
181  rb_check_arity(ci->argc, 0, 0);
182  ret = rb_attr_get(ci->recv, ci->me->def->body.attr.id);
183  goto success;
185  ret = vm_call_bmethod_body(th, ci, argv);
186  goto success;
189  {
190  if (ci->me->def->type == VM_METHOD_TYPE_REFINED &&
191  ci->me->def->body.orig_me) {
192  ci->me = ci->me->def->body.orig_me;
193  goto again;
194  }
195 
197 
198  if (!ci->defined_class || !(ci->me = rb_method_entry(ci->defined_class, ci->mid, &ci->defined_class))) {
199  ret = method_missing(ci->recv, ci->mid, ci->argc, argv, NOEX_SUPER);
200  goto success;
201  }
202  RUBY_VM_CHECK_INTS(th);
203  if (!ci->me->def) return Qnil;
204  goto again;
205  }
207  {
208  VALUE new_args = rb_ary_new4(ci->argc, argv);
209 
210  RB_GC_GUARD(new_args);
211  rb_ary_unshift(new_args, ID2SYM(ci->mid));
212  th->passed_block = ci->blockptr;
213  return rb_funcall2(ci->recv, idMethodMissing, ci->argc+1, RARRAY_PTR(new_args));
214  }
216  switch (ci->me->def->body.optimize_type) {
217  case OPTIMIZED_METHOD_TYPE_SEND:
218  ret = send_internal(ci->argc, argv, ci->recv, CALL_FCALL);
219  goto success;
220  case OPTIMIZED_METHOD_TYPE_CALL:
221  {
222  rb_proc_t *proc;
223  GetProcPtr(ci->recv, proc);
224  ret = rb_vm_invoke_proc(th, proc, ci->argc, argv, ci->blockptr);
225  goto success;
226  }
227  default:
228  rb_bug("vm_call0: unsupported optimized method type (%d)", ci->me->def->body.optimize_type);
229  }
230  break;
232  break;
233  }
234  rb_bug("vm_call0: unsupported method type (%d)", ci->me->def->type);
235  return Qundef;
236 
237  success:
238  RUBY_VM_CHECK_INTS(th);
239  return ret;
240 }
241 
242 VALUE
243 rb_vm_call(rb_thread_t *th, VALUE recv, VALUE id, int argc, const VALUE *argv,
244  const rb_method_entry_t *me, VALUE defined_class)
245 {
246  return vm_call0(th, recv, id, argc, argv, me, defined_class);
247 }
248 
249 static inline VALUE
250 vm_call_super(rb_thread_t *th, int argc, const VALUE *argv)
251 {
252  VALUE recv = th->cfp->self;
253  VALUE klass;
254  ID id;
255  rb_method_entry_t *me;
256  rb_control_frame_t *cfp = th->cfp;
257 
258  if (cfp->iseq || NIL_P(cfp->klass)) {
259  rb_bug("vm_call_super: should not be reached");
260  }
261 
262  klass = RCLASS_SUPER(cfp->klass);
263  id = cfp->me->def->original_id;
264  me = rb_method_entry(klass, id, &klass);
265  if (!me) {
266  return method_missing(recv, id, argc, argv, NOEX_SUPER);
267  }
268 
269  return vm_call0(th, recv, id, argc, argv, me, klass);
270 }
271 
272 VALUE
273 rb_call_super(int argc, const VALUE *argv)
274 {
276  return vm_call_super(GET_THREAD(), argc, argv);
277 }
278 
279 static inline void
281 {
282  rb_thread_t *th = GET_THREAD();
283 
287  }
288 }
289 
290 static inline rb_method_entry_t *
291  rb_search_method_entry(VALUE recv, ID mid, VALUE *defined_class_ptr);
292 static inline int rb_method_call_status(rb_thread_t *th, const rb_method_entry_t *me, call_type scope, VALUE self);
293 #define NOEX_OK NOEX_NOSUPER
294 
310 static inline VALUE
311 rb_call0(VALUE recv, ID mid, int argc, const VALUE *argv,
312  call_type scope, VALUE self)
313 {
314  VALUE defined_class;
315  rb_method_entry_t *me =
316  rb_search_method_entry(recv, mid, &defined_class);
317  rb_thread_t *th = GET_THREAD();
318  int call_status = rb_method_call_status(th, me, scope, self);
319 
320  if (call_status != NOEX_OK) {
321  return method_missing(recv, mid, argc, argv, call_status);
322  }
323  stack_check();
324  return vm_call0(th, recv, mid, argc, argv, me, defined_class);
325 }
326 
330  int argc;
332 };
333 
334 static VALUE
336 {
337  VALUE new_args = rb_ary_new4(args->argc, args->argv);
338 
339  RB_GC_GUARD(new_args);
340  rb_ary_unshift(new_args, args->sym);
341  return rb_funcall2(args->recv, idMethodMissing,
342  args->argc+1, RARRAY_PTR(new_args));
343 }
344 
345 static VALUE
347 {
348  if (rb_respond_to(args->recv, SYM2ID(args->sym))) {
349  rb_exc_raise(e);
350  }
351  return Qundef;
352 }
353 
354 static int
356 {
357  VALUE defined_class;
358  const rb_method_entry_t *me = rb_method_entry(klass, idRespond_to, &defined_class);
359 
360  if (me && !(me->flag & NOEX_BASIC)) {
361  const rb_block_t *passed_block = th->passed_block;
362  VALUE args[2], result;
363  int arity = rb_method_entry_arity(me);
364 
365  if (arity > 2)
366  rb_raise(rb_eArgError, "respond_to? must accept 1 or 2 arguments (requires %d)", arity);
367 
368  if (arity < 1) arity = 2;
369 
370  args[0] = ID2SYM(mid);
371  args[1] = Qtrue;
372  result = vm_call0(th, recv, idRespond_to, arity, args, me, defined_class);
373  th->passed_block = passed_block;
374  if (!RTEST(result)) {
375  return FALSE;
376  }
377  }
378  return TRUE;
379 }
380 
381 static int
383 {
384  return rb_method_call_status(th, me, CALL_FCALL, th->cfp->self) == NOEX_OK;
385 }
386 
387 static VALUE
388 check_funcall_missing(rb_thread_t *th, VALUE klass, VALUE recv, ID mid, int argc, VALUE *argv)
389 {
390  if (rb_method_basic_definition_p(klass, idMethodMissing)) {
391  return Qundef;
392  }
393  else {
394  struct rescue_funcall_args args;
395 
396  th->method_missing_reason = 0;
397  args.recv = recv;
398  args.sym = ID2SYM(mid);
399  args.argc = argc;
400  args.argv = argv;
401  return rb_rescue2(check_funcall_exec, (VALUE)&args,
402  check_funcall_failed, (VALUE)&args,
404  }
405 }
406 
407 VALUE
409 {
410  VALUE klass = CLASS_OF(recv);
411  const rb_method_entry_t *me;
412  rb_thread_t *th = GET_THREAD();
413  VALUE defined_class;
414 
415  if (!check_funcall_respond_to(th, klass, recv, mid))
416  return Qundef;
417 
418  me = rb_search_method_entry(recv, mid, &defined_class);
419  if (check_funcall_callable(th, me) != NOEX_OK) {
420  return check_funcall_missing(th, klass, recv, mid, argc, argv);
421  }
422  stack_check();
423  return vm_call0(th, recv, mid, argc, argv, me, defined_class);
424 }
425 
426 VALUE
429 {
430  VALUE klass = CLASS_OF(recv);
431  const rb_method_entry_t *me;
432  rb_thread_t *th = GET_THREAD();
433  VALUE defined_class;
434 
435  if (!check_funcall_respond_to(th, klass, recv, mid))
436  return Qundef;
437 
438  me = rb_search_method_entry(recv, mid, &defined_class);
439  if (check_funcall_callable(th, me) != NOEX_OK) {
440  (*hook)(FALSE, recv, mid, argc, argv, arg);
441  return check_funcall_missing(th, klass, recv, mid, argc, argv);
442  }
443  stack_check();
444  (*hook)(TRUE, recv, mid, argc, argv, arg);
445  return vm_call0(th, recv, mid, argc, argv, me, defined_class);
446 }
447 
448 static const char *
450 {
451 #define type_case(t) case t: return #t;
452  switch (type) {
478  default: return NULL;
479  }
480 #undef type_case
481 }
482 
483 static inline rb_method_entry_t *
484 rb_search_method_entry(VALUE recv, ID mid, VALUE *defined_class_ptr)
485 {
486  VALUE klass = CLASS_OF(recv);
487 
488  if (!klass) {
489  VALUE flags, klass;
490  if (IMMEDIATE_P(recv)) {
492  "method `%s' called on unexpected immediate object (%p)",
493  rb_id2name(mid), (void *)recv);
494  }
495  flags = RBASIC(recv)->flags;
496  klass = RBASIC(recv)->klass;
497  if (flags == 0) {
499  "method `%s' called on terminated object"
500  " (%p flags=0x%"PRIxVALUE" klass=0x%"PRIxVALUE")",
501  rb_id2name(mid), (void *)recv, flags, klass);
502  }
503  else {
504  int type = BUILTIN_TYPE(recv);
505  const char *typestr = rb_type_str(type);
506  if (typestr && T_OBJECT <= type && type < T_NIL)
508  "method `%s' called on hidden %s object"
509  " (%p flags=0x%"PRIxVALUE" klass=0x%"PRIxVALUE")",
510  rb_id2name(mid), typestr, (void *)recv, flags, klass);
511  if (typestr)
513  "method `%s' called on unexpected %s object"
514  " (%p flags=0x%"PRIxVALUE" klass=0x%"PRIxVALUE")",
515  rb_id2name(mid), typestr, (void *)recv, flags, klass);
516  else
518  "method `%s' called on broken T_???" "(0x%02x) object"
519  " (%p flags=0x%"PRIxVALUE" klass=0x%"PRIxVALUE")",
520  rb_id2name(mid), type, (void *)recv, flags, klass);
521  }
522  }
523  return rb_method_entry(klass, mid, defined_class_ptr);
524 }
525 
526 static inline int
528 {
529  VALUE klass;
530  ID oid;
531  int noex;
532 
533  if (UNDEFINED_METHOD_ENTRY_P(me)) {
534  return scope == CALL_VCALL ? NOEX_VCALL : 0;
535  }
536  klass = me->klass;
537  oid = me->def->original_id;
538  noex = me->flag;
539 
540  if (oid != idMethodMissing) {
541  /* receiver specified form for private method */
542  if (UNLIKELY(noex)) {
543  if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == CALL_PUBLIC) {
544  return NOEX_PRIVATE;
545  }
546 
547  /* self must be kind of a specified form for protected method */
548  if (((noex & NOEX_MASK) & NOEX_PROTECTED) && scope == CALL_PUBLIC) {
549  VALUE defined_class = klass;
550 
551  if (RB_TYPE_P(defined_class, T_ICLASS)) {
552  defined_class = RBASIC(defined_class)->klass;
553  }
554 
555  if (self == Qundef || !rb_obj_is_kind_of(self, defined_class)) {
556  return NOEX_PROTECTED;
557  }
558  }
559 
560  if (NOEX_SAFE(noex) > th->safe_level) {
561  rb_raise(rb_eSecurityError, "calling insecure method: %s",
562  rb_id2name(me->called_id));
563  }
564  }
565  }
566  return NOEX_OK;
567 }
568 
569 
581 static inline VALUE
582 rb_call(VALUE recv, ID mid, int argc, const VALUE *argv, call_type scope)
583 {
584  rb_thread_t *th = GET_THREAD();
585  return rb_call0(recv, mid, argc, argv, scope, th->cfp->self);
586 }
587 
588 NORETURN(static void raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv,
589  VALUE obj, int call_status));
590 
591 /*
592  * call-seq:
593  * obj.method_missing(symbol [, *args] ) -> result
594  *
595  * Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
596  * <i>symbol</i> is the symbol for the method called, and <i>args</i>
597  * are any arguments that were passed to it. By default, the interpreter
598  * raises an error when this method is called. However, it is possible
599  * to override the method to provide more dynamic behavior.
600  * If it is decided that a particular method should not be handled, then
601  * <i>super</i> should be called, so that ancestors can pick up the
602  * missing method.
603  * The example below creates
604  * a class <code>Roman</code>, which responds to methods with names
605  * consisting of roman numerals, returning the corresponding integer
606  * values.
607  *
608  * class Roman
609  * def roman_to_int(str)
610  * # ...
611  * end
612  * def method_missing(methId)
613  * str = methId.id2name
614  * roman_to_int(str)
615  * end
616  * end
617  *
618  * r = Roman.new
619  * r.iv #=> 4
620  * r.xxiii #=> 23
621  * r.mm #=> 2000
622  */
623 
624 static VALUE
625 rb_method_missing(int argc, const VALUE *argv, VALUE obj)
626 {
627  rb_thread_t *th = GET_THREAD();
628  raise_method_missing(th, argc, argv, obj, th->method_missing_reason);
629  UNREACHABLE;
630 }
631 
632 #define NOEX_MISSING 0x80
633 
634 static VALUE
635 make_no_method_exception(VALUE exc, const char *format, VALUE obj, int argc, const VALUE *argv)
636 {
637  int n = 0;
638  VALUE mesg;
639  VALUE args[3];
640 
641  if (!format) {
642  format = "undefined method `%s' for %s";
643  }
644  mesg = rb_const_get(exc, rb_intern("message"));
645  if (rb_method_basic_definition_p(CLASS_OF(mesg), '!')) {
646  args[n++] = rb_name_err_mesg_new(mesg, rb_str_new2(format), obj, argv[0]);
647  }
648  else {
649  args[n++] = rb_funcall(mesg, '!', 3, rb_str_new2(format), obj, argv[0]);
650  }
651  args[n++] = argv[0];
652  if (exc == rb_eNoMethodError) {
653  args[n++] = rb_ary_new4(argc - 1, argv + 1);
654  }
655  return rb_class_new_instance(n, args, exc);
656 }
657 
658 static void
659 raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, VALUE obj,
660  int last_call_status)
661 {
662  VALUE exc = rb_eNoMethodError;
663  const char *format = 0;
664 
665  if (argc == 0 || !SYMBOL_P(argv[0])) {
666  rb_raise(rb_eArgError, "no id given");
667  }
668 
669  stack_check();
670 
671  if (last_call_status & NOEX_PRIVATE) {
672  format = "private method `%s' called for %s";
673  }
674  else if (last_call_status & NOEX_PROTECTED) {
675  format = "protected method `%s' called for %s";
676  }
677  else if (last_call_status & NOEX_VCALL) {
678  format = "undefined local variable or method `%s' for %s";
679  exc = rb_eNameError;
680  }
681  else if (last_call_status & NOEX_SUPER) {
682  format = "super: no superclass method `%s' for %s";
683  }
684 
685  {
686  exc = make_no_method_exception(exc, format, obj, argc, argv);
687  if (!(last_call_status & NOEX_MISSING)) {
689  }
690  rb_exc_raise(exc);
691  }
692 }
693 
694 static inline VALUE
695 method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status)
696 {
697  VALUE *nargv, result, argv_ary = 0;
698  rb_thread_t *th = GET_THREAD();
699  const rb_block_t *blockptr = th->passed_block;
700 
701  th->method_missing_reason = call_status;
702  th->passed_block = 0;
703 
704  if (id == idMethodMissing) {
705  raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING);
706  }
707 
708  if (argc < 0x100) {
709  nargv = ALLOCA_N(VALUE, argc + 1);
710  }
711  else {
712  argv_ary = rb_ary_tmp_new(argc + 1);
713  nargv = RARRAY_PTR(argv_ary);
714  }
715  nargv[0] = ID2SYM(id);
716  MEMCPY(nargv + 1, argv, VALUE, argc);
717  if (argv_ary) rb_ary_set_len(argv_ary, argc + 1);
718 
719  if (rb_method_basic_definition_p(CLASS_OF(obj) , idMethodMissing)) {
720  raise_method_missing(th, argc+1, nargv, obj, call_status | NOEX_MISSING);
721  }
722  th->passed_block = blockptr;
723  result = rb_funcall2(obj, idMethodMissing, argc + 1, nargv);
724  if (argv_ary) rb_ary_clear(argv_ary);
725  return result;
726 }
727 
728 void
730  VALUE obj, int call_status)
731 {
732  th->passed_block = 0;
733  raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING);
734 }
735 
744 VALUE
746 {
747  int argc;
748  VALUE *argv, ret;
749 
750  argc = RARRAY_LENINT(args);
751  if (argc >= 0x100) {
752  args = rb_ary_subseq(args, 0, argc);
753  RBASIC(args)->klass = 0;
754  OBJ_FREEZE(args);
755  ret = rb_call(recv, mid, argc, RARRAY_PTR(args), CALL_FCALL);
756  RB_GC_GUARD(args);
757  return ret;
758  }
759  argv = ALLOCA_N(VALUE, argc);
760  MEMCPY(argv, RARRAY_PTR(args), VALUE, argc);
761  return rb_call(recv, mid, argc, argv, CALL_FCALL);
762 }
763 
773 VALUE
774 rb_funcall(VALUE recv, ID mid, int n, ...)
775 {
776  VALUE *argv;
777  va_list ar;
778 
779  if (n > 0) {
780  long i;
781 
782  va_init_list(ar, n);
783 
784  argv = ALLOCA_N(VALUE, n);
785 
786  for (i = 0; i < n; i++) {
787  argv[i] = va_arg(ar, VALUE);
788  }
789  va_end(ar);
790  }
791  else {
792  argv = 0;
793  }
794  return rb_call(recv, mid, n, argv, CALL_FCALL);
795 }
796 
804 VALUE
805 rb_funcall2(VALUE recv, ID mid, int argc, const VALUE *argv)
806 {
807  return rb_call(recv, mid, argc, argv, CALL_FCALL);
808 }
809 
819 VALUE
820 rb_funcall3(VALUE recv, ID mid, int argc, const VALUE *argv)
821 {
822  return rb_call(recv, mid, argc, argv, CALL_PUBLIC);
823 }
824 
825 VALUE
827 {
829 
830  return rb_call(recv, mid, argc, argv, CALL_PUBLIC);
831 }
832 
833 static VALUE
834 send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope)
835 {
836  ID id;
837  VALUE vid;
838  VALUE self;
839  rb_thread_t *th = GET_THREAD();
840 
841  if (scope == CALL_PUBLIC) {
842  self = Qundef;
843  }
844  else {
845  self = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp)->self;
846  }
847 
848  if (argc == 0) {
849  rb_raise(rb_eArgError, "no method name given");
850  }
851 
852  vid = *argv++; argc--;
853 
854  id = rb_check_id(&vid);
855  if (!id) {
856  if (rb_method_basic_definition_p(CLASS_OF(recv), idMethodMissing)) {
858  recv, ++argc, --argv);
859  rb_exc_raise(exc);
860  }
861  id = rb_to_id(vid);
862  }
864  return rb_call0(recv, id, argc, argv, scope, self);
865 }
866 
867 /*
868  * call-seq:
869  * foo.send(symbol [, args...]) -> obj
870  * foo.__send__(symbol [, args...]) -> obj
871  *
872  * Invokes the method identified by _symbol_, passing it any
873  * arguments specified. You can use <code>__send__</code> if the name
874  * +send+ clashes with an existing method in _obj_.
875  *
876  * class Klass
877  * def hello(*args)
878  * "Hello " + args.join(' ')
879  * end
880  * end
881  * k = Klass.new
882  * k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
883  */
884 
885 VALUE
887 {
888  return send_internal(argc, argv, recv, CALL_FCALL);
889 }
890 
891 /*
892  * call-seq:
893  * obj.public_send(symbol [, args...]) -> obj
894  *
895  * Invokes the method identified by _symbol_, passing it any
896  * arguments specified. Unlike send, public_send calls public
897  * methods only.
898  *
899  * 1.public_send(:puts, "hello") # causes NoMethodError
900  */
901 
902 VALUE
904 {
905  return send_internal(argc, argv, recv, CALL_PUBLIC);
906 }
907 
908 /* yield */
909 
910 static inline VALUE
911 rb_yield_0(int argc, const VALUE * argv)
912 {
913  return vm_yield(GET_THREAD(), argc, argv);
914 }
915 
916 VALUE
918 {
919  if (val == Qundef) {
920  return rb_yield_0(0, 0);
921  }
922  else {
923  return rb_yield_0(1, &val);
924  }
925 }
926 
927 VALUE
928 rb_yield_values(int n, ...)
929 {
930  if (n == 0) {
931  return rb_yield_0(0, 0);
932  }
933  else {
934  int i;
935  VALUE *argv;
936  va_list args;
937  argv = ALLOCA_N(VALUE, n);
938 
939  va_init_list(args, n);
940  for (i=0; i<n; i++) {
941  argv[i] = va_arg(args, VALUE);
942  }
943  va_end(args);
944 
945  return rb_yield_0(n, argv);
946  }
947 }
948 
949 VALUE
950 rb_yield_values2(int argc, const VALUE *argv)
951 {
952  return rb_yield_0(argc, argv);
953 }
954 
955 VALUE
957 {
958  VALUE tmp = rb_check_array_type(values);
959  volatile VALUE v;
960  if (NIL_P(tmp)) {
961  rb_raise(rb_eArgError, "not an array");
962  }
963  v = rb_yield_0(RARRAY_LENINT(tmp), RARRAY_PTR(tmp));
964  return v;
965 }
966 
967 static VALUE
968 loop_i(void)
969 {
970  for (;;) {
971  rb_yield_0(0, 0);
972  }
973  return Qnil;
974 }
975 
976 static VALUE
978 {
979  return DBL2NUM(INFINITY);
980 }
981 
982 /*
983  * call-seq:
984  * loop { block }
985  * loop -> an_enumerator
986  *
987  * Repeatedly executes the block.
988  *
989  * If no block is given, an enumerator is returned instead.
990  *
991  * loop do
992  * print "Input: "
993  * line = gets
994  * break if !line or line =~ /^qQ/
995  * # ...
996  * end
997  *
998  * StopIteration raised in the block breaks the loop.
999  */
1000 
1001 static VALUE
1003 {
1005  rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0);
1006  return Qnil; /* dummy */
1007 }
1008 
1009 #if VMDEBUG
1010 static const char *
1011 vm_frametype_name(const rb_control_frame_t *cfp);
1012 #endif
1013 
1014 VALUE
1015 rb_iterate(VALUE (* it_proc) (VALUE), VALUE data1,
1016  VALUE (* bl_proc) (ANYARGS), VALUE data2)
1017 {
1018  int state;
1019  volatile VALUE retval = Qnil;
1020  NODE *node = NEW_IFUNC(bl_proc, data2);
1021  rb_thread_t *th = GET_THREAD();
1022  rb_control_frame_t *volatile cfp = th->cfp;
1023 
1024  node->nd_aid = rb_frame_this_func();
1025  TH_PUSH_TAG(th);
1026  state = TH_EXEC_TAG();
1027  if (state == 0) {
1028  iter_retry:
1029  {
1030  rb_block_t *blockptr;
1031  if (bl_proc) {
1032  blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP(th->cfp);
1033  blockptr->iseq = (void *)node;
1034  blockptr->proc = 0;
1035  }
1036  else {
1037  blockptr = VM_CF_BLOCK_PTR(th->cfp);
1038  }
1039  th->passed_block = blockptr;
1040  }
1041  retval = (*it_proc) (data1);
1042  }
1043  else {
1044  VALUE err = th->errinfo;
1045  if (state == TAG_BREAK) {
1046  VALUE *escape_ep = GET_THROWOBJ_CATCH_POINT(err);
1047  VALUE *cep = cfp->ep;
1048 
1049  if (cep == escape_ep) {
1050  state = 0;
1051  th->state = 0;
1052  th->errinfo = Qnil;
1053  retval = GET_THROWOBJ_VAL(err);
1054 
1055  /* check skipped frame */
1056  while (th->cfp != cfp) {
1057 #if VMDEBUG
1058  printf("skipped frame: %s\n", vm_frametype_name(th->cfp));
1059 #endif
1061  const rb_method_entry_t *me = th->cfp->me;
1064  }
1065 
1067  }
1068  }
1069  else{
1070  /* SDR(); printf("%p, %p\n", cdfp, escape_dfp); */
1071  }
1072  }
1073  else if (state == TAG_RETRY) {
1074  VALUE *escape_ep = GET_THROWOBJ_CATCH_POINT(err);
1075  VALUE *cep = cfp->ep;
1076 
1077  if (cep == escape_ep) {
1078  state = 0;
1079  th->state = 0;
1080  th->errinfo = Qnil;
1081  th->cfp = cfp;
1082  goto iter_retry;
1083  }
1084  }
1085  }
1086  TH_POP_TAG();
1087 
1088  switch (state) {
1089  case 0:
1090  break;
1091  default:
1092  TH_JUMP_TAG(th, state);
1093  }
1094  return retval;
1095 }
1096 
1100  int argc;
1102 };
1103 
1104 static VALUE
1106 {
1107  const struct iter_method_arg * arg =
1108  (struct iter_method_arg *) obj;
1109 
1110  return rb_call(arg->obj, arg->mid, arg->argc, arg->argv, CALL_FCALL);
1111 }
1112 
1113 VALUE
1115  VALUE (*bl_proc) (ANYARGS), VALUE data2)
1116 {
1117  struct iter_method_arg arg;
1118 
1119  arg.obj = obj;
1120  arg.mid = mid;
1121  arg.argc = argc;
1122  arg.argv = argv;
1123  return rb_iterate(iterate_method, (VALUE)&arg, bl_proc, data2);
1124 }
1125 
1126 static VALUE
1128 {
1129  const struct iter_method_arg * arg =
1130  (struct iter_method_arg *) obj;
1131 
1132  return rb_check_funcall(arg->obj, arg->mid, arg->argc, arg->argv);
1133 }
1134 
1135 VALUE
1136 rb_check_block_call(VALUE obj, ID mid, int argc, VALUE * argv,
1137  VALUE (*bl_proc) (ANYARGS), VALUE data2)
1138 {
1139  struct iter_method_arg arg;
1140 
1141  arg.obj = obj;
1142  arg.mid = mid;
1143  arg.argc = argc;
1144  arg.argv = argv;
1145  return rb_iterate(iterate_check_method, (VALUE)&arg, bl_proc, data2);
1146 }
1147 
1148 VALUE
1150 {
1151  return rb_call(obj, idEach, 0, 0, CALL_FCALL);
1152 }
1153 
1154 static VALUE
1155 eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, const char *volatile file, volatile int line)
1156 {
1157  int state;
1158  VALUE result = Qundef;
1159  VALUE envval;
1160  rb_binding_t *bind = 0;
1161  rb_thread_t *th = GET_THREAD();
1162  rb_env_t *env = NULL;
1163  rb_block_t block, *base_block;
1164  volatile int parse_in_eval;
1165  volatile int mild_compile_error;
1166 
1167  if (file == 0) {
1168  file = rb_sourcefile();
1169  line = rb_sourceline();
1170  }
1171 
1172  parse_in_eval = th->parse_in_eval;
1173  mild_compile_error = th->mild_compile_error;
1174  TH_PUSH_TAG(th);
1175  if ((state = TH_EXEC_TAG()) == 0) {
1176  rb_iseq_t *iseq;
1177  volatile VALUE iseqval;
1178 
1179  if (scope != Qnil) {
1180  if (rb_obj_is_kind_of(scope, rb_cBinding)) {
1181  GetBindingPtr(scope, bind);
1182  envval = bind->env;
1183  if (strcmp(file, "(eval)") == 0 && bind->path != Qnil) {
1184  file = RSTRING_PTR(bind->path);
1185  line = bind->first_lineno;
1186  }
1187  }
1188  else {
1190  "wrong argument type %s (expected Binding)",
1191  rb_obj_classname(scope));
1192  }
1193  GetEnvPtr(envval, env);
1194  base_block = &env->block;
1195  }
1196  else {
1198 
1199  if (cfp != 0) {
1200  block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp);
1201  base_block = &block;
1202  base_block->self = self;
1203  base_block->iseq = cfp->iseq; /* TODO */
1204  }
1205  else {
1206  rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread");
1207  }
1208  }
1209 
1210  /* make eval iseq */
1211  th->parse_in_eval++;
1212  th->mild_compile_error++;
1213  iseqval = rb_iseq_compile_on_base(src, rb_str_new2(file), INT2FIX(line), base_block);
1214  th->mild_compile_error--;
1215  th->parse_in_eval--;
1216 
1217  vm_set_eval_stack(th, iseqval, cref, base_block);
1218 
1219  if (0) { /* for debug */
1220  VALUE disasm = rb_iseq_disasm(iseqval);
1221  printf("%s\n", StringValuePtr(disasm));
1222  }
1223 
1224  /* save new env */
1225  GetISeqPtr(iseqval, iseq);
1226  if (bind && iseq->local_table_size > 0) {
1227  bind->env = rb_vm_make_env_object(th, th->cfp);
1228  }
1229 
1230  /* kick */
1232  result = vm_exec(th);
1233  }
1234  TH_POP_TAG();
1235  th->mild_compile_error = mild_compile_error;
1236  th->parse_in_eval = parse_in_eval;
1237 
1238  if (state) {
1239  if (state == TAG_RAISE) {
1240  VALUE errinfo = th->errinfo;
1241  if (strcmp(file, "(eval)") == 0) {
1242  VALUE mesg, errat, bt2;
1243  ID id_mesg;
1244 
1245  CONST_ID(id_mesg, "mesg");
1246  errat = rb_get_backtrace(errinfo);
1247  mesg = rb_attr_get(errinfo, id_mesg);
1248  if (!NIL_P(errat) && RB_TYPE_P(errat, T_ARRAY) &&
1249  (bt2 = vm_backtrace_str_ary(th, 0, 0), RARRAY_LEN(bt2) > 0)) {
1250  if (!NIL_P(mesg) && RB_TYPE_P(mesg, T_STRING) && !RSTRING_LEN(mesg)) {
1251  if (OBJ_FROZEN(mesg)) {
1252  VALUE m = rb_str_cat(rb_str_dup(RARRAY_PTR(errat)[0]), ": ", 2);
1253  rb_ivar_set(errinfo, id_mesg, rb_str_append(m, mesg));
1254  }
1255  else {
1256  rb_str_update(mesg, 0, 0, rb_str_new2(": "));
1257  rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]);
1258  }
1259  }
1260  RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0];
1261  }
1262  }
1263  rb_exc_raise(errinfo);
1264  }
1265  JUMP_TAG(state);
1266  }
1267  return result;
1268 }
1269 
1270 static VALUE
1271 eval_string(VALUE self, VALUE src, VALUE scope, const char *file, int line)
1272 {
1273  return eval_string_with_cref(self, src, scope, 0, file, line);
1274 }
1275 
1276 /*
1277  * call-seq:
1278  * eval(string [, binding [, filename [,lineno]]]) -> obj
1279  *
1280  * Evaluates the Ruby expression(s) in <em>string</em>. If
1281  * <em>binding</em> is given, which must be a <code>Binding</code>
1282  * object, the evaluation is performed in its context. If the
1283  * optional <em>filename</em> and <em>lineno</em> parameters are
1284  * present, they will be used when reporting syntax errors.
1285  *
1286  * def get_binding(str)
1287  * return binding
1288  * end
1289  * str = "hello"
1290  * eval "str + ' Fred'" #=> "hello Fred"
1291  * eval "str + ' Fred'", get_binding("bye") #=> "bye Fred"
1292  */
1293 
1294 VALUE
1295 rb_f_eval(int argc, VALUE *argv, VALUE self)
1296 {
1297  VALUE src, scope, vfile, vline;
1298  const char *file = "(eval)";
1299  int line = 1;
1300 
1301  rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
1302  if (rb_safe_level() >= 4) {
1303  StringValue(src);
1304  if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
1306  "Insecure: can't modify trusted binding");
1307  }
1308  }
1309  else {
1310  SafeStringValue(src);
1311  }
1312  if (argc >= 3) {
1313  StringValue(vfile);
1314  }
1315  if (argc >= 4) {
1316  line = NUM2INT(vline);
1317  }
1318 
1319  if (!NIL_P(vfile))
1320  file = RSTRING_PTR(vfile);
1321  return eval_string(self, src, scope, file, line);
1322 }
1323 
1325 VALUE
1326 ruby_eval_string_from_file(const char *str, const char *filename)
1327 {
1328  return eval_string(rb_vm_top_self(), rb_str_new2(str), Qnil, filename, 1);
1329 }
1330 
1332  const char *str;
1333  const char *filename;
1334 };
1335 
1336 static VALUE
1338 {
1339  const struct eval_string_from_file_arg *const arg = (struct eval_string_from_file_arg*)data;
1340  return eval_string(rb_vm_top_self(), rb_str_new2(arg->str), Qnil, arg->filename, 1);
1341 }
1342 
1343 VALUE
1344 ruby_eval_string_from_file_protect(const char *str, const char *filename, int *state)
1345 {
1346  struct eval_string_from_file_arg arg;
1347  arg.str = str;
1348  arg.filename = filename;
1349  return rb_protect((VALUE (*)(VALUE))eval_string_from_file_helper, (VALUE)&arg, state);
1350 }
1351 
1364 VALUE
1365 rb_eval_string(const char *str)
1366 {
1367  return ruby_eval_string_from_file(str, "eval");
1368 }
1369 
1380 VALUE
1381 rb_eval_string_protect(const char *str, int *state)
1382 {
1383  return rb_protect((VALUE (*)(VALUE))rb_eval_string, (VALUE)str, state);
1384 }
1385 
1397 VALUE
1398 rb_eval_string_wrap(const char *str, int *state)
1399 {
1400  int status;
1401  rb_thread_t *th = GET_THREAD();
1402  VALUE self = th->top_self;
1403  VALUE wrapper = th->top_wrapper;
1404  VALUE val;
1405 
1406  th->top_wrapper = rb_module_new();
1409 
1410  val = rb_eval_string_protect(str, &status);
1411 
1412  th->top_self = self;
1413  th->top_wrapper = wrapper;
1414 
1415  if (state) {
1416  *state = status;
1417  }
1418  else if (status) {
1419  JUMP_TAG(status);
1420  }
1421  return val;
1422 }
1423 
1424 VALUE
1425 rb_eval_cmd(VALUE cmd, VALUE arg, int level)
1426 {
1427  int state;
1428  VALUE val = Qnil; /* OK */
1429  volatile int safe = rb_safe_level();
1430 
1431  if (OBJ_TAINTED(cmd)) {
1432  level = 4;
1433  }
1434 
1435  if (!RB_TYPE_P(cmd, T_STRING)) {
1436  PUSH_TAG();
1437  rb_set_safe_level_force(level);
1438  if ((state = EXEC_TAG()) == 0) {
1439  val = rb_funcall2(cmd, rb_intern("call"), RARRAY_LENINT(arg),
1440  RARRAY_PTR(arg));
1441  }
1442  POP_TAG();
1443 
1445 
1446  if (state)
1447  JUMP_TAG(state);
1448  return val;
1449  }
1450 
1451  PUSH_TAG();
1452  if ((state = EXEC_TAG()) == 0) {
1453  val = eval_string(rb_vm_top_self(), cmd, Qnil, 0, 0);
1454  }
1455  POP_TAG();
1456 
1458  if (state) JUMP_TAG(state);
1459  return val;
1460 }
1461 
1462 /* block eval under the class/module context */
1463 
1464 static VALUE
1465 yield_under(VALUE under, VALUE self, VALUE values)
1466 {
1467  rb_thread_t *th = GET_THREAD();
1468  rb_block_t block, *blockptr;
1469  NODE *cref;
1470 
1471  if ((blockptr = VM_CF_BLOCK_PTR(th->cfp)) != 0) {
1472  block = *blockptr;
1473  block.self = self;
1474  VM_CF_LEP(th->cfp)[0] = VM_ENVVAL_BLOCK_PTR(&block);
1475  }
1476  cref = vm_cref_push(th, under, NOEX_PUBLIC, blockptr);
1478 
1479  if (values == Qundef) {
1480  return vm_yield_with_cref(th, 1, &self, cref);
1481  }
1482  else {
1483  return vm_yield_with_cref(th, RARRAY_LENINT(values), RARRAY_PTR(values), cref);
1484  }
1485 }
1486 
1487 VALUE
1488 rb_yield_refine_block(VALUE refinement, VALUE refinements)
1489 {
1490  rb_thread_t *th = GET_THREAD();
1491  rb_block_t block, *blockptr;
1492  NODE *cref;
1493 
1494  if ((blockptr = VM_CF_BLOCK_PTR(th->cfp)) != 0) {
1495  block = *blockptr;
1496  block.self = refinement;
1497  VM_CF_LEP(th->cfp)[0] = VM_ENVVAL_BLOCK_PTR(&block);
1498  }
1499  cref = vm_cref_push(th, refinement, NOEX_PUBLIC, blockptr);
1501  cref->nd_refinements = refinements;
1502 
1503  return vm_yield_with_cref(th, 0, NULL, cref);
1504 }
1505 
1506 /* string eval under the class/module context */
1507 static VALUE
1508 eval_under(VALUE under, VALUE self, VALUE src, const char *file, int line)
1509 {
1510  NODE *cref = vm_cref_push(GET_THREAD(), under, NOEX_PUBLIC, NULL);
1511 
1512  if (SPECIAL_CONST_P(self) && !NIL_P(under)) {
1514  }
1515  if (rb_safe_level() >= 4) {
1516  StringValue(src);
1517  }
1518  else {
1519  SafeStringValue(src);
1520  }
1521 
1522  return eval_string_with_cref(self, src, Qnil, cref, file, line);
1523 }
1524 
1525 static VALUE
1526 specific_eval(int argc, VALUE *argv, VALUE klass, VALUE self)
1527 {
1528  if (rb_block_given_p()) {
1529  rb_check_arity(argc, 0, 0);
1530  return yield_under(klass, self, Qundef);
1531  }
1532  else {
1533  const char *file = "(eval)";
1534  int line = 1;
1535 
1536  rb_check_arity(argc, 1, 3);
1537  if (rb_safe_level() >= 4) {
1538  StringValue(argv[0]);
1539  }
1540  else {
1541  SafeStringValue(argv[0]);
1542  }
1543  if (argc > 2)
1544  line = NUM2INT(argv[2]);
1545  if (argc > 1) {
1546  file = StringValuePtr(argv[1]);
1547  }
1548  return eval_under(klass, self, argv[0], file, line);
1549  }
1550 }
1551 
1552 /*
1553  * call-seq:
1554  * obj.instance_eval(string [, filename [, lineno]] ) -> obj
1555  * obj.instance_eval {| | block } -> obj
1556  *
1557  * Evaluates a string containing Ruby source code, or the given block,
1558  * within the context of the receiver (_obj_). In order to set the
1559  * context, the variable +self+ is set to _obj_ while
1560  * the code is executing, giving the code access to _obj_'s
1561  * instance variables. In the version of <code>instance_eval</code>
1562  * that takes a +String+, the optional second and third
1563  * parameters supply a filename and starting line number that are used
1564  * when reporting compilation errors.
1565  *
1566  * class KlassWithSecret
1567  * def initialize
1568  * @secret = 99
1569  * end
1570  * end
1571  * k = KlassWithSecret.new
1572  * k.instance_eval { @secret } #=> 99
1573  */
1574 
1575 VALUE
1576 rb_obj_instance_eval(int argc, VALUE *argv, VALUE self)
1577 {
1578  VALUE klass;
1579 
1580  if (SPECIAL_CONST_P(self)) {
1581  klass = rb_special_singleton_class(self);
1582  }
1583  else {
1584  klass = rb_singleton_class(self);
1585  }
1586  return specific_eval(argc, argv, klass, self);
1587 }
1588 
1589 /*
1590  * call-seq:
1591  * obj.instance_exec(arg...) {|var...| block } -> obj
1592  *
1593  * Executes the given block within the context of the receiver
1594  * (_obj_). In order to set the context, the variable +self+ is set
1595  * to _obj_ while the code is executing, giving the code access to
1596  * _obj_'s instance variables. Arguments are passed as block parameters.
1597  *
1598  * class KlassWithSecret
1599  * def initialize
1600  * @secret = 99
1601  * end
1602  * end
1603  * k = KlassWithSecret.new
1604  * k.instance_exec(5) {|x| @secret+x } #=> 104
1605  */
1606 
1607 VALUE
1608 rb_obj_instance_exec(int argc, VALUE *argv, VALUE self)
1609 {
1610  VALUE klass;
1611 
1612  if (SPECIAL_CONST_P(self)) {
1613  klass = rb_special_singleton_class(self);
1614  }
1615  else {
1616  klass = rb_singleton_class(self);
1617  }
1618  return yield_under(klass, self, rb_ary_new4(argc, argv));
1619 }
1620 
1621 /*
1622  * call-seq:
1623  * mod.class_eval(string [, filename [, lineno]]) -> obj
1624  * mod.module_eval {|| block } -> obj
1625  *
1626  * Evaluates the string or block in the context of _mod_, except that when
1627  * a block is given, constant/class variable lookup is not affected. This
1628  * can be used to add methods to a class. <code>module_eval</code> returns
1629  * the result of evaluating its argument. The optional _filename_ and
1630  * _lineno_ parameters set the text for error messages.
1631  *
1632  * class Thing
1633  * end
1634  * a = %q{def hello() "Hello there!" end}
1635  * Thing.module_eval(a)
1636  * puts Thing.new.hello()
1637  * Thing.module_eval("invalid code", "dummy", 123)
1638  *
1639  * <em>produces:</em>
1640  *
1641  * Hello there!
1642  * dummy:123:in `module_eval': undefined local variable
1643  * or method `code' for Thing:Class
1644  */
1645 
1646 VALUE
1648 {
1649  return specific_eval(argc, argv, mod, mod);
1650 }
1651 
1652 /*
1653  * call-seq:
1654  * mod.module_exec(arg...) {|var...| block } -> obj
1655  * mod.class_exec(arg...) {|var...| block } -> obj
1656  *
1657  * Evaluates the given block in the context of the class/module.
1658  * The method defined in the block will belong to the receiver.
1659  *
1660  * class Thing
1661  * end
1662  * Thing.class_exec{
1663  * def hello() "Hello there!" end
1664  * }
1665  * puts Thing.new.hello()
1666  *
1667  * <em>produces:</em>
1668  *
1669  * Hello there!
1670  */
1671 
1672 VALUE
1674 {
1675  return yield_under(mod, mod, rb_ary_new4(argc, argv));
1676 }
1677 
1678 /*
1679  * call-seq:
1680  * throw(tag [, obj])
1681  *
1682  * Transfers control to the end of the active +catch+ block
1683  * waiting for _tag_. Raises +ArgumentError+ if there
1684  * is no +catch+ block for the _tag_. The optional second
1685  * parameter supplies a return value for the +catch+ block,
1686  * which otherwise defaults to +nil+. For examples, see
1687  * <code>Kernel::catch</code>.
1688  */
1689 
1690 static VALUE
1691 rb_f_throw(int argc, VALUE *argv)
1692 {
1693  VALUE tag, value;
1694 
1695  rb_scan_args(argc, argv, "11", &tag, &value);
1696  rb_throw_obj(tag, value);
1697  UNREACHABLE;
1698 }
1699 
1700 void
1702 {
1703  rb_thread_t *th = GET_THREAD();
1704  struct rb_vm_tag *tt = th->tag;
1705 
1706  while (tt) {
1707  if (tt->tag == tag) {
1708  tt->retval = value;
1709  break;
1710  }
1711  tt = tt->prev;
1712  }
1713  if (!tt) {
1714  VALUE desc = rb_inspect(tag);
1715  RB_GC_GUARD(desc);
1716  rb_raise(rb_eArgError, "uncaught throw %s", RSTRING_PTR(desc));
1717  }
1718  th->errinfo = NEW_THROW_OBJECT(tag, 0, TAG_THROW);
1719 
1721 }
1722 
1723 void
1724 rb_throw(const char *tag, VALUE val)
1725 {
1726  rb_throw_obj(ID2SYM(rb_intern(tag)), val);
1727 }
1728 
1729 static VALUE
1731 {
1732  return rb_yield_0(1, &tag);
1733 }
1734 
1735 /*
1736  * call-seq:
1737  * catch([arg]) {|tag| block } -> obj
1738  *
1739  * +catch+ executes its block. If a +throw+ is
1740  * executed, Ruby searches up its stack for a +catch+ block
1741  * with a tag corresponding to the +throw+'s
1742  * _tag_. If found, that block is terminated, and
1743  * +catch+ returns the value given to +throw+. If
1744  * +throw+ is not called, the block terminates normally, and
1745  * the value of +catch+ is the value of the last expression
1746  * evaluated. +catch+ expressions may be nested, and the
1747  * +throw+ call need not be in lexical scope.
1748  *
1749  * def routine(n)
1750  * puts n
1751  * throw :done if n <= 0
1752  * routine(n-1)
1753  * end
1754  *
1755  *
1756  * catch(:done) { routine(3) }
1757  *
1758  * <em>produces:</em>
1759  *
1760  * 3
1761  * 2
1762  * 1
1763  * 0
1764  *
1765  * when _arg_ is given, +catch+ yields it as is, or when no
1766  * _arg_ is given, +catch+ assigns a new unique object to
1767  * +throw+. this is useful for nested +catch+. _arg_ can
1768  * be an arbitrary object, not only Symbol.
1769  *
1770  */
1771 
1772 static VALUE
1773 rb_f_catch(int argc, VALUE *argv)
1774 {
1775  VALUE tag;
1776 
1777  if (argc == 0) {
1778  tag = rb_obj_alloc(rb_cObject);
1779  }
1780  else {
1781  rb_scan_args(argc, argv, "01", &tag);
1782  }
1783  return rb_catch_obj(tag, catch_i, 0);
1784 }
1785 
1786 VALUE
1787 rb_catch(const char *tag, VALUE (*func)(), VALUE data)
1788 {
1789  VALUE vtag = tag ? ID2SYM(rb_intern(tag)) : rb_obj_alloc(rb_cObject);
1790  return rb_catch_obj(vtag, func, data);
1791 }
1792 
1793 VALUE
1795 {
1796  int state;
1797  volatile VALUE val = Qnil; /* OK */
1798  rb_thread_t *th = GET_THREAD();
1799  rb_control_frame_t *saved_cfp = th->cfp;
1800 
1801  TH_PUSH_TAG(th);
1802 
1803  th->tag->tag = tag;
1804 
1805  if ((state = TH_EXEC_TAG()) == 0) {
1806  /* call with argc=1, argv = [tag], block = Qnil to insure compatibility */
1807  val = (*func)(tag, data, 1, &tag, Qnil);
1808  }
1809  else if (state == TAG_THROW && RNODE(th->errinfo)->u1.value == tag) {
1810  th->cfp = saved_cfp;
1811  val = th->tag->retval;
1812  th->errinfo = Qnil;
1813  state = 0;
1814  }
1815  TH_POP_TAG();
1816  if (state)
1817  JUMP_TAG(state);
1818 
1819  return val;
1820 }
1821 
1822 /*
1823  * call-seq:
1824  * local_variables -> array
1825  *
1826  * Returns the names of the current local variables.
1827  *
1828  * fred = 1
1829  * for i in 1..10
1830  * # ...
1831  * end
1832  * local_variables #=> [:fred, :i]
1833  */
1834 
1835 static VALUE
1837 {
1838  VALUE ary = rb_ary_new();
1839  rb_thread_t *th = GET_THREAD();
1840  rb_control_frame_t *cfp =
1842  int i;
1843 
1844  while (cfp) {
1845  if (cfp->iseq) {
1846  for (i = 0; i < cfp->iseq->local_table_size; i++) {
1847  ID lid = cfp->iseq->local_table[i];
1848  if (lid) {
1849  const char *vname = rb_id2name(lid);
1850  /* should skip temporary variable */
1851  if (vname) {
1852  rb_ary_push(ary, ID2SYM(lid));
1853  }
1854  }
1855  }
1856  }
1857  if (!VM_EP_LEP_P(cfp->ep)) {
1858  /* block */
1859  VALUE *ep = VM_CF_PREV_EP(cfp);
1860 
1861  if (vm_collect_local_variables_in_heap(th, ep, ary)) {
1862  break;
1863  }
1864  else {
1865  while (cfp->ep != ep) {
1866  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1867  }
1868  }
1869  }
1870  else {
1871  break;
1872  }
1873  }
1874  return ary;
1875 }
1876 
1877 /*
1878  * call-seq:
1879  * block_given? -> true or false
1880  * iterator? -> true or false
1881  *
1882  * Returns <code>true</code> if <code>yield</code> would execute a
1883  * block in the current context. The <code>iterator?</code> form
1884  * is mildly deprecated.
1885  *
1886  * def try
1887  * if block_given?
1888  * yield
1889  * else
1890  * "no block"
1891  * end
1892  * end
1893  * try #=> "no block"
1894  * try { "hello" } #=> "hello"
1895  * try do "hello" end #=> "hello"
1896  */
1897 
1898 
1899 VALUE
1901 {
1902  rb_thread_t *th = GET_THREAD();
1903  rb_control_frame_t *cfp = th->cfp;
1905 
1906  if (cfp != 0 && VM_CF_BLOCK_PTR(cfp)) {
1907  return Qtrue;
1908  }
1909  else {
1910  return Qfalse;
1911  }
1912 }
1913 
1914 VALUE
1916 {
1917  rb_thread_t *th = GET_THREAD();
1918  rb_control_frame_t *cfp = th->cfp;
1920  if (cfp != 0) return cfp->iseq->location.absolute_path;
1921  return Qnil;
1922 }
1923 
1924 void
1926 {
1927  rb_define_global_function("eval", rb_f_eval, -1);
1928  rb_define_global_function("local_variables", rb_f_local_variables, 0);
1930  rb_define_global_function("block_given?", rb_f_block_given_p, 0);
1931 
1932  rb_define_global_function("catch", rb_f_catch, -1);
1933  rb_define_global_function("throw", rb_f_throw, -1);
1934 
1936 
1937  rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval, -1);
1938  rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec, -1);
1940 
1941 #if 1
1943  VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, 0);
1945  VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, 0);
1946 #else
1947  rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1);
1948  rb_define_method(rb_mKernel, "send", rb_f_send, -1);
1949 #endif
1950  rb_define_method(rb_mKernel, "public_send", rb_f_public_send, -1);
1951 
1952  rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec, -1);
1953  rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec, -1);
1954  rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1);
1955  rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1);
1956 }
1957