* transcode.c (trans_open_i): check the result of rb_transcoding_open.
[ruby-svn.git] / vm_eval.c
blob96a189ae85b6192ff5f824d0566f1057ba8df0a8
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, result, argv_ary = 0;
152 if (argc < 0x100) {
153 argv_m = ALLOCA_N(VALUE, argc+1);
155 else {
156 argv_ary = rb_ary_tmp_new(argc+1);
157 argv_m = RARRAY_PTR(argv_ary);
159 MEMCPY(argv_m + 1, argv, VALUE, argc);
160 argv_m[0] = ID2SYM(id);
161 th->method_missing_reason = 0;
162 th->passed_block = 0;
163 result = rb_funcall2(recv, idMethodMissing, argc + 1, argv_m);
164 if (argv_ary) rb_ary_clear(argv_ary);
165 return result;
168 return vm_call0(th, klass, recv, id, id, argc, argv, body, CALL_SUPER);
171 VALUE
172 rb_call_super(int argc, const VALUE *argv)
174 PASS_PASSED_BLOCK();
175 return vm_call_super(GET_THREAD(), argc, argv);
178 static inline void
179 stack_check(void)
181 rb_thread_t *th = GET_THREAD();
183 if (!rb_thread_raised_p(th, RAISED_STACKOVERFLOW) && ruby_stack_check()) {
184 rb_thread_raised_set(th, RAISED_STACKOVERFLOW);
185 rb_exc_raise(sysstack_error);
189 static inline VALUE
190 rb_call0(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv,
191 int scope, VALUE self)
193 NODE *body, *method;
194 int noex;
195 ID id = mid;
196 struct cache_entry *ent;
197 rb_thread_t *th = GET_THREAD();
199 if (!klass) {
200 rb_raise(rb_eNotImpError,
201 "method `%s' called on terminated object (%p)",
202 rb_id2name(mid), (void *)recv);
204 /* is it in the method cache? */
205 ent = cache + EXPR1(klass, mid);
207 if (ent->mid == mid && ent->klass == klass) {
208 if (!ent->method)
209 return method_missing(recv, mid, argc, argv,
210 scope == 2 ? NOEX_VCALL : 0);
211 id = ent->mid0;
212 noex = ent->method->nd_noex;
213 klass = ent->method->nd_clss;
214 body = ent->method->nd_body;
216 else if ((method = rb_get_method_body(klass, id, &id)) != 0) {
217 noex = method->nd_noex;
218 klass = method->nd_clss;
219 body = method->nd_body;
221 else {
222 if (scope == 3) {
223 return method_missing(recv, mid, argc, argv, NOEX_SUPER);
225 return method_missing(recv, mid, argc, argv,
226 scope == 2 ? NOEX_VCALL : 0);
230 if (mid != missing) {
231 /* receiver specified form for private method */
232 if (UNLIKELY(noex)) {
233 if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == 0) {
234 return method_missing(recv, mid, argc, argv, NOEX_PRIVATE);
237 /* self must be kind of a specified form for protected method */
238 if (((noex & NOEX_MASK) & NOEX_PROTECTED) && scope == 0) {
239 VALUE defined_class = klass;
241 if (TYPE(defined_class) == T_ICLASS) {
242 defined_class = RBASIC(defined_class)->klass;
245 if (self == Qundef) {
246 self = th->cfp->self;
248 if (!rb_obj_is_kind_of(self, rb_class_real(defined_class))) {
249 return method_missing(recv, mid, argc, argv, NOEX_PROTECTED);
253 if (NOEX_SAFE(noex) > th->safe_level) {
254 rb_raise(rb_eSecurityError, "calling insecure method: %s", rb_id2name(mid));
259 stack_check();
260 return vm_call0(th, klass, recv, mid, id, argc, argv, body, noex & NOEX_NOSUPER);
263 static inline VALUE
264 rb_call(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv, int scope)
266 return rb_call0(klass, recv, mid, argc, argv, scope, Qundef);
270 * call-seq:
271 * obj.method_missing(symbol [, *args] ) => result
273 * Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
274 * <i>symbol</i> is the symbol for the method called, and <i>args</i>
275 * are any arguments that were passed to it. By default, the interpreter
276 * raises an error when this method is called. However, it is possible
277 * to override the method to provide more dynamic behavior.
278 * If it is decided that a particular method should not be handled, then
279 * <i>super</i> should be called, so that ancestors can pick up the
280 * missing method.
281 * The example below creates
282 * a class <code>Roman</code>, which responds to methods with names
283 * consisting of roman numerals, returning the corresponding integer
284 * values.
286 * class Roman
287 * def romanToInt(str)
288 * # ...
289 * end
290 * def method_missing(methId)
291 * str = methId.id2name
292 * romanToInt(str)
293 * end
294 * end
296 * r = Roman.new
297 * r.iv #=> 4
298 * r.xxiii #=> 23
299 * r.mm #=> 2000
302 static VALUE
303 rb_method_missing(int argc, const VALUE *argv, VALUE obj)
305 ID id;
306 VALUE exc = rb_eNoMethodError;
307 const char *format = 0;
308 rb_thread_t *th = GET_THREAD();
309 int last_call_status = th->method_missing_reason;
310 if (argc == 0 || !SYMBOL_P(argv[0])) {
311 rb_raise(rb_eArgError, "no id given");
314 stack_check();
316 id = SYM2ID(argv[0]);
318 if (last_call_status & NOEX_PRIVATE) {
319 format = "private method `%s' called for %s";
321 else if (last_call_status & NOEX_PROTECTED) {
322 format = "protected method `%s' called for %s";
324 else if (last_call_status & NOEX_VCALL) {
325 format = "undefined local variable or method `%s' for %s";
326 exc = rb_eNameError;
328 else if (last_call_status & NOEX_SUPER) {
329 format = "super: no superclass method `%s' for %s";
331 if (!format) {
332 format = "undefined method `%s' for %s";
336 int n = 0;
337 VALUE args[3];
338 args[n++] = rb_funcall(rb_const_get(exc, rb_intern("message")), '!',
339 3, rb_str_new2(format), obj, argv[0]);
340 args[n++] = argv[0];
341 if (exc == rb_eNoMethodError) {
342 args[n++] = rb_ary_new4(argc - 1, argv + 1);
344 exc = rb_class_new_instance(n, args, exc);
346 th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp);
347 rb_exc_raise(exc);
350 return Qnil; /* not reached */
353 static inline VALUE
354 method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status)
356 VALUE *nargv;
357 GET_THREAD()->method_missing_reason = call_status;
359 if (id == missing) {
360 rb_method_missing(argc, argv, obj);
362 else if (id == ID_ALLOCATOR) {
363 rb_raise(rb_eTypeError, "allocator undefined for %s",
364 rb_class2name(obj));
367 nargv = ALLOCA_N(VALUE, argc + 1);
368 nargv[0] = ID2SYM(id);
369 MEMCPY(nargv + 1, argv, VALUE, argc);
371 return rb_funcall2(obj, missing, argc + 1, nargv);
374 VALUE
375 rb_apply(VALUE recv, ID mid, VALUE args)
377 int argc;
378 VALUE *argv;
380 argc = RARRAY_LEN(args); /* Assigns LONG, but argc is INT */
381 argv = ALLOCA_N(VALUE, argc);
382 MEMCPY(argv, RARRAY_PTR(args), VALUE, argc);
383 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL);
386 VALUE
387 rb_funcall(VALUE recv, ID mid, int n, ...)
389 VALUE *argv;
390 va_list ar;
391 va_init_list(ar, n);
393 if (n > 0) {
394 long i;
396 argv = ALLOCA_N(VALUE, n);
398 for (i = 0; i < n; i++) {
399 argv[i] = va_arg(ar, VALUE);
401 va_end(ar);
403 else {
404 argv = 0;
406 return rb_call(CLASS_OF(recv), recv, mid, n, argv, CALL_FCALL);
409 VALUE
410 rb_funcall2(VALUE recv, ID mid, int argc, const VALUE *argv)
412 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL);
415 VALUE
416 rb_funcall3(VALUE recv, ID mid, int argc, const VALUE *argv)
418 return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_PUBLIC);
421 static VALUE
422 send_internal(int argc, VALUE *argv, VALUE recv, int scope)
424 VALUE vid;
425 VALUE self = RUBY_VM_PREVIOUS_CONTROL_FRAME(GET_THREAD()->cfp)->self;
426 rb_thread_t *th = GET_THREAD();
428 if (argc == 0) {
429 rb_raise(rb_eArgError, "no method name given");
432 vid = *argv++; argc--;
433 PASS_PASSED_BLOCK_TH(th);
435 return rb_call0(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, scope, self);
439 * call-seq:
440 * obj.send(symbol [, args...]) => obj
441 * obj.__send__(symbol [, args...]) => obj
443 * Invokes the method identified by _symbol_, passing it any
444 * arguments specified. You can use <code>__send__</code> if the name
445 * +send+ clashes with an existing method in _obj_.
447 * class Klass
448 * def hello(*args)
449 * "Hello " + args.join(' ')
450 * end
451 * end
452 * k = Klass.new
453 * k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
456 VALUE
457 rb_f_send(int argc, VALUE *argv, VALUE recv)
459 return send_internal(argc, argv, recv, NOEX_NOSUPER | NOEX_PRIVATE);
463 * call-seq:
464 * obj.public_send(symbol [, args...]) => obj
466 * Invokes the method identified by _symbol_, passing it any
467 * arguments specified. Unlike send, public_send calls public
468 * methods only.
470 * 1.public_send(:puts, "hello") # causes NoMethodError
473 VALUE
474 rb_f_public_send(int argc, VALUE *argv, VALUE recv)
476 return send_internal(argc, argv, recv, NOEX_PUBLIC);
479 /* yield */
481 static inline VALUE
482 rb_yield_0(int argc, const VALUE * argv)
484 return vm_yield(GET_THREAD(), argc, argv);
487 VALUE
488 rb_yield(VALUE val)
490 if (val == Qundef) {
491 return rb_yield_0(0, 0);
493 else {
494 return rb_yield_0(1, &val);
498 VALUE
499 rb_yield_values(int n, ...)
501 if (n == 0) {
502 return rb_yield_0(0, 0);
504 else {
505 int i;
506 VALUE *argv;
507 va_list args;
508 argv = ALLOCA_N(VALUE, n);
510 va_init_list(args, n);
511 for (i=0; i<n; i++) {
512 argv[i] = va_arg(args, VALUE);
514 va_end(args);
516 return rb_yield_0(n, argv);
520 VALUE
521 rb_yield_values2(int argc, const VALUE *argv)
523 return rb_yield_0(argc, argv);
526 VALUE
527 rb_yield_splat(VALUE values)
529 VALUE tmp = rb_check_array_type(values);
530 volatile VALUE v;
531 if (NIL_P(tmp)) {
532 rb_raise(rb_eArgError, "not an array");
534 v = rb_yield_0(RARRAY_LEN(tmp), RARRAY_PTR(tmp));
535 return v;
538 static VALUE
539 loop_i(void)
541 for (;;) {
542 rb_yield_0(0, 0);
544 return Qnil;
548 * call-seq:
549 * loop {|| block }
551 * Repeatedly executes the block.
553 * loop do
554 * print "Input: "
555 * line = gets
556 * break if !line or line =~ /^qQ/
557 * # ...
558 * end
560 * StopIteration raised in the block breaks the loop.
563 static VALUE
564 rb_f_loop(void)
566 rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0);
567 return Qnil; /* dummy */
570 VALUE
571 rb_iterate(VALUE (* it_proc) (VALUE), VALUE data1,
572 VALUE (* bl_proc) (ANYARGS), VALUE data2)
574 int state;
575 volatile VALUE retval = Qnil;
576 NODE *node = NEW_IFUNC(bl_proc, data2);
577 rb_thread_t *th = GET_THREAD();
578 rb_control_frame_t *cfp = th->cfp;
580 TH_PUSH_TAG(th);
581 state = TH_EXEC_TAG();
582 if (state == 0) {
583 iter_retry:
585 rb_block_t *blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP(th->cfp);
586 blockptr->iseq = (void *)node;
587 blockptr->proc = 0;
588 th->passed_block = blockptr;
590 retval = (*it_proc) (data1);
592 else {
593 VALUE err = th->errinfo;
594 if (state == TAG_BREAK) {
595 VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err);
596 VALUE *cdfp = cfp->dfp;
598 if (cdfp == escape_dfp) {
599 state = 0;
600 th->state = 0;
601 th->errinfo = Qnil;
602 th->cfp = cfp;
604 else{
605 /* SDR(); printf("%p, %p\n", cdfp, escape_dfp); */
608 else if (state == TAG_RETRY) {
609 VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err);
610 VALUE *cdfp = cfp->dfp;
612 if (cdfp == escape_dfp) {
613 state = 0;
614 th->state = 0;
615 th->errinfo = Qnil;
616 th->cfp = cfp;
617 goto iter_retry;
621 TH_POP_TAG();
623 switch (state) {
624 case 0:
625 break;
626 default:
627 TH_JUMP_TAG(th, state);
629 return retval;
632 struct iter_method_arg {
633 VALUE obj;
634 ID mid;
635 int argc;
636 VALUE *argv;
639 static VALUE
640 iterate_method(VALUE obj)
642 const struct iter_method_arg * arg =
643 (struct iter_method_arg *) obj;
645 return rb_call(CLASS_OF(arg->obj), arg->obj, arg->mid,
646 arg->argc, arg->argv, CALL_FCALL);
649 VALUE
650 rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv,
651 VALUE (*bl_proc) (ANYARGS), VALUE data2)
653 struct iter_method_arg arg;
655 arg.obj = obj;
656 arg.mid = mid;
657 arg.argc = argc;
658 arg.argv = argv;
659 return rb_iterate(iterate_method, (VALUE)&arg, bl_proc, data2);
662 VALUE
663 rb_each(VALUE obj)
665 return rb_call(CLASS_OF(obj), obj, idEach, 0, 0, CALL_FCALL);
668 static VALUE
669 eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, const char *file, int line)
671 int state;
672 VALUE result = Qundef;
673 VALUE envval;
674 rb_binding_t *bind = 0;
675 rb_thread_t *th = GET_THREAD();
676 rb_env_t *env = NULL;
677 rb_block_t block;
678 volatile int parse_in_eval;
679 volatile int mild_compile_error;
681 if (file == 0) {
682 file = rb_sourcefile();
683 line = rb_sourceline();
686 parse_in_eval = th->parse_in_eval;
687 mild_compile_error = th->mild_compile_error;
688 PUSH_TAG();
689 if ((state = EXEC_TAG()) == 0) {
690 rb_iseq_t *iseq;
691 volatile VALUE iseqval;
693 if (scope != Qnil) {
694 if (rb_obj_is_kind_of(scope, rb_cBinding)) {
695 GetBindingPtr(scope, bind);
696 envval = bind->env;
698 else {
699 rb_raise(rb_eTypeError,
700 "wrong argument type %s (expected Binding)",
701 rb_obj_classname(scope));
703 GetEnvPtr(envval, env);
704 th->base_block = &env->block;
706 else {
707 rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(th, th->cfp);
709 if (cfp != 0) {
710 block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp);
711 th->base_block = &block;
712 th->base_block->self = self;
713 th->base_block->iseq = cfp->iseq; /* TODO */
715 else {
716 rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread");
720 /* make eval iseq */
721 th->parse_in_eval++;
722 th->mild_compile_error++;
723 iseqval = rb_iseq_compile(src, rb_str_new2(file), INT2FIX(line));
724 th->mild_compile_error--;
725 th->parse_in_eval--;
727 vm_set_eval_stack(th, iseqval, cref);
728 th->base_block = 0;
730 if (0) { /* for debug */
731 extern VALUE ruby_iseq_disasm(VALUE);
732 printf("%s\n", RSTRING_PTR(ruby_iseq_disasm(iseqval)));
735 /* save new env */
736 GetISeqPtr(iseqval, iseq);
737 if (bind && iseq->local_size > 0) {
738 bind->env = vm_make_env_object(th, th->cfp);
741 /* kick */
742 CHECK_STACK_OVERFLOW(th->cfp, iseq->stack_max);
743 result = vm_eval_body(th);
745 POP_TAG();
746 th->mild_compile_error = mild_compile_error;
747 th->parse_in_eval = parse_in_eval;
749 if (state) {
750 if (state == TAG_RAISE) {
751 VALUE errinfo = th->errinfo;
752 if (strcmp(file, "(eval)") == 0) {
753 VALUE mesg, errat, bt2;
754 extern VALUE rb_get_backtrace(VALUE info);
756 errat = rb_get_backtrace(errinfo);
757 mesg = rb_attr_get(errinfo, rb_intern("mesg"));
758 if (!NIL_P(errat) && TYPE(errat) == T_ARRAY &&
759 (bt2 = vm_backtrace(th, -2), RARRAY_LEN(bt2) > 0)) {
760 if (!NIL_P(mesg) && TYPE(mesg) == T_STRING && !RSTRING_LEN(mesg)) {
761 rb_str_update(mesg, 0, 0, rb_str_new2(": "));
762 rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]);
764 RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0];
767 rb_exc_raise(errinfo);
769 JUMP_TAG(state);
771 return result;
774 static VALUE
775 eval_string(VALUE self, VALUE src, VALUE scope, const char *file, int line)
777 return eval_string_with_cref(self, src, scope, 0, file, line);
781 * call-seq:
782 * eval(string [, binding [, filename [,lineno]]]) => obj
784 * Evaluates the Ruby expression(s) in <em>string</em>. If
785 * <em>binding</em> is given, the evaluation is performed in its
786 * context. The binding may be a <code>Binding</code> object or a
787 * <code>Proc</code> object. If the optional <em>filename</em> and
788 * <em>lineno</em> parameters are present, they will be used when
789 * reporting syntax errors.
791 * def getBinding(str)
792 * return binding
793 * end
794 * str = "hello"
795 * eval "str + ' Fred'" #=> "hello Fred"
796 * eval "str + ' Fred'", getBinding("bye") #=> "bye Fred"
799 VALUE
800 rb_f_eval(int argc, VALUE *argv, VALUE self)
802 VALUE src, scope, vfile, vline;
803 const char *file = "(eval)";
804 int line = 1;
806 rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
807 if (rb_safe_level() >= 4) {
808 StringValue(src);
809 if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
810 rb_raise(rb_eSecurityError,
811 "Insecure: can't modify trusted binding");
814 else {
815 SafeStringValue(src);
817 if (argc >= 3) {
818 StringValue(vfile);
820 if (argc >= 4) {
821 line = NUM2INT(vline);
824 if (!NIL_P(vfile))
825 file = RSTRING_PTR(vfile);
826 return eval_string(self, src, scope, file, line);
829 VALUE
830 rb_eval_string(const char *str)
832 return eval_string(rb_vm_top_self(), rb_str_new2(str), Qnil, "(eval)", 1);
835 VALUE
836 rb_eval_string_protect(const char *str, int *state)
838 return rb_protect((VALUE (*)(VALUE))rb_eval_string, (VALUE)str, state);
841 VALUE
842 rb_eval_string_wrap(const char *str, int *state)
844 int status;
845 rb_thread_t *th = GET_THREAD();
846 VALUE self = th->top_self;
847 VALUE wrapper = th->top_wrapper;
848 VALUE val;
850 th->top_wrapper = rb_module_new();
851 th->top_self = rb_obj_clone(rb_vm_top_self());
852 rb_extend_object(th->top_self, th->top_wrapper);
854 val = rb_eval_string_protect(str, &status);
856 th->top_self = self;
857 th->top_wrapper = wrapper;
859 if (state) {
860 *state = status;
862 else if (status) {
863 JUMP_TAG(status);
865 return val;
868 VALUE
869 rb_eval_cmd(VALUE cmd, VALUE arg, int level)
871 int state;
872 VALUE val = Qnil; /* OK */
873 volatile int safe = rb_safe_level();
875 if (OBJ_TAINTED(cmd)) {
876 level = 4;
879 if (TYPE(cmd) != T_STRING) {
880 PUSH_TAG();
881 rb_set_safe_level_force(level);
882 if ((state = EXEC_TAG()) == 0) {
883 val = rb_funcall2(cmd, rb_intern("call"), RARRAY_LEN(arg),
884 RARRAY_PTR(arg));
886 POP_TAG();
888 rb_set_safe_level_force(safe);
890 if (state)
891 JUMP_TAG(state);
892 return val;
895 PUSH_TAG();
896 if ((state = EXEC_TAG()) == 0) {
897 val = eval_string(rb_vm_top_self(), cmd, Qnil, 0, 0);
899 POP_TAG();
901 rb_set_safe_level_force(safe);
902 if (state) vm_jump_tag_but_local_jump(state, val);
903 return val;
906 /* block eval under the class/module context */
908 static VALUE
909 yield_under(VALUE under, VALUE self, VALUE values)
911 rb_thread_t *th = GET_THREAD();
912 rb_block_t block, *blockptr;
913 NODE *cref = vm_cref_push(th, under, NOEX_PUBLIC);
915 if ((blockptr = GC_GUARDED_PTR_REF(th->cfp->lfp[0])) != 0) {
916 block = *blockptr;
917 block.self = self;
918 th->cfp->lfp[0] = GC_GUARDED_PTR(&block);
921 if (values == Qundef) {
922 return vm_yield_with_cref(th, 0, 0, cref);
924 else {
925 return vm_yield_with_cref(th, RARRAY_LEN(values), RARRAY_PTR(values), cref);
929 /* string eval under the class/module context */
930 static VALUE
931 eval_under(VALUE under, VALUE self, VALUE src, const char *file, int line)
933 NODE *cref = vm_cref_push(GET_THREAD(), under, NOEX_PUBLIC);
935 if (rb_safe_level() >= 4) {
936 StringValue(src);
938 else {
939 SafeStringValue(src);
942 return eval_string_with_cref(self, src, Qnil, cref, file, line);
945 static VALUE
946 specific_eval(int argc, VALUE *argv, VALUE klass, VALUE self)
948 if (rb_block_given_p()) {
949 if (argc > 0) {
950 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
952 return yield_under(klass, self, Qundef);
954 else {
955 const char *file = "(eval)";
956 int line = 1;
958 if (argc == 0) {
959 rb_raise(rb_eArgError, "block not supplied");
961 else {
962 if (rb_safe_level() >= 4) {
963 StringValue(argv[0]);
965 else {
966 SafeStringValue(argv[0]);
968 if (argc > 3) {
969 const char *name = rb_id2name(rb_frame_callee());
970 rb_raise(rb_eArgError,
971 "wrong number of arguments: %s(src) or %s{..}",
972 name, name);
974 if (argc > 2)
975 line = NUM2INT(argv[2]);
976 if (argc > 1) {
977 file = StringValuePtr(argv[1]);
980 return eval_under(klass, self, argv[0], file, line);
985 * call-seq:
986 * obj.instance_eval(string [, filename [, lineno]] ) => obj
987 * obj.instance_eval {| | block } => obj
989 * Evaluates a string containing Ruby source code, or the given block,
990 * within the context of the receiver (_obj_). In order to set the
991 * context, the variable +self+ is set to _obj_ while
992 * the code is executing, giving the code access to _obj_'s
993 * instance variables. In the version of <code>instance_eval</code>
994 * that takes a +String+, the optional second and third
995 * parameters supply a filename and starting line number that are used
996 * when reporting compilation errors.
998 * class KlassWithSecret
999 * def initialize
1000 * @secret = 99
1001 * end
1002 * end
1003 * k = KlassWithSecret.new
1004 * k.instance_eval { @secret } #=> 99
1007 VALUE
1008 rb_obj_instance_eval(int argc, VALUE *argv, VALUE self)
1010 VALUE klass;
1012 if (SPECIAL_CONST_P(self)) {
1013 klass = Qnil;
1015 else {
1016 klass = rb_singleton_class(self);
1018 return specific_eval(argc, argv, klass, self);
1022 * call-seq:
1023 * obj.instance_exec(arg...) {|var...| block } => obj
1025 * Executes the given block within the context of the receiver
1026 * (_obj_). In order to set the context, the variable +self+ is set
1027 * to _obj_ while the code is executing, giving the code access to
1028 * _obj_'s instance variables. Arguments are passed as block parameters.
1030 * class KlassWithSecret
1031 * def initialize
1032 * @secret = 99
1033 * end
1034 * end
1035 * k = KlassWithSecret.new
1036 * k.instance_exec(5) {|x| @secret+x } #=> 104
1039 VALUE
1040 rb_obj_instance_exec(int argc, VALUE *argv, VALUE self)
1042 VALUE klass;
1044 if (SPECIAL_CONST_P(self)) {
1045 klass = Qnil;
1047 else {
1048 klass = rb_singleton_class(self);
1050 return yield_under(klass, self, rb_ary_new4(argc, argv));
1054 * call-seq:
1055 * mod.class_eval(string [, filename [, lineno]]) => obj
1056 * mod.module_eval {|| block } => obj
1058 * Evaluates the string or block in the context of _mod_. This can
1059 * be used to add methods to a class. <code>module_eval</code> returns
1060 * the result of evaluating its argument. The optional _filename_
1061 * and _lineno_ parameters set the text for error messages.
1063 * class Thing
1064 * end
1065 * a = %q{def hello() "Hello there!" end}
1066 * Thing.module_eval(a)
1067 * puts Thing.new.hello()
1068 * Thing.module_eval("invalid code", "dummy", 123)
1070 * <em>produces:</em>
1072 * Hello there!
1073 * dummy:123:in `module_eval': undefined local variable
1074 * or method `code' for Thing:Class
1077 VALUE
1078 rb_mod_module_eval(int argc, VALUE *argv, VALUE mod)
1080 return specific_eval(argc, argv, mod, mod);
1084 * call-seq:
1085 * mod.module_exec(arg...) {|var...| block } => obj
1086 * mod.class_exec(arg...) {|var...| block } => obj
1088 * Evaluates the given block in the context of the class/module.
1089 * The method defined in the block will belong to the receiver.
1091 * class Thing
1092 * end
1093 * Thing.class_exec{
1094 * def hello() "Hello there!" end
1096 * puts Thing.new.hello()
1098 * <em>produces:</em>
1100 * Hello there!
1103 VALUE
1104 rb_mod_module_exec(int argc, VALUE *argv, VALUE mod)
1106 return yield_under(mod, mod, rb_ary_new4(argc, argv));
1109 NORETURN(static VALUE rb_f_throw _((int, VALUE *)));
1112 * call-seq:
1113 * throw(symbol [, obj])
1115 * Transfers control to the end of the active +catch+ block
1116 * waiting for _symbol_. Raises +NameError+ if there
1117 * is no +catch+ block for the symbol. The optional second
1118 * parameter supplies a return value for the +catch+ block,
1119 * which otherwise defaults to +nil+. For examples, see
1120 * <code>Kernel::catch</code>.
1123 static VALUE
1124 rb_f_throw(int argc, VALUE *argv)
1126 VALUE tag, value;
1127 rb_thread_t *th = GET_THREAD();
1128 struct rb_vm_tag *tt = th->tag;
1130 rb_scan_args(argc, argv, "11", &tag, &value);
1131 while (tt) {
1132 if (tt->tag == tag) {
1133 tt->retval = value;
1134 break;
1136 tt = tt->prev;
1138 if (!tt) {
1139 VALUE desc = rb_inspect(tag);
1140 rb_raise(rb_eArgError, "uncaught throw %s", RSTRING_PTR(desc));
1142 rb_trap_restore_mask();
1143 th->errinfo = NEW_THROW_OBJECT(tag, 0, TAG_THROW);
1145 JUMP_TAG(TAG_THROW);
1146 #ifndef __GNUC__
1147 return Qnil; /* not reached */
1148 #endif
1151 void
1152 rb_throw(const char *tag, VALUE val)
1154 VALUE argv[2];
1156 argv[0] = ID2SYM(rb_intern(tag));
1157 argv[1] = val;
1158 rb_f_throw(2, argv);
1161 void
1162 rb_throw_obj(VALUE tag, VALUE val)
1164 VALUE argv[2];
1166 argv[0] = tag;
1167 argv[1] = val;
1168 rb_f_throw(2, argv);
1172 * call-seq:
1173 * catch(symbol) {| | block } > obj
1175 * +catch+ executes its block. If a +throw+ is
1176 * executed, Ruby searches up its stack for a +catch+ block
1177 * with a tag corresponding to the +throw+'s
1178 * _symbol_. If found, that block is terminated, and
1179 * +catch+ returns the value given to +throw+. If
1180 * +throw+ is not called, the block terminates normally, and
1181 * the value of +catch+ is the value of the last expression
1182 * evaluated. +catch+ expressions may be nested, and the
1183 * +throw+ call need not be in lexical scope.
1185 * def routine(n)
1186 * puts n
1187 * throw :done if n <= 0
1188 * routine(n-1)
1189 * end
1192 * catch(:done) { routine(3) }
1194 * <em>produces:</em>
1202 static VALUE
1203 rb_f_catch(int argc, VALUE *argv)
1205 VALUE tag;
1206 int state;
1207 VALUE val = Qnil; /* OK */
1208 rb_thread_t *th = GET_THREAD();
1209 rb_control_frame_t *saved_cfp = th->cfp;
1211 if (argc == 0) {
1212 tag = rb_obj_alloc(rb_cObject);
1214 else {
1215 rb_scan_args(argc, argv, "01", &tag);
1217 PUSH_TAG();
1219 th->tag->tag = tag;
1221 if ((state = EXEC_TAG()) == 0) {
1222 val = rb_yield_0(1, &tag);
1224 else if (state == TAG_THROW && RNODE(th->errinfo)->u1.value == tag) {
1225 th->cfp = saved_cfp;
1226 val = th->tag->retval;
1227 th->errinfo = Qnil;
1228 state = 0;
1230 POP_TAG();
1231 if (state)
1232 JUMP_TAG(state);
1234 return val;
1237 static VALUE
1238 catch_null_i(VALUE dmy)
1240 return rb_funcall(Qnil, rb_intern("catch"), 0, 0);
1243 static VALUE
1244 catch_i(VALUE tag)
1246 return rb_funcall(Qnil, rb_intern("catch"), 1, tag);
1249 VALUE
1250 rb_catch(const char *tag, VALUE (*func)(), VALUE data)
1252 if (!tag) {
1253 return rb_iterate(catch_null_i, 0, func, data);
1255 return rb_iterate(catch_i, ID2SYM(rb_intern(tag)), func, data);
1258 VALUE
1259 rb_catch_obj(VALUE tag, VALUE (*func)(), VALUE data)
1261 return rb_iterate((VALUE (*)_((VALUE)))catch_i, tag, func, data);
1265 * call-seq:
1266 * caller(start=1) => array
1268 * Returns the current execution stack---an array containing strings in
1269 * the form ``<em>file:line</em>'' or ``<em>file:line: in
1270 * `method'</em>''. The optional _start_ parameter
1271 * determines the number of initial stack entries to omit from the
1272 * result.
1274 * def a(skip)
1275 * caller(skip)
1276 * end
1277 * def b(skip)
1278 * a(skip)
1279 * end
1280 * def c(skip)
1281 * b(skip)
1282 * end
1283 * c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
1284 * c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
1285 * c(2) #=> ["prog:8:in `c'", "prog:12"]
1286 * c(3) #=> ["prog:13"]
1289 static VALUE
1290 rb_f_caller(int argc, VALUE *argv)
1292 VALUE level;
1293 int lev;
1295 rb_scan_args(argc, argv, "01", &level);
1297 if (NIL_P(level))
1298 lev = 1;
1299 else
1300 lev = NUM2INT(level);
1301 if (lev < 0)
1302 rb_raise(rb_eArgError, "negative level (%d)", lev);
1304 return vm_backtrace(GET_THREAD(), lev);
1307 void
1308 rb_backtrace(void)
1310 long i;
1311 VALUE ary;
1313 ary = vm_backtrace(GET_THREAD(), -1);
1314 for (i = 0; i < RARRAY_LEN(ary); i++) {
1315 printf("\tfrom %s\n", RSTRING_PTR(RARRAY_PTR(ary)[i]));
1319 VALUE
1320 rb_make_backtrace(void)
1322 return vm_backtrace(GET_THREAD(), -1);
1325 void
1326 Init_vm_eval(void)
1328 rb_define_global_function("catch", rb_f_catch, -1);
1329 rb_define_global_function("throw", rb_f_throw, -1);
1331 rb_define_global_function("loop", rb_f_loop, 0);
1333 rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval, -1);
1334 rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec, -1);
1335 rb_define_private_method(rb_cBasicObject, "method_missing", rb_method_missing, -1);
1337 rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1);
1338 rb_define_method(rb_mKernel, "send", rb_f_send, -1);
1339 rb_define_method(rb_mKernel, "public_send", rb_f_public_send, -1);
1341 rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec, -1);
1342 rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec, -1);
1344 rb_define_global_function("caller", rb_f_caller, -1);