* io.c (rb_pipe_internal): new function for handling EMFILE and ENFILE
[ruby-svn.git] / vm_eval.c
blobd89f7e972a4c49d8fca2f56dc76ddd49817f7345
1 /**********************************************************************
3 vm_eval.c -
5 $Author$
6 created at: Sat May 24 16:02:32 JST 2008
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
15 #include "ruby/node.h"
16 #include "ruby/st.h"
18 #include "vm_method.c"
20 static inline VALUE method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status);
21 static inline VALUE rb_vm_set_finish_env(rb_thread_t * th);
22 static inline VALUE vm_yield_with_cref(rb_thread_t *th, int argc, const VALUE *argv, const NODE *cref);
23 static inline VALUE vm_yield(rb_thread_t *th, int argc, const VALUE *argv);
24 static inline VALUE vm_backtrace(rb_thread_t *th, int lev);
25 static NODE *vm_cref_push(rb_thread_t *th, VALUE klass, int noex);
26 static VALUE vm_eval_body(rb_thread_t *th);
27 static void vm_set_eval_stack(rb_thread_t * th, VALUE iseqval, const NODE *cref);
29 static inline VALUE
30 vm_call0(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid,
31 int argc, const VALUE *argv, const NODE *body, int nosuper)
33 VALUE val;
34 rb_block_t *blockptr = 0;
36 if (0) printf("id: %s, nd: %s, argc: %d, passed: %p\n",
37 rb_id2name(id), ruby_node_name(nd_type(body)),
38 argc, th->passed_block);
40 if (th->passed_block) {
41 blockptr = th->passed_block;
42 th->passed_block = 0;
44 switch (nd_type(body)) {
45 case RUBY_VM_METHOD_NODE:{
46 rb_control_frame_t *reg_cfp;
47 VALUE iseqval = (VALUE)body->nd_body;
48 int i;
50 rb_vm_set_finish_env(th);
51 reg_cfp = th->cfp;
53 CHECK_STACK_OVERFLOW(reg_cfp, argc + 1);
55 *reg_cfp->sp++ = recv;
56 for (i = 0; i < argc; i++) {
57 *reg_cfp->sp++ = argv[i];
60 vm_setup_method(th, reg_cfp, argc, blockptr, 0, iseqval, recv, klass);
61 val = vm_eval_body(th);
62 break;
64 case NODE_CFUNC: {
65 EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, recv, id, klass);
67 rb_control_frame_t *reg_cfp = th->cfp;
68 rb_control_frame_t *cfp =
69 vm_push_frame(th, 0, VM_FRAME_MAGIC_CFUNC,
70 recv, (VALUE)blockptr, 0, reg_cfp->sp, 0, 1);
72 cfp->method_id = id;
73 cfp->method_class = klass;
75 val = call_cfunc(body->nd_cfnc, recv, body->nd_argc, argc, argv);
77 if (reg_cfp != th->cfp + 1) {
78 SDR2(reg_cfp);
79 SDR2(th->cfp-5);
80 rb_bug("cfp consistency error - call0");
81 th->cfp = reg_cfp;
83 vm_pop_frame(th);
85 EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, recv, id, klass);
86 break;
88 case NODE_ATTRSET:{
89 if (argc != 1) {
90 rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
92 val = rb_ivar_set(recv, body->nd_vid, argv[0]);
93 break;
95 case NODE_IVAR: {
96 if (argc != 0) {
97 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)",
98 argc);
100 val = rb_attr_get(recv, body->nd_vid);
101 break;
103 case NODE_BMETHOD:{
104 val = vm_call_bmethod(th, id, body->nd_cval,
105 recv, klass, argc, (VALUE *)argv, blockptr);
106 break;
108 default:
109 rb_bug("unsupported: vm_call0(%s)", ruby_node_name(nd_type(body)));
111 RUBY_VM_CHECK_INTS();
112 return val;
115 VALUE
116 rb_vm_call(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid,
117 int argc, const VALUE *argv, const NODE *body, int nosuper)
119 return vm_call0(th, klass, recv, id, oid, argc, argv, body, nosuper);
122 static inline VALUE
123 vm_call_super(rb_thread_t * const th, const int argc, const VALUE * const argv)
125 VALUE recv = th->cfp->self;
126 VALUE klass;
127 ID id;
128 NODE *body;
129 rb_control_frame_t *cfp = th->cfp;
131 if (!cfp->iseq) {
132 klass = cfp->method_class;
133 klass = RCLASS_SUPER(klass);
135 if (klass == 0) {
136 klass = vm_search_normal_superclass(cfp->method_class, recv);
139 id = cfp->method_id;
141 else {
142 rb_bug("vm_call_super: should not be reached");
145 body = rb_method_node(klass, id); /* this returns NODE_METHOD */
147 if (body) {
148 body = body->nd_body;
150 else {
151 VALUE *argv_m = ALLOCA_N(VALUE, argc+1);
152 MEMCPY(argv_m + 1, argv, VALUE, argc);
153 argv_m[0] = ID2SYM(id);
154 th->method_missing_reason = 0;
155 th->passed_block = 0;
156 return rb_funcall2(recv, idMethodMissing, argc + 1, argv);
159 return vm_call0(th, klass, recv, id, id, argc, argv, body, CALL_SUPER);
162 VALUE
163 rb_call_super(int argc, const VALUE *argv)
165 PASS_PASSED_BLOCK();
166 return vm_call_super(GET_THREAD(), argc, argv);
169 static inline void
170 stack_check(void)
172 rb_thread_t *th = GET_THREAD();
174 if (!rb_thread_raised_p(th, RAISED_STACKOVERFLOW) && ruby_stack_check()) {
175 rb_thread_raised_set(th, RAISED_STACKOVERFLOW);
176 rb_exc_raise(sysstack_error);
180 static inline VALUE
181 rb_call0(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv,
182 int scope, VALUE self)
184 NODE *body, *method;
185 int noex;
186 ID id = mid;
187 struct cache_entry *ent;
188 rb_thread_t *th = GET_THREAD();
190 if (!klass) {
191 rb_raise(rb_eNotImpError,
192 "method `%s' called on terminated object (%p)",
193 rb_id2name(mid), (void *)recv);
195 /* is it in the method cache? */
196 ent = cache + EXPR1(klass, mid);
198 if (ent->mid == mid && ent->klass == klass) {
199 if (!ent->method)
200 return method_missing(recv, mid, argc, argv,
201 scope == 2 ? NOEX_VCALL : 0);
202 id = ent->mid0;
203 noex = ent->method->nd_noex;
204 klass = ent->method->nd_clss;
205 body = ent->method->nd_body;
207 else if ((method = rb_get_method_body(klass, id, &id)) != 0) {
208 noex = method->nd_noex;
209 klass = method->nd_clss;
210 body = method->nd_body;
212 else {
213 if (scope == 3) {
214 return method_missing(recv, mid, argc, argv, NOEX_SUPER);
216 return method_missing(recv, mid, argc, argv,
217 scope == 2 ? NOEX_VCALL : 0);
221 if (mid != missing) {
222 /* receiver specified form for private method */
223 if (UNLIKELY(noex)) {
224 if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == 0) {
225 return method_missing(recv, mid, argc, argv, NOEX_PRIVATE);
228 /* self must be kind of a specified form for protected method */
229 if (((noex & NOEX_MASK) & NOEX_PROTECTED) && scope == 0) {
230 VALUE defined_class = klass;
232 if (TYPE(defined_class) == T_ICLASS) {
233 defined_class = RBASIC(defined_class)->klass;
236 if (self == Qundef) {
237 self = th->cfp->self;
239 if (!rb_obj_is_kind_of(self, rb_class_real(defined_class))) {
240 return method_missing(recv, mid, argc, argv, NOEX_PROTECTED);
244 if (NOEX_SAFE(noex) > th->safe_level) {
245 rb_raise(rb_eSecurityError, "calling insecure method: %s", rb_id2name(mid));
250 stack_check();
251 return vm_call0(th, klass, recv, mid, id, argc, argv, body, noex & NOEX_NOSUPER);
254 static inline VALUE
255 rb_call(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv, int scope)
257 return rb_call0(klass, recv, mid, argc, argv, scope, Qundef);
261 * call-seq:
262 * obj.method_missing(symbol [, *args] ) => result
264 * Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
265 * <i>symbol</i> is the symbol for the method called, and <i>args</i>
266 * are any arguments that were passed to it. By default, the interpreter
267 * raises an error when this method is called. However, it is possible
268 * to override the method to provide more dynamic behavior.
269 * If it is decided that a particular method should not be handled, then
270 * <i>super</i> should be called, so that ancestors can pick up the
271 * missing method.
272 * The example below creates
273 * a class <code>Roman</code>, which responds to methods with names
274 * consisting of roman numerals, returning the corresponding integer
275 * values.
277 * class Roman
278 * def romanToInt(str)
279 * # ...
280 * end
281 * def method_missing(methId)
282 * str = methId.id2name
283 * romanToInt(str)
284 * end
285 * end
287 * r = Roman.new
288 * r.iv #=> 4
289 * r.xxiii #=> 23
290 * r.mm #=> 2000
293 static VALUE
294 rb_method_missing(int argc, const VALUE *argv, VALUE obj)
296 ID id;
297 VALUE exc = rb_eNoMethodError;
298 const char *format = 0;
299 rb_thread_t *th = GET_THREAD();
300 int last_call_status = th->method_missing_reason;
301 if (argc == 0 || !SYMBOL_P(argv[0])) {
302 rb_raise(rb_eArgError, "no id given");
305 stack_check();
307 id = SYM2ID(argv[0]);
309 if (last_call_status & NOEX_PRIVATE) {
310 format = "private method `%s' called for %s";
312 else if (last_call_status & NOEX_PROTECTED) {
313 format = "protected method `%s' called for %s";
315 else if (last_call_status & NOEX_VCALL) {
316 format = "undefined local variable or method `%s' for %s";
317 exc = rb_eNameError;
319 else if (last_call_status & NOEX_SUPER) {
320 format = "super: no superclass method `%s' for %s";
322 if (!format) {
323 format = "undefined method `%s' for %s";
327 int n = 0;
328 VALUE args[3];
329 args[n++] = rb_funcall(rb_const_get(exc, rb_intern("message")), '!',
330 3, rb_str_new2(format), obj, argv[0]);
331 args[n++] = argv[0];
332 if (exc == rb_eNoMethodError) {
333 args[n++] = rb_ary_new4(argc - 1, argv + 1);
335 exc = rb_class_new_instance(n, args, exc);
337 th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp);
338 rb_exc_raise(exc);
341 return Qnil; /* not reached */
344 static inline VALUE
345 method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status)
347 VALUE *nargv;
348 GET_THREAD()->method_missing_reason = call_status;
350 if (id == missing) {
351 rb_method_missing(argc, argv, obj);
353 else if (id == ID_ALLOCATOR) {
354 rb_raise(rb_eTypeError, "allocator undefined for %s",
355 rb_class2name(obj));
358 nargv = ALLOCA_N(VALUE, argc + 1);
359 nargv[0] = ID2SYM(id);
360 MEMCPY(nargv + 1, argv, VALUE, argc);
362 return rb_funcall2(obj, missing, argc + 1, nargv);
365 VALUE
366 rb_apply(VALUE recv, ID mid, VALUE args)
368 int argc;
369 VALUE *argv;
371 argc = RARRAY_LEN(args); /* Assigns LONG, but argc is INT */
372 argv = ALLOCA_N(VALUE, argc);
373 MEMCPY(argv, RARRAY_PTR(args), VALUE, argc);
374 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL);
377 VALUE
378 rb_funcall(VALUE recv, ID mid, int n, ...)
380 VALUE *argv;
381 va_list ar;
382 va_init_list(ar, n);
384 if (n > 0) {
385 long i;
387 argv = ALLOCA_N(VALUE, n);
389 for (i = 0; i < n; i++) {
390 argv[i] = va_arg(ar, VALUE);
392 va_end(ar);
394 else {
395 argv = 0;
397 return rb_call(CLASS_OF(recv), recv, mid, n, argv, CALL_FCALL);
400 VALUE
401 rb_funcall2(VALUE recv, ID mid, int argc, const VALUE *argv)
403 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL);
406 VALUE
407 rb_funcall3(VALUE recv, ID mid, int argc, const VALUE *argv)
409 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_PUBLIC);
412 static VALUE
413 send_internal(int argc, VALUE *argv, VALUE recv, int scope)
415 VALUE vid;
416 VALUE self = RUBY_VM_PREVIOUS_CONTROL_FRAME(GET_THREAD()->cfp)->self;
417 rb_thread_t *th = GET_THREAD();
419 if (argc == 0) {
420 rb_raise(rb_eArgError, "no method name given");
423 vid = *argv++; argc--;
424 PASS_PASSED_BLOCK_TH(th);
426 return rb_call0(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, scope, self);
430 * call-seq:
431 * obj.send(symbol [, args...]) => obj
432 * obj.__send__(symbol [, args...]) => obj
434 * Invokes the method identified by _symbol_, passing it any
435 * arguments specified. You can use <code>__send__</code> if the name
436 * +send+ clashes with an existing method in _obj_.
438 * class Klass
439 * def hello(*args)
440 * "Hello " + args.join(' ')
441 * end
442 * end
443 * k = Klass.new
444 * k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
447 VALUE
448 rb_f_send(int argc, VALUE *argv, VALUE recv)
450 return send_internal(argc, argv, recv, NOEX_NOSUPER | NOEX_PRIVATE);
454 * call-seq:
455 * obj.public_send(symbol [, args...]) => obj
457 * Invokes the method identified by _symbol_, passing it any
458 * arguments specified. Unlike send, public_send calls public
459 * methods only.
461 * 1.public_send(:puts, "hello") # causes NoMethodError
464 VALUE
465 rb_f_public_send(int argc, VALUE *argv, VALUE recv)
467 return send_internal(argc, argv, recv, NOEX_PUBLIC);
470 /* yield */
472 static inline VALUE
473 rb_yield_0(int argc, const VALUE * argv)
475 return vm_yield(GET_THREAD(), argc, argv);
478 VALUE
479 rb_yield(VALUE val)
481 if (val == Qundef) {
482 return rb_yield_0(0, 0);
484 else {
485 return rb_yield_0(1, &val);
489 VALUE
490 rb_yield_values(int n, ...)
492 if (n == 0) {
493 return rb_yield_0(0, 0);
495 else {
496 int i;
497 VALUE *argv;
498 va_list args;
499 argv = ALLOCA_N(VALUE, n);
501 va_init_list(args, n);
502 for (i=0; i<n; i++) {
503 argv[i] = va_arg(args, VALUE);
505 va_end(args);
507 return rb_yield_0(n, argv);
511 VALUE
512 rb_yield_values2(int argc, const VALUE *argv)
514 return rb_yield_0(argc, argv);
517 VALUE
518 rb_yield_splat(VALUE values)
520 VALUE tmp = rb_check_array_type(values);
521 volatile VALUE v;
522 if (NIL_P(tmp)) {
523 rb_raise(rb_eArgError, "not an array");
525 v = rb_yield_0(RARRAY_LEN(tmp), RARRAY_PTR(tmp));
526 return v;
529 static VALUE
530 loop_i(void)
532 for (;;) {
533 rb_yield_0(0, 0);
535 return Qnil;
539 * call-seq:
540 * loop {|| block }
542 * Repeatedly executes the block.
544 * loop do
545 * print "Input: "
546 * line = gets
547 * break if !line or line =~ /^qQ/
548 * # ...
549 * end
551 * StopIteration raised in the block breaks the loop.
554 static VALUE
555 rb_f_loop(void)
557 rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0);
558 return Qnil; /* dummy */
561 VALUE
562 rb_iterate(VALUE (* it_proc) (VALUE), VALUE data1,
563 VALUE (* bl_proc) (ANYARGS), VALUE data2)
565 int state;
566 volatile VALUE retval = Qnil;
567 NODE *node = NEW_IFUNC(bl_proc, data2);
568 rb_thread_t *th = GET_THREAD();
569 rb_control_frame_t *cfp = th->cfp;
571 TH_PUSH_TAG(th);
572 state = TH_EXEC_TAG();
573 if (state == 0) {
574 iter_retry:
576 rb_block_t *blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP(th->cfp);
577 blockptr->iseq = (void *)node;
578 blockptr->proc = 0;
579 th->passed_block = blockptr;
581 retval = (*it_proc) (data1);
583 else {
584 VALUE err = th->errinfo;
585 if (state == TAG_BREAK) {
586 VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err);
587 VALUE *cdfp = cfp->dfp;
589 if (cdfp == escape_dfp) {
590 state = 0;
591 th->state = 0;
592 th->errinfo = Qnil;
593 th->cfp = cfp;
595 else{
596 /* SDR(); printf("%p, %p\n", cdfp, escape_dfp); */
599 else if (state == TAG_RETRY) {
600 VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err);
601 VALUE *cdfp = cfp->dfp;
603 if (cdfp == escape_dfp) {
604 state = 0;
605 th->state = 0;
606 th->errinfo = Qnil;
607 th->cfp = cfp;
608 goto iter_retry;
612 TH_POP_TAG();
614 switch (state) {
615 case 0:
616 break;
617 default:
618 TH_JUMP_TAG(th, state);
620 return retval;
623 struct iter_method_arg {
624 VALUE obj;
625 ID mid;
626 int argc;
627 VALUE *argv;
630 static VALUE
631 iterate_method(VALUE obj)
633 const struct iter_method_arg * arg =
634 (struct iter_method_arg *) obj;
636 return rb_call(CLASS_OF(arg->obj), arg->obj, arg->mid,
637 arg->argc, arg->argv, CALL_FCALL);
640 VALUE
641 rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv,
642 VALUE (*bl_proc) (ANYARGS), VALUE data2)
644 struct iter_method_arg arg;
646 arg.obj = obj;
647 arg.mid = mid;
648 arg.argc = argc;
649 arg.argv = argv;
650 return rb_iterate(iterate_method, (VALUE)&arg, bl_proc, data2);
653 VALUE
654 rb_each(VALUE obj)
656 return rb_call(CLASS_OF(obj), obj, idEach, 0, 0, CALL_FCALL);
659 static VALUE
660 eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, const char *file, int line)
662 int state;
663 VALUE result = Qundef;
664 VALUE envval;
665 rb_binding_t *bind = 0;
666 rb_thread_t *th = GET_THREAD();
667 rb_env_t *env = NULL;
668 rb_block_t block;
669 volatile int parse_in_eval;
670 volatile int mild_compile_error;
672 if (file == 0) {
673 file = rb_sourcefile();
674 line = rb_sourceline();
677 parse_in_eval = th->parse_in_eval;
678 mild_compile_error = th->mild_compile_error;
679 PUSH_TAG();
680 if ((state = EXEC_TAG()) == 0) {
681 rb_iseq_t *iseq;
682 volatile VALUE iseqval;
684 if (scope != Qnil) {
685 if (rb_obj_is_kind_of(scope, rb_cBinding)) {
686 GetBindingPtr(scope, bind);
687 envval = bind->env;
689 else {
690 rb_raise(rb_eTypeError,
691 "wrong argument type %s (expected Binding)",
692 rb_obj_classname(scope));
694 GetEnvPtr(envval, env);
695 th->base_block = &env->block;
697 else {
698 rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(th, th->cfp);
700 if (cfp != 0) {
701 block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp);
702 th->base_block = &block;
703 th->base_block->self = self;
704 th->base_block->iseq = cfp->iseq; /* TODO */
706 else {
707 rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread");
711 /* make eval iseq */
712 th->parse_in_eval++;
713 th->mild_compile_error++;
714 iseqval = rb_iseq_compile(src, rb_str_new2(file), INT2FIX(line));
715 th->mild_compile_error--;
716 th->parse_in_eval--;
718 vm_set_eval_stack(th, iseqval, cref);
719 th->base_block = 0;
721 if (0) { /* for debug */
722 extern VALUE ruby_iseq_disasm(VALUE);
723 printf("%s\n", RSTRING_PTR(ruby_iseq_disasm(iseqval)));
726 /* save new env */
727 GetISeqPtr(iseqval, iseq);
728 if (bind && iseq->local_size > 0) {
729 bind->env = vm_make_env_object(th, th->cfp);
732 /* kick */
733 CHECK_STACK_OVERFLOW(th->cfp, iseq->stack_max);
734 result = vm_eval_body(th);
736 POP_TAG();
737 th->mild_compile_error = mild_compile_error;
738 th->parse_in_eval = parse_in_eval;
740 if (state) {
741 if (state == TAG_RAISE) {
742 VALUE errinfo = th->errinfo;
743 if (strcmp(file, "(eval)") == 0) {
744 VALUE mesg, errat, bt2;
745 extern VALUE rb_get_backtrace(VALUE info);
747 errat = rb_get_backtrace(errinfo);
748 mesg = rb_attr_get(errinfo, rb_intern("mesg"));
749 if (!NIL_P(errat) && TYPE(errat) == T_ARRAY &&
750 (bt2 = vm_backtrace(th, -2), RARRAY_LEN(bt2) > 0)) {
751 if (!NIL_P(mesg) && TYPE(mesg) == T_STRING && !RSTRING_LEN(mesg)) {
752 rb_str_update(mesg, 0, 0, rb_str_new2(": "));
753 rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]);
755 RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0];
758 rb_exc_raise(errinfo);
760 JUMP_TAG(state);
762 return result;
765 static VALUE
766 eval_string(VALUE self, VALUE src, VALUE scope, const char *file, int line)
768 return eval_string_with_cref(self, src, scope, 0, file, line);
772 * call-seq:
773 * eval(string [, binding [, filename [,lineno]]]) => obj
775 * Evaluates the Ruby expression(s) in <em>string</em>. If
776 * <em>binding</em> is given, the evaluation is performed in its
777 * context. The binding may be a <code>Binding</code> object or a
778 * <code>Proc</code> object. If the optional <em>filename</em> and
779 * <em>lineno</em> parameters are present, they will be used when
780 * reporting syntax errors.
782 * def getBinding(str)
783 * return binding
784 * end
785 * str = "hello"
786 * eval "str + ' Fred'" #=> "hello Fred"
787 * eval "str + ' Fred'", getBinding("bye") #=> "bye Fred"
790 VALUE
791 rb_f_eval(int argc, VALUE *argv, VALUE self)
793 VALUE src, scope, vfile, vline;
794 const char *file = "(eval)";
795 int line = 1;
797 rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
798 if (rb_safe_level() >= 4) {
799 StringValue(src);
800 if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
801 rb_raise(rb_eSecurityError,
802 "Insecure: can't modify trusted binding");
805 else {
806 SafeStringValue(src);
808 if (argc >= 3) {
809 StringValue(vfile);
811 if (argc >= 4) {
812 line = NUM2INT(vline);
815 if (!NIL_P(vfile))
816 file = RSTRING_PTR(vfile);
817 return eval_string(self, src, scope, file, line);
820 VALUE
821 rb_eval_string(const char *str)
823 return eval_string(rb_vm_top_self(), rb_str_new2(str), Qnil, "(eval)", 1);
826 VALUE
827 rb_eval_string_protect(const char *str, int *state)
829 return rb_protect((VALUE (*)(VALUE))rb_eval_string, (VALUE)str, state);
832 VALUE
833 rb_eval_string_wrap(const char *str, int *state)
835 int status;
836 rb_thread_t *th = GET_THREAD();
837 VALUE self = th->top_self;
838 VALUE wrapper = th->top_wrapper;
839 VALUE val;
841 th->top_wrapper = rb_module_new();
842 th->top_self = rb_obj_clone(rb_vm_top_self());
843 rb_extend_object(th->top_self, th->top_wrapper);
845 val = rb_eval_string_protect(str, &status);
847 th->top_self = self;
848 th->top_wrapper = wrapper;
850 if (state) {
851 *state = status;
853 else if (status) {
854 JUMP_TAG(status);
856 return val;
859 VALUE
860 rb_eval_cmd(VALUE cmd, VALUE arg, int level)
862 int state;
863 VALUE val = Qnil; /* OK */
864 volatile int safe = rb_safe_level();
866 if (OBJ_TAINTED(cmd)) {
867 level = 4;
870 if (TYPE(cmd) != T_STRING) {
871 PUSH_TAG();
872 rb_set_safe_level_force(level);
873 if ((state = EXEC_TAG()) == 0) {
874 val = rb_funcall2(cmd, rb_intern("call"), RARRAY_LEN(arg),
875 RARRAY_PTR(arg));
877 POP_TAG();
879 rb_set_safe_level_force(safe);
881 if (state)
882 JUMP_TAG(state);
883 return val;
886 PUSH_TAG();
887 if ((state = EXEC_TAG()) == 0) {
888 val = eval_string(rb_vm_top_self(), cmd, Qnil, 0, 0);
890 POP_TAG();
892 rb_set_safe_level_force(safe);
893 if (state) vm_jump_tag_but_local_jump(state, val);
894 return val;
897 /* block eval under the class/module context */
899 static VALUE
900 yield_under(VALUE under, VALUE self, VALUE values)
902 rb_thread_t *th = GET_THREAD();
903 rb_block_t block, *blockptr;
904 NODE *cref = vm_cref_push(th, under, NOEX_PUBLIC);
906 if ((blockptr = GC_GUARDED_PTR_REF(th->cfp->lfp[0])) != 0) {
907 block = *blockptr;
908 block.self = self;
909 th->cfp->lfp[0] = GC_GUARDED_PTR(&block);
912 if (values == Qundef) {
913 return vm_yield_with_cref(th, 0, 0, cref);
915 else {
916 return vm_yield_with_cref(th, RARRAY_LEN(values), RARRAY_PTR(values), cref);
920 /* string eval under the class/module context */
921 static VALUE
922 eval_under(VALUE under, VALUE self, VALUE src, const char *file, int line)
924 NODE *cref = vm_cref_push(GET_THREAD(), under, NOEX_PUBLIC);
926 if (rb_safe_level() >= 4) {
927 StringValue(src);
929 else {
930 SafeStringValue(src);
933 return eval_string_with_cref(self, src, Qnil, cref, file, line);
936 static VALUE
937 specific_eval(int argc, VALUE *argv, VALUE klass, VALUE self)
939 if (rb_block_given_p()) {
940 if (argc > 0) {
941 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
943 return yield_under(klass, self, Qundef);
945 else {
946 const char *file = "(eval)";
947 int line = 1;
949 if (argc == 0) {
950 rb_raise(rb_eArgError, "block not supplied");
952 else {
953 if (rb_safe_level() >= 4) {
954 StringValue(argv[0]);
956 else {
957 SafeStringValue(argv[0]);
959 if (argc > 3) {
960 const char *name = rb_id2name(rb_frame_callee());
961 rb_raise(rb_eArgError,
962 "wrong number of arguments: %s(src) or %s{..}",
963 name, name);
965 if (argc > 2)
966 line = NUM2INT(argv[2]);
967 if (argc > 1) {
968 file = StringValuePtr(argv[1]);
971 return eval_under(klass, self, argv[0], file, line);
976 * call-seq:
977 * obj.instance_eval(string [, filename [, lineno]] ) => obj
978 * obj.instance_eval {| | block } => obj
980 * Evaluates a string containing Ruby source code, or the given block,
981 * within the context of the receiver (_obj_). In order to set the
982 * context, the variable +self+ is set to _obj_ while
983 * the code is executing, giving the code access to _obj_'s
984 * instance variables. In the version of <code>instance_eval</code>
985 * that takes a +String+, the optional second and third
986 * parameters supply a filename and starting line number that are used
987 * when reporting compilation errors.
989 * class KlassWithSecret
990 * def initialize
991 * @secret = 99
992 * end
993 * end
994 * k = KlassWithSecret.new
995 * k.instance_eval { @secret } #=> 99
998 VALUE
999 rb_obj_instance_eval(int argc, VALUE *argv, VALUE self)
1001 VALUE klass;
1003 if (SPECIAL_CONST_P(self)) {
1004 klass = Qnil;
1006 else {
1007 klass = rb_singleton_class(self);
1009 return specific_eval(argc, argv, klass, self);
1013 * call-seq:
1014 * obj.instance_exec(arg...) {|var...| block } => obj
1016 * Executes the given block within the context of the receiver
1017 * (_obj_). In order to set the context, the variable +self+ is set
1018 * to _obj_ while the code is executing, giving the code access to
1019 * _obj_'s instance variables. Arguments are passed as block parameters.
1021 * class KlassWithSecret
1022 * def initialize
1023 * @secret = 99
1024 * end
1025 * end
1026 * k = KlassWithSecret.new
1027 * k.instance_exec(5) {|x| @secret+x } #=> 104
1030 VALUE
1031 rb_obj_instance_exec(int argc, VALUE *argv, VALUE self)
1033 VALUE klass;
1035 if (SPECIAL_CONST_P(self)) {
1036 klass = Qnil;
1038 else {
1039 klass = rb_singleton_class(self);
1041 return yield_under(klass, self, rb_ary_new4(argc, argv));
1045 * call-seq:
1046 * mod.class_eval(string [, filename [, lineno]]) => obj
1047 * mod.module_eval {|| block } => obj
1049 * Evaluates the string or block in the context of _mod_. This can
1050 * be used to add methods to a class. <code>module_eval</code> returns
1051 * the result of evaluating its argument. The optional _filename_
1052 * and _lineno_ parameters set the text for error messages.
1054 * class Thing
1055 * end
1056 * a = %q{def hello() "Hello there!" end}
1057 * Thing.module_eval(a)
1058 * puts Thing.new.hello()
1059 * Thing.module_eval("invalid code", "dummy", 123)
1061 * <em>produces:</em>
1063 * Hello there!
1064 * dummy:123:in `module_eval': undefined local variable
1065 * or method `code' for Thing:Class
1068 VALUE
1069 rb_mod_module_eval(int argc, VALUE *argv, VALUE mod)
1071 return specific_eval(argc, argv, mod, mod);
1075 * call-seq:
1076 * mod.module_exec(arg...) {|var...| block } => obj
1077 * mod.class_exec(arg...) {|var...| block } => obj
1079 * Evaluates the given block in the context of the class/module.
1080 * The method defined in the block will belong to the receiver.
1082 * class Thing
1083 * end
1084 * Thing.class_exec{
1085 * def hello() "Hello there!" end
1087 * puts Thing.new.hello()
1089 * <em>produces:</em>
1091 * Hello there!
1094 VALUE
1095 rb_mod_module_exec(int argc, VALUE *argv, VALUE mod)
1097 return yield_under(mod, mod, rb_ary_new4(argc, argv));
1100 NORETURN(static VALUE rb_f_throw _((int, VALUE *)));
1103 * call-seq:
1104 * throw(symbol [, obj])
1106 * Transfers control to the end of the active +catch+ block
1107 * waiting for _symbol_. Raises +NameError+ if there
1108 * is no +catch+ block for the symbol. The optional second
1109 * parameter supplies a return value for the +catch+ block,
1110 * which otherwise defaults to +nil+. For examples, see
1111 * <code>Kernel::catch</code>.
1114 static VALUE
1115 rb_f_throw(int argc, VALUE *argv)
1117 VALUE tag, value;
1118 rb_thread_t *th = GET_THREAD();
1119 struct rb_vm_tag *tt = th->tag;
1121 rb_scan_args(argc, argv, "11", &tag, &value);
1122 while (tt) {
1123 if (tt->tag == tag) {
1124 tt->retval = value;
1125 break;
1127 tt = tt->prev;
1129 if (!tt) {
1130 VALUE desc = rb_inspect(tag);
1131 rb_raise(rb_eArgError, "uncaught throw %s", RSTRING_PTR(desc));
1133 rb_trap_restore_mask();
1134 th->errinfo = NEW_THROW_OBJECT(tag, 0, TAG_THROW);
1136 JUMP_TAG(TAG_THROW);
1137 #ifndef __GNUC__
1138 return Qnil; /* not reached */
1139 #endif
1142 void
1143 rb_throw(const char *tag, VALUE val)
1145 VALUE argv[2];
1147 argv[0] = ID2SYM(rb_intern(tag));
1148 argv[1] = val;
1149 rb_f_throw(2, argv);
1152 void
1153 rb_throw_obj(VALUE tag, VALUE val)
1155 VALUE argv[2];
1157 argv[0] = tag;
1158 argv[1] = val;
1159 rb_f_throw(2, argv);
1163 * call-seq:
1164 * catch(symbol) {| | block } > obj
1166 * +catch+ executes its block. If a +throw+ is
1167 * executed, Ruby searches up its stack for a +catch+ block
1168 * with a tag corresponding to the +throw+'s
1169 * _symbol_. If found, that block is terminated, and
1170 * +catch+ returns the value given to +throw+. If
1171 * +throw+ is not called, the block terminates normally, and
1172 * the value of +catch+ is the value of the last expression
1173 * evaluated. +catch+ expressions may be nested, and the
1174 * +throw+ call need not be in lexical scope.
1176 * def routine(n)
1177 * puts n
1178 * throw :done if n <= 0
1179 * routine(n-1)
1180 * end
1183 * catch(:done) { routine(3) }
1185 * <em>produces:</em>
1193 static VALUE
1194 rb_f_catch(int argc, VALUE *argv)
1196 VALUE tag;
1197 int state;
1198 VALUE val = Qnil; /* OK */
1199 rb_thread_t *th = GET_THREAD();
1200 rb_control_frame_t *saved_cfp = th->cfp;
1202 if (argc == 0) {
1203 tag = rb_obj_alloc(rb_cObject);
1205 else {
1206 rb_scan_args(argc, argv, "01", &tag);
1208 PUSH_TAG();
1210 th->tag->tag = tag;
1212 if ((state = EXEC_TAG()) == 0) {
1213 val = rb_yield_0(1, &tag);
1215 else if (state == TAG_THROW && RNODE(th->errinfo)->u1.value == tag) {
1216 th->cfp = saved_cfp;
1217 val = th->tag->retval;
1218 th->errinfo = Qnil;
1219 state = 0;
1221 POP_TAG();
1222 if (state)
1223 JUMP_TAG(state);
1225 return val;
1228 static VALUE
1229 catch_null_i(VALUE dmy)
1231 return rb_funcall(Qnil, rb_intern("catch"), 0, 0);
1234 static VALUE
1235 catch_i(VALUE tag)
1237 return rb_funcall(Qnil, rb_intern("catch"), 1, tag);
1240 VALUE
1241 rb_catch(const char *tag, VALUE (*func)(), VALUE data)
1243 if (!tag) {
1244 return rb_iterate(catch_null_i, 0, func, data);
1246 return rb_iterate(catch_i, ID2SYM(rb_intern(tag)), func, data);
1249 VALUE
1250 rb_catch_obj(VALUE tag, VALUE (*func)(), VALUE data)
1252 return rb_iterate((VALUE (*)_((VALUE)))catch_i, tag, func, data);
1256 * call-seq:
1257 * caller(start=1) => array
1259 * Returns the current execution stack---an array containing strings in
1260 * the form ``<em>file:line</em>'' or ``<em>file:line: in
1261 * `method'</em>''. The optional _start_ parameter
1262 * determines the number of initial stack entries to omit from the
1263 * result.
1265 * def a(skip)
1266 * caller(skip)
1267 * end
1268 * def b(skip)
1269 * a(skip)
1270 * end
1271 * def c(skip)
1272 * b(skip)
1273 * end
1274 * c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
1275 * c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
1276 * c(2) #=> ["prog:8:in `c'", "prog:12"]
1277 * c(3) #=> ["prog:13"]
1280 static VALUE
1281 rb_f_caller(int argc, VALUE *argv)
1283 VALUE level;
1284 int lev;
1286 rb_scan_args(argc, argv, "01", &level);
1288 if (NIL_P(level))
1289 lev = 1;
1290 else
1291 lev = NUM2INT(level);
1292 if (lev < 0)
1293 rb_raise(rb_eArgError, "negative level (%d)", lev);
1295 return vm_backtrace(GET_THREAD(), lev);
1298 void
1299 rb_backtrace(void)
1301 long i;
1302 VALUE ary;
1304 ary = vm_backtrace(GET_THREAD(), -1);
1305 for (i = 0; i < RARRAY_LEN(ary); i++) {
1306 printf("\tfrom %s\n", RSTRING_PTR(RARRAY_PTR(ary)[i]));
1310 VALUE
1311 rb_make_backtrace(void)
1313 return vm_backtrace(GET_THREAD(), -1);
1316 void
1317 Init_vm_eval(void)
1319 rb_define_global_function("catch", rb_f_catch, -1);
1320 rb_define_global_function("throw", rb_f_throw, -1);
1322 rb_define_global_function("loop", rb_f_loop, 0);
1324 rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval, -1);
1325 rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec, -1);
1326 rb_define_private_method(rb_cBasicObject, "method_missing", rb_method_missing, -1);
1328 rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1);
1329 rb_define_method(rb_mKernel, "send", rb_f_send, -1);
1330 rb_define_method(rb_mKernel, "public_send", rb_f_public_send, -1);
1332 rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec, -1);
1333 rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec, -1);
1335 rb_define_global_function("caller", rb_f_caller, -1);