1 /**********************************************************************
3 proc.c - Proc, Binding, Env
6 created at: Wed Jan 17 12:13:14 2007
8 Copyright (C) 2004-2007 Koichi Sasada
10 **********************************************************************/
12 #include "eval_intern.h"
16 VALUE oclass; /* class that holds the method */
17 VALUE rclass; /* class of the receiver */
23 VALUE rb_cUnboundMethod;
28 static VALUE bmcall(VALUE, VALUE);
29 static int method_arity(VALUE);
30 static VALUE rb_obj_is_method(VALUE m);
37 RUBY_FREE_ENTER("proc");
41 RUBY_FREE_LEAVE("proc");
48 RUBY_MARK_ENTER("proc");
51 RUBY_MARK_UNLESS_NULL(proc->envval);
52 RUBY_MARK_UNLESS_NULL(proc->blockprocval);
53 RUBY_MARK_UNLESS_NULL(proc->block.proc);
54 RUBY_MARK_UNLESS_NULL(proc->block.self);
55 if (proc->block.iseq && RUBY_VM_IFUNC_P(proc->block.iseq)) {
56 RUBY_MARK_UNLESS_NULL((VALUE)(proc->block.iseq));
59 RUBY_MARK_LEAVE("proc");
63 rb_proc_alloc(VALUE klass)
67 obj = Data_Make_Struct(klass, rb_proc_t, proc_mark, proc_free, proc);
68 MEMZERO(proc, rb_proc_t, 1);
73 rb_obj_is_proc(VALUE proc)
75 if (TYPE(proc) == T_DATA &&
76 RDATA(proc)->dfree == (RUBY_DATA_FUNC) proc_free) {
87 VALUE procval = rb_proc_alloc(rb_cProc);
89 GetProcPtr(self, src);
90 GetProcPtr(procval, dst);
92 dst->block = src->block;
93 dst->block.proc = procval;
94 dst->envval = src->envval;
95 dst->safe_level = src->safe_level;
96 dst->is_lambda = src->is_lambda;
102 proc_clone(VALUE self)
104 VALUE procval = proc_dup(self);
105 CLONESETUP(procval, self);
111 * prc.lambda? => true or false
113 * Returns true for a Proc object which argument handling is rigid.
114 * Such procs are typically generated by lambda.
116 * A Proc object generated by proc ignore extra arguments.
118 * proc {|a,b| [a,b] }.call(1,2,3) => [1,2]
120 * It provides nil for lacked arguments.
122 * proc {|a,b| [a,b] }.call(1) => [1,nil]
124 * It expand single-array argument.
126 * proc {|a,b| [a,b] }.call([1,2]) => [1,2]
128 * A Proc object generated by lambda doesn't have such tricks.
130 * lambda {|a,b| [a,b] }.call(1,2,3) => ArgumentError
131 * lambda {|a,b| [a,b] }.call(1) => ArgumentError
132 * lambda {|a,b| [a,b] }.call([1,2]) => ArgumentError
134 * Proc#lambda? is a predicate for the tricks.
135 * It returns true if no tricks.
137 * lambda {}.lambda? => true
138 * proc {}.lambda? => false
140 * Proc.new is same as proc.
142 * Proc.new {}.lambda? => false
144 * lambda, proc and Proc.new preserves the tricks of
145 * a Proc object given by & argument.
147 * lambda(&lambda {}).lambda? => true
148 * proc(&lambda {}).lambda? => true
149 * Proc.new(&lambda {}).lambda? => true
151 * lambda(&proc {}).lambda? => false
152 * proc(&proc {}).lambda? => false
153 * Proc.new(&proc {}).lambda? => false
155 * A Proc object generated by & argument has the tricks
157 * def n(&b) b.lambda? end
160 * The & argument preserves the tricks if a Proc object is given
163 * n(&lambda {}) => true
164 * n(&proc {}) => false
165 * n(&Proc.new {}) => false
167 * A Proc object converted from a method has no tricks.
170 * method(:m).to_proc.lambda? => true
172 * n(&method(:m)) => true
173 * n(&method(:m).to_proc) => true
175 * define_method is treated same as method definition.
176 * The defined method has no tricks.
179 * define_method(:d) {}
181 * C.new.e(1,2) => ArgumentError
182 * C.new.method(:d).to_proc.lambda? => true
184 * define_method always defines a method without the tricks,
185 * even if a non-lambda Proc object is given.
186 * This is the only exception which the tricks are not preserved.
189 * define_method(:e, &proc {})
191 * C.new.e(1,2) => ArgumentError
192 * C.new.method(:e).to_proc.lambda? => true
194 * This exception is for a wrapper of define_method.
195 * It eases defining a method defining method which defines a usual method which has no tricks.
198 * def def2(name, &body)
199 * define_method(name, &body)
205 * C.new.f(1,2) => ArgumentError
207 * The wrapper, def2, defines a method which has no tricks.
212 proc_lambda_p(VALUE procval)
215 GetProcPtr(procval, proc);
217 return proc->is_lambda ? Qtrue : Qfalse;
223 binding_free(void *ptr)
226 RUBY_FREE_ENTER("binding");
231 RUBY_FREE_LEAVE("binding");
235 binding_mark(void *ptr)
238 RUBY_MARK_ENTER("binding");
241 RUBY_MARK_UNLESS_NULL(bind->env);
243 RUBY_MARK_LEAVE("binding");
247 binding_alloc(VALUE klass)
251 obj = Data_Make_Struct(klass, rb_binding_t, binding_mark, binding_free, bind);
256 binding_dup(VALUE self)
258 VALUE bindval = binding_alloc(rb_cBinding);
259 rb_binding_t *src, *dst;
260 GetBindingPtr(self, src);
261 GetBindingPtr(bindval, dst);
267 binding_clone(VALUE self)
269 VALUE bindval = binding_dup(self);
270 CLONESETUP(bindval, self);
274 rb_control_frame_t *vm_get_ruby_level_next_cfp(rb_thread_t *th, rb_control_frame_t *cfp);
279 rb_thread_t *th = GET_THREAD();
280 rb_control_frame_t *cfp = vm_get_ruby_level_next_cfp(th, th->cfp);
281 VALUE bindval = binding_alloc(rb_cBinding);
285 rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber.");
288 GetBindingPtr(bindval, bind);
289 bind->env = vm_make_env_object(th, cfp);
295 * binding -> a_binding
297 * Returns a +Binding+ object, describing the variable and
298 * method bindings at the point of call. This object can be used when
299 * calling +eval+ to execute the evaluated command in this
300 * environment. Also see the description of class +Binding+.
302 * def getBinding(param)
305 * b = getBinding("hello")
306 * eval("param", b) #=> "hello"
310 rb_f_binding(VALUE self)
312 return rb_binding_new();
317 * binding.eval(string [, filename [,lineno]]) => obj
319 * Evaluates the Ruby expression(s) in <em>string</em>, in the
320 * <em>binding</em>'s context. If the optional <em>filename</em> and
321 * <em>lineno</em> parameters are present, they will be used when
322 * reporting syntax errors.
324 * def getBinding(param)
327 * b = getBinding("hello")
328 * b.eval("param") #=> "hello"
332 bind_eval(int argc, VALUE *argv, VALUE bindval)
336 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
338 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
342 proc_new(VALUE klass, int is_lambda)
344 VALUE procval = Qnil;
345 rb_thread_t *th = GET_THREAD();
346 rb_control_frame_t *cfp = th->cfp;
349 if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 &&
350 !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) {
352 block = GC_GUARDED_PTR_REF(cfp->lfp[0]);
355 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
357 if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 &&
358 !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) {
360 block = GC_GUARDED_PTR_REF(cfp->lfp[0]);
363 rb_warn("tried to create Proc object without a block");
367 rb_raise(rb_eArgError,
368 "tried to create Proc object without a block");
372 procval = block->proc;
375 if (RBASIC(procval)->klass == klass) {
379 VALUE newprocval = proc_dup(procval);
380 RBASIC(newprocval)->klass = klass;
385 procval = vm_make_proc(th, block, klass);
389 GetProcPtr(procval, proc);
390 proc->is_lambda = Qtrue;
397 * Proc.new {|...| block } => a_proc
400 * Creates a new <code>Proc</code> object, bound to the current
401 * context. <code>Proc::new</code> may be called without a block only
402 * within a method with an attached block, in which case that block is
403 * converted to the <code>Proc</code> object.
408 * proc = proc_from { "hello" }
409 * proc.call #=> "hello"
413 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
415 VALUE block = proc_new(klass, Qfalse);
417 rb_obj_call_init(block, argc, argv);
423 * proc { |...| block } => a_proc
425 * Equivalent to <code>Proc.new</code>.
431 return proc_new(rb_cProc, Qfalse);
435 rb_block_lambda(void)
437 return proc_new(rb_cProc, Qtrue);
443 rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
444 return rb_block_lambda();
449 * lambda { |...| block } => a_proc
451 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
452 * check the number of parameters passed when called.
458 return rb_block_lambda();
461 /* CHECKME: are the argument checking semantics correct? */
465 * prc.call(params,...) => obj
466 * prc[params,...] => obj
467 * prc.(params,...) => obj
469 * Invokes the block, setting the block's parameters to the values in
470 * <i>params</i> using something close to method calling semantics.
471 * Generates a warning if multiple values are passed to a proc that
472 * expects just one (previously this silently converted the parameters
473 * to an array). Note that prc.() invokes prc.call() with the parameters
474 * given. It's a syntax sugar to hide "call".
476 * For procs created using <code>Kernel.proc</code>, generates an
477 * error if the wrong number of parameters
478 * are passed to a proc with multiple parameters. For procs created using
479 * <code>Proc.new</code>, extra parameters are silently discarded.
481 * Returns the value of the last expression evaluated in the block. See
482 * also <code>Proc#yield</code>.
484 * a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
485 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
486 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
487 * a_proc = Proc.new {|a,b| a}
492 * prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
493 * from prog.rb:4:in `call'
501 * Invokes the block, with <i>obj</i> as the block's parameter. It is
502 * to allow a proc object to be a target of when clause in the case statement.
506 proc_call(int argc, VALUE *argv, VALUE procval)
509 rb_block_t *blockptr = 0;
511 GetProcPtr(procval, proc);
513 iseq = proc->block.iseq;
514 if (BUILTIN_TYPE(iseq) == T_NODE || iseq->arg_block != -1) {
515 if (rb_block_given_p()) {
518 procval = rb_block_proc();
519 GetProcPtr(procval, proc);
520 blockptr = &proc->block;
524 return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
525 argc, argv, blockptr);
529 rb_proc_call(VALUE self, VALUE args)
532 GetProcPtr(self, proc);
533 return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
534 RARRAY_LEN(args), RARRAY_PTR(args), 0);
538 rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval)
541 rb_block_t *block = 0;
542 GetProcPtr(self, proc);
544 if (!NIL_P(pass_procval)) {
545 rb_proc_t *pass_proc;
546 GetProcPtr(pass_procval, pass_proc);
547 block = &pass_proc->block;
550 return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
556 * prc.arity -> fixnum
558 * Returns the number of arguments that would not be ignored. If the block
559 * is declared to take no arguments, returns 0. If the block is known
560 * to take exactly n arguments, returns n. If the block has optional
561 * arguments, return -n-1, where n is the number of mandatory
562 * arguments. A <code>proc</code> with no argument declarations
563 * is the same a block declaring <code>||</code> as its arguments.
565 * Proc.new {}.arity #=> 0
566 * Proc.new {||}.arity #=> 0
567 * Proc.new {|a|}.arity #=> 1
568 * Proc.new {|a,b|}.arity #=> 2
569 * Proc.new {|a,b,c|}.arity #=> 3
570 * Proc.new {|*a|}.arity #=> -1
571 * Proc.new {|a,*b|}.arity #=> -2
572 * Proc.new {|a,*b, c|}.arity #=> -3
576 proc_arity(VALUE self)
580 GetProcPtr(self, proc);
581 iseq = proc->block.iseq;
583 if (BUILTIN_TYPE(iseq) != T_NODE) {
584 if (iseq->arg_rest < 0) {
585 return INT2FIX(iseq->argc);
588 return INT2FIX(-(iseq->argc + 1 + iseq->arg_post_len));
592 NODE *node = (NODE *)iseq;
593 if (nd_type(node) == NODE_IFUNC && node->nd_cfnc == bmcall) {
594 /* method(:foo).to_proc.arity */
595 return INT2FIX(method_arity(node->nd_tval));
603 rb_proc_arity(VALUE proc)
605 return FIX2INT(proc_arity(proc));
609 get_proc_iseq(VALUE self)
614 GetProcPtr(self, proc);
615 iseq = proc->block.iseq;
616 if (!RUBY_VM_NORMAL_ISEQ_P(iseq))
622 iseq_location(rb_iseq_t *iseq)
626 if (!iseq) return Qnil;
627 loc[0] = iseq->filename;
628 if (iseq->insn_info_table) {
629 loc[1] = INT2FIX(rb_iseq_first_lineno(iseq));
634 return rb_ary_new4(2, loc);
639 * prc.source_location => [String, Fixnum]
641 * returns the ruby source filename and line number containing this proc
642 * or nil if this proc was not defined in ruby (i.e. native)
646 rb_proc_location(VALUE self)
648 return iseq_location(get_proc_iseq(self));
653 * prc == other_proc => true or false
655 * Return <code>true</code> if <i>prc</i> is the same object as
656 * <i>other_proc</i>, or if they are both procs with the same body.
660 proc_eq(VALUE self, VALUE other)
666 if (TYPE(other) == T_DATA &&
667 RDATA(other)->dmark == proc_mark) {
669 GetProcPtr(self, p1);
670 GetProcPtr(other, p2);
671 if (p1->envval == p2->envval &&
672 p1->block.iseq->iseq_size == p2->block.iseq->iseq_size &&
673 p1->block.iseq->local_size == p2->block.iseq->local_size &&
674 MEMCMP(p1->block.iseq->iseq, p2->block.iseq->iseq, VALUE,
675 p1->block.iseq->iseq_size) == 0) {
685 * prc.hash => integer
687 * Return hash value corresponding to proc body.
691 proc_hash(VALUE self)
695 GetProcPtr(self, proc);
696 hash = (long)proc->block.iseq;
697 hash ^= (long)proc->envval;
698 hash ^= (long)proc->block.lfp >> 16;
699 return INT2FIX(hash);
706 * Shows the unique identifier for this proc, along with
707 * an indication of where the proc was defined.
711 proc_to_s(VALUE self)
715 const char *cname = rb_obj_classname(self);
717 const char *is_lambda;
719 GetProcPtr(self, proc);
720 iseq = proc->block.iseq;
721 is_lambda = proc->is_lambda ? " (lambda)" : "";
723 if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
726 if (iseq->insn_info_table) {
727 line_no = rb_iseq_first_lineno(iseq);
729 str = rb_sprintf("#<%s:%p@%s:%d%s>", cname, (void *)self,
730 RSTRING_PTR(iseq->filename),
734 str = rb_sprintf("#<%s:%p%s>", cname, (void *)proc->block.iseq,
738 if (OBJ_TAINTED(self)) {
748 * Part of the protocol for converting objects to <code>Proc</code>
749 * objects. Instances of class <code>Proc</code> simply return
754 proc_to_proc(VALUE self)
760 bm_mark(struct METHOD *data)
762 rb_gc_mark(data->rclass);
763 rb_gc_mark(data->oclass);
764 rb_gc_mark(data->recv);
765 rb_gc_mark((VALUE)data->body);
769 rb_method_body(VALUE method)
773 if (TYPE(method) == T_DATA &&
774 RDATA(method)->dmark == (RUBY_DATA_FUNC) bm_mark) {
775 Data_Get_Struct(method, struct METHOD, data);
783 NODE *rb_get_method_body(VALUE klass, ID id, ID *idp);
786 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
791 VALUE rclass = klass;
795 if ((body = rb_get_method_body(klass, id, 0)) == 0) {
796 rb_print_undef(rclass, oid, 0);
798 if (scope && (body->nd_noex & NOEX_MASK) != NOEX_PUBLIC) {
799 rb_print_undef(rclass, oid, (body->nd_noex & NOEX_MASK));
802 klass = body->nd_clss;
803 body = body->nd_body;
805 if (nd_type(body) == NODE_ZSUPER) {
806 klass = RCLASS_SUPER(klass);
810 while (rclass != klass &&
811 (FL_TEST(rclass, FL_SINGLETON) || TYPE(rclass) == T_ICLASS)) {
812 rclass = RCLASS_SUPER(rclass);
814 if (TYPE(klass) == T_ICLASS)
815 klass = RBASIC(klass)->klass;
816 method = Data_Make_Struct(mclass, struct METHOD, bm_mark, -1, data);
817 data->oclass = klass;
822 data->rclass = rclass;
824 OBJ_INFECT(method, klass);
830 /**********************************************************************
832 * Document-class : Method
834 * Method objects are created by <code>Object#method</code>, and are
835 * associated with a particular object (not just with a class). They
836 * may be used to invoke the method within the object, and as a block
837 * associated with an iterator. They may also be unbound from one
838 * object (creating an <code>UnboundMethod</code>) and bound to
847 * meth = thing.method(:square)
849 * meth.call(9) #=> 81
850 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
856 * meth == other_meth => true or false
858 * Two method objects are equal if that are bound to the same
859 * object and contain the same body.
864 method_eq(VALUE method, VALUE other)
866 struct METHOD *m1, *m2;
868 if (TYPE(other) != T_DATA
869 || RDATA(other)->dmark != (RUBY_DATA_FUNC) bm_mark)
871 if (CLASS_OF(method) != CLASS_OF(other))
874 Data_Get_Struct(method, struct METHOD, m1);
875 Data_Get_Struct(other, struct METHOD, m2);
877 if (m1->oclass != m2->oclass || m1->rclass != m2->rclass ||
878 m1->recv != m2->recv || m1->body != m2->body)
886 * meth.hash => integer
888 * Return a hash value corresponding to the method object.
892 method_hash(VALUE method)
897 Data_Get_Struct(method, struct METHOD, m);
898 hash = (long)m->oclass;
899 hash ^= (long)m->rclass;
900 hash ^= (long)m->recv;
901 hash ^= (long)m->body;
903 return INT2FIX(hash);
908 * meth.unbind => unbound_method
910 * Dissociates <i>meth</i> from it's current receiver. The resulting
911 * <code>UnboundMethod</code> can subsequently be bound to a new object
912 * of the same class (see <code>UnboundMethod</code>).
916 method_unbind(VALUE obj)
919 struct METHOD *orig, *data;
921 Data_Get_Struct(obj, struct METHOD, orig);
923 Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, -1, data);
924 data->oclass = orig->oclass;
927 data->body = orig->body;
928 data->rclass = orig->rclass;
929 data->oid = orig->oid;
930 OBJ_INFECT(method, obj);
937 * meth.receiver => object
939 * Returns the bound receiver of the method object.
943 method_receiver(VALUE obj)
947 Data_Get_Struct(obj, struct METHOD, data);
953 * meth.name => symbol
955 * Returns the name of the method.
959 method_name(VALUE obj)
963 Data_Get_Struct(obj, struct METHOD, data);
964 return ID2SYM(data->id);
969 * meth.owner => class_or_module
971 * Returns the class or module that defines the method.
975 method_owner(VALUE obj)
979 Data_Get_Struct(obj, struct METHOD, data);
985 * obj.method(sym) => method
987 * Looks up the named method as a receiver in <i>obj</i>, returning a
988 * <code>Method</code> object (or raising <code>NameError</code>). The
989 * <code>Method</code> object acts as a closure in <i>obj</i>'s object
990 * instance, so instance variables and the value of <code>self</code>
998 * "Hello, @iv = #{@iv}"
1003 * m = k.method(:hello)
1004 * m.call #=> "Hello, @iv = 99"
1006 * l = Demo.new('Fred')
1007 * m = l.method("hello")
1008 * m.call #=> "Hello, @iv = Fred"
1012 rb_obj_method(VALUE obj, VALUE vid)
1014 return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qfalse);
1018 rb_obj_public_method(VALUE obj, VALUE vid)
1020 return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qtrue);
1025 * mod.instance_method(symbol) => unbound_method
1027 * Returns an +UnboundMethod+ representing the given
1028 * instance method in _mod_.
1031 * def do_a() print "there, "; end
1032 * def do_d() print "Hello "; end
1033 * def do_e() print "!\n"; end
1034 * def do_v() print "Dave"; end
1036 * ?a => instance_method(:do_a),
1037 * ?d => instance_method(:do_d),
1038 * ?e => instance_method(:do_e),
1039 * ?v => instance_method(:do_v)
1041 * def interpret(string)
1042 * string.each_byte {|b| Dispatcher[b].bind(self).call }
1047 * interpreter = Interpreter.new
1048 * interpreter.interpret('dave')
1050 * <em>produces:</em>
1052 * Hello there, Dave!
1056 rb_mod_instance_method(VALUE mod, VALUE vid)
1058 return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qfalse);
1062 rb_mod_public_instance_method(VALUE mod, VALUE vid)
1064 return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qtrue);
1069 * define_method(symbol, method) => new_method
1070 * define_method(symbol) { block } => proc
1072 * Defines an instance method in the receiver. The _method_
1073 * parameter can be a +Proc+ or +Method+ object.
1074 * If a block is specified, it is used as the method body. This block
1075 * is evaluated using <code>instance_eval</code>, a point that is
1076 * tricky to demonstrate because <code>define_method</code> is private.
1077 * (This is why we resort to the +send+ hack in this example.)
1083 * def create_method(name, &block)
1084 * self.class.send(:define_method, name, &block)
1086 * define_method(:wilma) { puts "Charge it!" }
1089 * define_method(:barney, instance_method(:fred))
1094 * a.create_method(:betty) { p self }
1097 * <em>produces:</em>
1105 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
1110 int noex = NOEX_PUBLIC;
1113 id = rb_to_id(argv[0]);
1114 body = rb_block_lambda();
1116 else if (argc == 2) {
1117 id = rb_to_id(argv[0]);
1119 if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) {
1120 rb_raise(rb_eTypeError,
1121 "wrong argument type %s (expected Proc/Method)",
1122 rb_obj_classname(body));
1126 rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
1129 if (RDATA(body)->dmark == (RUBY_DATA_FUNC) bm_mark) {
1130 struct METHOD *method = (struct METHOD *)DATA_PTR(body);
1131 VALUE rclass = method->rclass;
1132 if (rclass != mod) {
1133 if (FL_TEST(rclass, FL_SINGLETON)) {
1134 rb_raise(rb_eTypeError,
1135 "can't bind singleton method to a different class");
1137 if (!RTEST(rb_class_inherited_p(mod, rclass))) {
1138 rb_raise(rb_eTypeError,
1139 "bind argument must be a subclass of %s",
1140 rb_class2name(rclass));
1143 node = method->body;
1145 else if (rb_obj_is_proc(body)) {
1147 body = proc_dup(body);
1148 GetProcPtr(body, proc);
1149 if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) {
1150 proc->block.iseq->defined_method_id = id;
1151 proc->block.iseq->klass = mod;
1152 proc->is_lambda = Qtrue;
1153 proc->is_from_method = Qtrue;
1155 node = NEW_BMETHOD(body);
1159 rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
1162 /* TODO: visibility */
1164 rb_add_method(mod, id, node, noex);
1169 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
1171 VALUE klass = rb_singleton_class(obj);
1173 return rb_mod_define_method(argc, argv, klass);
1178 * MISSING: documentation
1182 method_clone(VALUE self)
1185 struct METHOD *orig, *data;
1187 Data_Get_Struct(self, struct METHOD, orig);
1188 clone = Data_Make_Struct(CLASS_OF(self), struct METHOD, bm_mark, -1, data);
1189 CLONESETUP(clone, self);
1197 * meth.call(args, ...) => obj
1198 * meth[args, ...] => obj
1200 * Invokes the <i>meth</i> with the specified arguments, returning the
1201 * method's return value.
1203 * m = 12.method("+")
1209 rb_method_call(int argc, VALUE *argv, VALUE method)
1211 VALUE result = Qnil; /* OK */
1212 struct METHOD *data;
1214 volatile int safe = -1;
1216 Data_Get_Struct(method, struct METHOD, data);
1217 if (data->recv == Qundef) {
1218 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
1221 if (OBJ_TAINTED(method)) {
1222 safe = rb_safe_level();
1223 if (rb_safe_level() < 4) {
1224 rb_set_safe_level_force(4);
1227 if ((state = EXEC_TAG()) == 0) {
1228 rb_thread_t *th = GET_THREAD();
1229 VALUE rb_vm_call(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid,
1230 int argc, const VALUE *argv, const NODE *body, int nosuper);
1232 PASS_PASSED_BLOCK_TH(th);
1233 result = rb_vm_call(th, data->oclass, data->recv, data->id, data->oid,
1234 argc, argv, data->body, 0);
1238 rb_set_safe_level_force(safe);
1244 /**********************************************************************
1246 * Document-class: UnboundMethod
1248 * Ruby supports two forms of objectified methods. Class
1249 * <code>Method</code> is used to represent methods that are associated
1250 * with a particular object: these method objects are bound to that
1251 * object. Bound method objects for an object can be created using
1252 * <code>Object#method</code>.
1254 * Ruby also supports unbound methods; methods objects that are not
1255 * associated with a particular object. These can be created either by
1256 * calling <code>Module#instance_method</code> or by calling
1257 * <code>unbind</code> on a bound method object. The result of both of
1258 * these is an <code>UnboundMethod</code> object.
1260 * Unbound methods can only be called after they are bound to an
1261 * object. That object must be be a kind_of? the method's original
1268 * def initialize(side)
1273 * area_un = Square.instance_method(:area)
1275 * s = Square.new(12)
1276 * area = area_un.bind(s)
1279 * Unbound methods are a reference to the method at the time it was
1280 * objectified: subsequent changes to the underlying class will not
1281 * affect the unbound method.
1288 * um = Test.instance_method(:test)
1295 * t.test #=> :modified
1296 * um.bind(t).call #=> :original
1302 * umeth.bind(obj) -> method
1304 * Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
1305 * from which <i>umeth</i> was obtained,
1306 * <code>obj.kind_of?(Klass)</code> must be true.
1310 * puts "In test, class = #{self.class}"
1319 * um = B.instance_method(:test)
1320 * bm = um.bind(C.new)
1322 * bm = um.bind(B.new)
1324 * bm = um.bind(A.new)
1327 * <em>produces:</em>
1329 * In test, class = C
1330 * In test, class = B
1331 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
1336 umethod_bind(VALUE method, VALUE recv)
1338 struct METHOD *data, *bound;
1340 Data_Get_Struct(method, struct METHOD, data);
1341 if (data->rclass != CLASS_OF(recv)) {
1342 if (FL_TEST(data->rclass, FL_SINGLETON)) {
1343 rb_raise(rb_eTypeError,
1344 "singleton method called for a different object");
1346 if (!rb_obj_is_kind_of(recv, data->rclass)) {
1347 rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
1348 rb_class2name(data->rclass));
1352 method = Data_Make_Struct(rb_cMethod, struct METHOD, bm_mark, -1, bound);
1355 bound->rclass = CLASS_OF(recv);
1361 rb_node_arity(NODE* body)
1363 switch (nd_type(body)) {
1365 if (body->nd_argc < 0)
1367 return body->nd_argc;
1375 return rb_proc_arity(body->nd_cval);
1376 case RUBY_VM_METHOD_NODE:
1379 GetISeqPtr((VALUE)body->nd_body, iseq);
1380 if (iseq->arg_rest == -1 && iseq->arg_opts == 0) {
1384 return -(iseq->argc + 1 + iseq->arg_post_len);
1388 rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body));
1394 * meth.arity => fixnum
1396 * Returns an indication of the number of arguments accepted by a
1397 * method. Returns a nonnegative integer for methods that take a fixed
1398 * number of arguments. For Ruby methods that take a variable number of
1399 * arguments, returns -n-1, where n is the number of required
1400 * arguments. For methods written in C, returns -1 if the call takes a
1401 * variable number of arguments.
1406 * def three(*a); end
1407 * def four(a, b); end
1408 * def five(a, b, *c); end
1409 * def six(a, b, *c, &d); end
1412 * c.method(:one).arity #=> 0
1413 * c.method(:two).arity #=> 1
1414 * c.method(:three).arity #=> -1
1415 * c.method(:four).arity #=> 2
1416 * c.method(:five).arity #=> -3
1417 * c.method(:six).arity #=> -3
1419 * "cat".method(:size).arity #=> 0
1420 * "cat".method(:replace).arity #=> 1
1421 * "cat".method(:squeeze).arity #=> -1
1422 * "cat".method(:count).arity #=> -1
1426 method_arity_m(VALUE method)
1428 int n = method_arity(method);
1433 method_arity(VALUE method)
1435 struct METHOD *data;
1437 Data_Get_Struct(method, struct METHOD, data);
1438 return rb_node_arity(data->body);
1442 rb_mod_method_arity(VALUE mod, ID id)
1444 NODE *node = rb_method_node(mod, id);
1445 return rb_node_arity(node);
1449 rb_obj_method_arity(VALUE obj, ID id)
1451 return rb_mod_method_arity(CLASS_OF(obj), id);
1455 get_method_iseq(VALUE method)
1457 struct METHOD *data;
1461 Data_Get_Struct(method, struct METHOD, data);
1463 switch (nd_type(body)) {
1464 case RUBY_VM_METHOD_NODE:
1465 GetISeqPtr((VALUE)body->nd_body, iseq);
1466 if (RUBY_VM_NORMAL_ISEQ_P(iseq)) break;
1475 * meth.source_location => [String, Fixnum]
1477 * returns the ruby source filename and line number containing this method
1478 * or nil if this method was not defined in ruby (i.e. native)
1482 rb_method_location(VALUE method)
1484 return iseq_location(get_method_iseq(method));
1489 * meth.to_s => string
1490 * meth.inspect => string
1492 * Show the name of the underlying method.
1494 * "cat".method(:count).inspect #=> "#<Method: String#count>"
1498 method_inspect(VALUE method)
1500 struct METHOD *data;
1503 const char *sharp = "#";
1505 Data_Get_Struct(method, struct METHOD, data);
1506 str = rb_str_buf_new2("#<");
1507 s = rb_obj_classname(method);
1508 rb_str_buf_cat2(str, s);
1509 rb_str_buf_cat2(str, ": ");
1511 if (FL_TEST(data->oclass, FL_SINGLETON)) {
1512 VALUE v = rb_iv_get(data->oclass, "__attached__");
1514 if (data->recv == Qundef) {
1515 rb_str_buf_append(str, rb_inspect(data->oclass));
1517 else if (data->recv == v) {
1518 rb_str_buf_append(str, rb_inspect(v));
1522 rb_str_buf_append(str, rb_inspect(data->recv));
1523 rb_str_buf_cat2(str, "(");
1524 rb_str_buf_append(str, rb_inspect(v));
1525 rb_str_buf_cat2(str, ")");
1530 rb_str_buf_cat2(str, rb_class2name(data->rclass));
1531 if (data->rclass != data->oclass) {
1532 rb_str_buf_cat2(str, "(");
1533 rb_str_buf_cat2(str, rb_class2name(data->oclass));
1534 rb_str_buf_cat2(str, ")");
1537 rb_str_buf_cat2(str, sharp);
1538 rb_str_append(str, rb_id2str(data->oid));
1539 rb_str_buf_cat2(str, ">");
1547 return rb_funcall(Qnil, rb_intern("proc"), 0);
1551 mlambda(VALUE method)
1553 return rb_funcall(Qnil, rb_intern("lambda"), 0);
1557 bmcall(VALUE args, VALUE method)
1561 if (CLASS_OF(args) != rb_cArray) {
1562 args = rb_ary_new3(1, args);
1566 return rb_method_call(RARRAY_LEN(a), RARRAY_PTR(a), method);
1571 VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */
1574 VALUE procval = rb_iterate(mproc, 0, func, val);
1580 * meth.to_proc => prc
1582 * Returns a <code>Proc</code> object corresponding to this method.
1586 method_proc(VALUE method)
1599 procval = rb_iterate(mlambda, 0, bmcall, method);
1600 GetProcPtr(procval, proc);
1601 proc->is_from_method = 1;
1606 rb_obj_is_method(VALUE m)
1608 if (TYPE(m) == T_DATA && RDATA(m)->dmark == (RUBY_DATA_FUNC) bm_mark) {
1616 * local_jump_error.exit_value => obj
1618 * Returns the exit value associated with this +LocalJumpError+.
1621 localjump_xvalue(VALUE exc)
1623 return rb_iv_get(exc, "@exit_value");
1628 * local_jump_error.reason => symbol
1630 * The reason this block was terminated:
1631 * :break, :redo, :retry, :next, :return, or :noreason.
1635 localjump_reason(VALUE exc)
1637 return rb_iv_get(exc, "@reason");
1642 * prc.binding => binding
1644 * Returns the binding associated with <i>prc</i>. Note that
1645 * <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
1646 * <code>Binding</code> object as its second parameter.
1653 * eval("param", b.binding) #=> 99
1656 proc_binding(VALUE self)
1659 VALUE bindval = binding_alloc(rb_cBinding);
1662 GetProcPtr(self, proc);
1663 GetBindingPtr(bindval, bind);
1665 if (TYPE(proc->block.iseq) == T_NODE) {
1666 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
1669 bind->env = proc->envval;
1673 static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc);
1676 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
1678 VALUE args = rb_ary_new3(3, proc, passed, arity);
1679 rb_ary_freeze(passed);
1680 rb_ary_freeze(args);
1681 return rb_proc_new(curry, args);
1685 curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc)
1687 VALUE proc, passed, arity;
1688 proc = RARRAY_PTR(args)[0];
1689 passed = RARRAY_PTR(args)[1];
1690 arity = RARRAY_PTR(args)[2];
1692 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
1693 rb_ary_freeze(passed);
1695 if(RARRAY_LEN(passed) < FIX2INT(arity)) {
1696 if (!NIL_P(passed_proc)) {
1697 rb_warn("given block not used");
1699 arity = make_curry_proc(proc, passed, arity);
1703 return rb_proc_call_with_block(proc, RARRAY_LEN(passed), RARRAY_PTR(passed), passed_proc);
1709 * prc.curry => a_proc
1710 * prc.curry(arity) => a_proc
1712 * Returns a curried proc. If the optional <i>arity</i> argument is given,
1713 * it determines the number of arguments.
1714 * A curried proc receives some arguments. If a sufficient number of
1715 * arguments are supplied, it passes the supplied arguments to the original
1716 * proc and returns the result. Otherwise, returns another curried proc that
1717 * takes the rest of arguments.
1719 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
1720 * p b.curry[1][2][3] #=> 6
1721 * p b.curry[1, 2][3, 4] #=> 6
1722 * p b.curry(5)[1][2][3][4][5] #=> 6
1723 * p b.curry(5)[1, 2][3, 4][5] #=> 6
1724 * p b.curry(1)[1] #=> 1
1726 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1727 * p b.curry[1][2][3] #=> 6
1728 * p b.curry[1, 2][3, 4] #=> 10
1729 * p b.curry(5)[1][2][3][4][5] #=> 15
1730 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1731 * p b.curry(1)[1] #=> 1
1733 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
1734 * p b.curry[1][2][3] #=> 6
1735 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (4 or 3)
1736 * p b.curry(5) #=> wrong number of arguments (5 or 3)
1737 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1739 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1740 * p b.curry[1][2][3] #=> 6
1741 * p b.curry[1, 2][3, 4] #=> 10
1742 * p b.curry(5)[1][2][3][4][5] #=> 15
1743 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1744 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1747 * p b.curry[] #=> :foo
1750 proc_curry(int argc, VALUE *argv, VALUE self)
1752 int sarity, marity = FIX2INT(proc_arity(self));
1753 VALUE arity, opt = Qfalse;
1756 marity = -marity - 1;
1760 rb_scan_args(argc, argv, "01", &arity);
1762 arity = INT2FIX(marity);
1765 sarity = FIX2INT(arity);
1766 if (proc_lambda_p(self) && (sarity < marity || (sarity > marity && !opt))) {
1767 rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", sarity, marity);
1771 return make_curry_proc(self, rb_ary_new(), arity);
1775 * <code>Proc</code> objects are blocks of code that have been bound to
1776 * a set of local variables. Once bound, the code may be called in
1777 * different contexts and still access those variables.
1779 * def gen_times(factor)
1780 * return Proc.new {|n| n*factor }
1783 * times3 = gen_times(3)
1784 * times5 = gen_times(5)
1786 * times3.call(12) #=> 36
1787 * times5.call(5) #=> 25
1788 * times3.call(times5.call(4)) #=> 60
1796 rb_cProc = rb_define_class("Proc", rb_cObject);
1797 rb_undef_alloc_func(rb_cProc);
1798 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
1799 rb_define_method(rb_cProc, "call", proc_call, -1);
1800 rb_define_method(rb_cProc, "[]", proc_call, -1);
1801 rb_define_method(rb_cProc, "===", proc_call, -1);
1802 rb_define_method(rb_cProc, "yield", proc_call, -1);
1803 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
1804 rb_define_method(rb_cProc, "arity", proc_arity, 0);
1805 rb_define_method(rb_cProc, "clone", proc_clone, 0);
1806 rb_define_method(rb_cProc, "dup", proc_dup, 0);
1807 rb_define_method(rb_cProc, "==", proc_eq, 1);
1808 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
1809 rb_define_method(rb_cProc, "hash", proc_hash, 0);
1810 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
1811 rb_define_method(rb_cProc, "lambda?", proc_lambda_p, 0);
1812 rb_define_method(rb_cProc, "binding", proc_binding, 0);
1813 rb_define_method(rb_cProc, "curry", proc_curry, -1);
1814 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
1817 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
1818 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
1819 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
1821 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
1822 sysstack_error = rb_exc_new3(rb_eSysStackError,
1823 rb_obj_freeze(rb_str_new2("stack level too deep")));
1824 OBJ_TAINT(sysstack_error);
1825 OBJ_FREEZE(sysstack_error);
1827 /* utility functions */
1828 rb_define_global_function("proc", rb_block_proc, 0);
1829 rb_define_global_function("lambda", proc_lambda, 0);
1832 rb_cMethod = rb_define_class("Method", rb_cObject);
1833 rb_undef_alloc_func(rb_cMethod);
1834 rb_undef_method(CLASS_OF(rb_cMethod), "new");
1835 rb_define_method(rb_cMethod, "==", method_eq, 1);
1836 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
1837 rb_define_method(rb_cMethod, "hash", method_hash, 0);
1838 rb_define_method(rb_cMethod, "clone", method_clone, 0);
1839 rb_define_method(rb_cMethod, "call", rb_method_call, -1);
1840 rb_define_method(rb_cMethod, "[]", rb_method_call, -1);
1841 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
1842 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
1843 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
1844 rb_define_method(rb_cMethod, "to_proc", method_proc, 0);
1845 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
1846 rb_define_method(rb_cMethod, "name", method_name, 0);
1847 rb_define_method(rb_cMethod, "owner", method_owner, 0);
1848 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
1849 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
1850 rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
1851 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
1854 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
1855 rb_undef_alloc_func(rb_cUnboundMethod);
1856 rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
1857 rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
1858 rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
1859 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
1860 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
1861 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
1862 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
1863 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
1864 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
1865 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
1866 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
1867 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
1869 /* Module#*_method */
1870 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
1871 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
1872 rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
1875 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
1879 * Objects of class <code>Binding</code> encapsulate the execution
1880 * context at some particular place in the code and retain this context
1881 * for future use. The variables, methods, value of <code>self</code>,
1882 * and possibly an iterator block that can be accessed in this context
1883 * are all retained. Binding objects can be created using
1884 * <code>Kernel#binding</code>, and are made available to the callback
1885 * of <code>Kernel#set_trace_func</code>.
1887 * These binding objects can be passed as the second argument of the
1888 * <code>Kernel#eval</code> method, establishing an environment for the
1901 * b1 = k1.getBinding
1903 * b2 = k2.getBinding
1905 * eval("@secret", b1) #=> 99
1906 * eval("@secret", b2) #=> -3
1907 * eval("@secret") #=> nil
1909 * Binding objects have no class-specific methods.
1916 rb_cBinding = rb_define_class("Binding", rb_cObject);
1917 rb_undef_alloc_func(rb_cBinding);
1918 rb_undef_method(CLASS_OF(rb_cBinding), "new");
1919 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
1920 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
1921 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
1922 rb_define_global_function("binding", rb_f_binding, 0);