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]);
353 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
356 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
358 if ((GC_GUARDED_PTR_REF(cfp
->lfp
[0])) != 0 &&
359 !RUBY_VM_CLASS_SPECIAL_P(cfp
->lfp
[0])) {
361 block
= GC_GUARDED_PTR_REF(cfp
->lfp
[0]);
367 /* TODO: check more (cfp limit, called via cfunc, etc) */
368 while (cfp
->dfp
!= block
->dfp
) {
369 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
373 rb_warn("tried to create Proc object without a block");
377 rb_raise(rb_eArgError
,
378 "tried to create Proc object without a block");
386 procval
= vm_make_proc(th
, cfp
, block
);
390 GetProcPtr(procval
, proc
);
391 proc
->is_lambda
= Qtrue
;
398 * Proc.new {|...| block } => a_proc
401 * Creates a new <code>Proc</code> object, bound to the current
402 * context. <code>Proc::new</code> may be called without a block only
403 * within a method with an attached block, in which case that block is
404 * converted to the <code>Proc</code> object.
409 * proc = proc_from { "hello" }
410 * proc.call #=> "hello"
414 rb_proc_s_new(int argc
, VALUE
*argv
, VALUE klass
)
416 VALUE block
= proc_new(klass
, Qfalse
);
418 rb_obj_call_init(block
, argc
, argv
);
424 * proc { |...| block } => a_proc
426 * Equivalent to <code>Proc.new</code>.
432 return proc_new(rb_cProc
, Qfalse
);
436 rb_block_lambda(void)
438 return proc_new(rb_cProc
, Qtrue
);
444 rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
445 return rb_block_lambda();
450 * lambda { |...| block } => a_proc
452 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
453 * check the number of parameters passed when called.
459 return rb_block_lambda();
462 /* CHECKME: are the argument checking semantics correct? */
466 * prc.call(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
475 * For procs created using <code>Kernel.proc</code>, generates an
476 * error if the wrong number of parameters
477 * are passed to a proc with multiple parameters. For procs created using
478 * <code>Proc.new</code>, extra parameters are silently discarded.
480 * Returns the value of the last expression evaluated in the block. See
481 * also <code>Proc#yield</code>.
483 * a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
484 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
485 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
486 * a_proc = Proc.new {|a,b| a}
491 * prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
492 * from prog.rb:4:in `call'
497 proc_call(int argc
, VALUE
*argv
, VALUE procval
)
500 rb_block_t
*blockptr
= 0;
501 GetProcPtr(procval
, proc
);
503 if (BUILTIN_TYPE(proc
->block
.iseq
) == T_NODE
||
504 proc
->block
.iseq
->arg_block
!= -1) {
506 if (rb_block_given_p()) {
509 procval
= rb_block_proc();
510 GetProcPtr(procval
, proc
);
511 blockptr
= &proc
->block
;
515 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
516 argc
, argv
, blockptr
);
520 rb_proc_call(VALUE self
, VALUE args
)
523 GetProcPtr(self
, proc
);
524 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
525 RARRAY_LEN(args
), RARRAY_PTR(args
), 0);
529 rb_proc_call_with_block(VALUE self
, int argc
, VALUE
*argv
, VALUE pass_procval
)
532 rb_block_t
*block
= 0;
533 GetProcPtr(self
, proc
);
535 if (!NIL_P(pass_procval
)) {
536 rb_proc_t
*pass_proc
;
537 GetProcPtr(pass_procval
, pass_proc
);
538 block
= &pass_proc
->block
;
541 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
547 * prc.arity -> fixnum
549 * Returns the number of arguments that would not be ignored. If the block
550 * is declared to take no arguments, returns 0. If the block is known
551 * to take exactly n arguments, returns n. If the block has optional
552 * arguments, return -n-1, where n is the number of mandatory
553 * arguments. A <code>proc</code> with no argument declarations
554 * is the same a block declaring <code>||</code> as its arguments.
556 * Proc.new {}.arity #=> 0
557 * Proc.new {||}.arity #=> 0
558 * Proc.new {|a|}.arity #=> 1
559 * Proc.new {|a,b|}.arity #=> 2
560 * Proc.new {|a,b,c|}.arity #=> 3
561 * Proc.new {|*a|}.arity #=> -1
562 * Proc.new {|a,*b|}.arity #=> -2
563 * Proc.new {|a,*b, c|}.arity #=> -3
567 proc_arity(VALUE self
)
571 GetProcPtr(self
, proc
);
572 iseq
= proc
->block
.iseq
;
574 if (BUILTIN_TYPE(iseq
) != T_NODE
) {
575 if (iseq
->arg_rest
< 0) {
576 return INT2FIX(iseq
->argc
);
579 return INT2FIX(-(iseq
->argc
+ 1 + iseq
->arg_post_len
));
583 NODE
*node
= (NODE
*)iseq
;
584 if (nd_type(node
) == NODE_IFUNC
&& node
->nd_cfnc
== bmcall
) {
585 /* method(:foo).to_proc.arity */
586 return INT2FIX(method_arity(node
->nd_tval
));
594 rb_proc_arity(VALUE proc
)
596 return FIX2INT(proc_arity(proc
));
600 get_proc_iseq(VALUE self
)
605 GetProcPtr(self
, proc
);
606 iseq
= proc
->block
.iseq
;
607 if (!RUBY_VM_NORMAL_ISEQ_P(iseq
))
613 rb_proc_location(VALUE self
)
615 rb_iseq_t
*iseq
= get_proc_iseq(self
);
618 if (!iseq
) return Qnil
;
619 loc
[0] = iseq
->filename
;
620 if (iseq
->insn_info_table
) {
621 loc
[1] = INT2FIX(iseq
->insn_info_table
[0].line_no
);
626 return rb_ary_new4(2, loc
);
631 * prc == other_proc => true or false
633 * Return <code>true</code> if <i>prc</i> is the same object as
634 * <i>other_proc</i>, or if they are both procs with the same body.
638 proc_eq(VALUE self
, VALUE other
)
644 if (TYPE(other
) == T_DATA
&&
645 RBASIC(other
)->klass
== rb_cProc
&&
646 CLASS_OF(self
) == CLASS_OF(other
)) {
648 GetProcPtr(self
, p1
);
649 GetProcPtr(other
, p2
);
650 if (p1
->block
.iseq
== p2
->block
.iseq
&& p1
->envval
== p2
->envval
) {
660 * prc.hash => integer
662 * Return hash value corresponding to proc body.
666 proc_hash(VALUE self
)
670 GetProcPtr(self
, proc
);
671 hash
= (long)proc
->block
.iseq
;
672 hash
^= (long)proc
->envval
;
673 hash
^= (long)proc
->block
.lfp
>> 16;
674 return INT2FIX(hash
);
681 * Shows the unique identifier for this proc, along with
682 * an indication of where the proc was defined.
686 proc_to_s(VALUE self
)
690 const char *cname
= rb_obj_classname(self
);
692 const char *is_lambda
;
694 GetProcPtr(self
, proc
);
695 iseq
= proc
->block
.iseq
;
696 is_lambda
= proc
->is_lambda
? " (lambda)" : "";
698 if (RUBY_VM_NORMAL_ISEQ_P(iseq
)) {
701 if (iseq
->insn_info_table
) {
702 line_no
= iseq
->insn_info_table
[0].line_no
;
704 str
= rb_sprintf("#<%s:%p@%s:%d%s>", cname
, (void *)self
,
705 RSTRING_PTR(iseq
->filename
),
709 str
= rb_sprintf("#<%s:%p%s>", cname
, proc
->block
.iseq
,
713 if (OBJ_TAINTED(self
)) {
723 * Part of the protocol for converting objects to <code>Proc</code>
724 * objects. Instances of class <code>Proc</code> simply return
729 proc_to_proc(VALUE self
)
735 bm_mark(struct METHOD
*data
)
737 rb_gc_mark(data
->rclass
);
738 rb_gc_mark(data
->oclass
);
739 rb_gc_mark(data
->recv
);
740 rb_gc_mark((VALUE
)data
->body
);
744 rb_method_body(VALUE method
)
748 if (TYPE(method
) == T_DATA
&&
749 RDATA(method
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
750 Data_Get_Struct(method
, struct METHOD
, data
);
758 NODE
*rb_get_method_body(VALUE klass
, ID id
, ID
*idp
);
761 mnew(VALUE klass
, VALUE obj
, ID id
, VALUE mclass
, int scope
)
766 VALUE rclass
= klass
;
770 if ((body
= rb_get_method_body(klass
, id
, 0)) == 0) {
771 rb_print_undef(rclass
, oid
, 0);
773 if (scope
&& (body
->nd_noex
& NOEX_MASK
) != NOEX_PUBLIC
) {
774 rb_print_undef(rclass
, oid
, (body
->nd_noex
& NOEX_MASK
));
777 klass
= body
->nd_clss
;
778 body
= body
->nd_body
;
780 if (nd_type(body
) == NODE_ZSUPER
) {
781 klass
= RCLASS_SUPER(klass
);
785 while (rclass
!= klass
&&
786 (FL_TEST(rclass
, FL_SINGLETON
) || TYPE(rclass
) == T_ICLASS
)) {
787 rclass
= RCLASS_SUPER(rclass
);
789 if (TYPE(klass
) == T_ICLASS
)
790 klass
= RBASIC(klass
)->klass
;
791 method
= Data_Make_Struct(mclass
, struct METHOD
, bm_mark
, -1, data
);
792 data
->oclass
= klass
;
797 data
->rclass
= rclass
;
799 OBJ_INFECT(method
, klass
);
805 /**********************************************************************
807 * Document-class : Method
809 * Method objects are created by <code>Object#method</code>, and are
810 * associated with a particular object (not just with a class). They
811 * may be used to invoke the method within the object, and as a block
812 * associated with an iterator. They may also be unbound from one
813 * object (creating an <code>UnboundMethod</code>) and bound to
822 * meth = thing.method(:square)
824 * meth.call(9) #=> 81
825 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
831 * meth == other_meth => true or false
833 * Two method objects are equal if that are bound to the same
834 * object and contain the same body.
839 method_eq(VALUE method
, VALUE other
)
841 struct METHOD
*m1
, *m2
;
843 if (TYPE(other
) != T_DATA
844 || RDATA(other
)->dmark
!= (RUBY_DATA_FUNC
) bm_mark
)
846 if (CLASS_OF(method
) != CLASS_OF(other
))
849 Data_Get_Struct(method
, struct METHOD
, m1
);
850 Data_Get_Struct(other
, struct METHOD
, m2
);
852 if (m1
->oclass
!= m2
->oclass
|| m1
->rclass
!= m2
->rclass
||
853 m1
->recv
!= m2
->recv
|| m1
->body
!= m2
->body
)
861 * meth.hash => integer
863 * Return a hash value corresponding to the method object.
867 method_hash(VALUE method
)
872 Data_Get_Struct(method
, struct METHOD
, m
);
873 hash
= (long)m
->oclass
;
874 hash
^= (long)m
->rclass
;
875 hash
^= (long)m
->recv
;
876 hash
^= (long)m
->body
;
878 return INT2FIX(hash
);
883 * meth.unbind => unbound_method
885 * Dissociates <i>meth</i> from it's current receiver. The resulting
886 * <code>UnboundMethod</code> can subsequently be bound to a new object
887 * of the same class (see <code>UnboundMethod</code>).
891 method_unbind(VALUE obj
)
894 struct METHOD
*orig
, *data
;
896 Data_Get_Struct(obj
, struct METHOD
, orig
);
898 Data_Make_Struct(rb_cUnboundMethod
, struct METHOD
, bm_mark
, -1, data
);
899 data
->oclass
= orig
->oclass
;
902 data
->body
= orig
->body
;
903 data
->rclass
= orig
->rclass
;
904 data
->oid
= orig
->oid
;
905 OBJ_INFECT(method
, obj
);
912 * meth.receiver => object
914 * Returns the bound receiver of the method object.
918 method_receiver(VALUE obj
)
922 Data_Get_Struct(obj
, struct METHOD
, data
);
928 * meth.name => symbol
930 * Returns the name of the method.
934 method_name(VALUE obj
)
938 Data_Get_Struct(obj
, struct METHOD
, data
);
939 return ID2SYM(data
->id
);
944 * meth.owner => class_or_module
946 * Returns the class or module that defines the method.
950 method_owner(VALUE obj
)
954 Data_Get_Struct(obj
, struct METHOD
, data
);
960 * obj.method(sym) => method
962 * Looks up the named method as a receiver in <i>obj</i>, returning a
963 * <code>Method</code> object (or raising <code>NameError</code>). The
964 * <code>Method</code> object acts as a closure in <i>obj</i>'s object
965 * instance, so instance variables and the value of <code>self</code>
973 * "Hello, @iv = #{@iv}"
978 * m = k.method(:hello)
979 * m.call #=> "Hello, @iv = 99"
981 * l = Demo.new('Fred')
982 * m = l.method("hello")
983 * m.call #=> "Hello, @iv = Fred"
987 rb_obj_method(VALUE obj
, VALUE vid
)
989 return mnew(CLASS_OF(obj
), obj
, rb_to_id(vid
), rb_cMethod
, Qfalse
);
993 rb_obj_public_method(VALUE obj
, VALUE vid
)
995 return mnew(CLASS_OF(obj
), obj
, rb_to_id(vid
), rb_cMethod
, Qtrue
);
1000 * mod.instance_method(symbol) => unbound_method
1002 * Returns an +UnboundMethod+ representing the given
1003 * instance method in _mod_.
1006 * def do_a() print "there, "; end
1007 * def do_d() print "Hello "; end
1008 * def do_e() print "!\n"; end
1009 * def do_v() print "Dave"; end
1011 * ?a => instance_method(:do_a),
1012 * ?d => instance_method(:do_d),
1013 * ?e => instance_method(:do_e),
1014 * ?v => instance_method(:do_v)
1016 * def interpret(string)
1017 * string.each_byte {|b| Dispatcher[b].bind(self).call }
1022 * interpreter = Interpreter.new
1023 * interpreter.interpret('dave')
1025 * <em>produces:</em>
1027 * Hello there, Dave!
1031 rb_mod_instance_method(VALUE mod
, VALUE vid
)
1033 return mnew(mod
, Qundef
, rb_to_id(vid
), rb_cUnboundMethod
, Qfalse
);
1037 rb_mod_public_instance_method(VALUE mod
, VALUE vid
)
1039 return mnew(mod
, Qundef
, rb_to_id(vid
), rb_cUnboundMethod
, Qtrue
);
1044 * define_method(symbol, method) => new_method
1045 * define_method(symbol) { block } => proc
1047 * Defines an instance method in the receiver. The _method_
1048 * parameter can be a +Proc+ or +Method+ object.
1049 * If a block is specified, it is used as the method body. This block
1050 * is evaluated using <code>instance_eval</code>, a point that is
1051 * tricky to demonstrate because <code>define_method</code> is private.
1052 * (This is why we resort to the +send+ hack in this example.)
1058 * def create_method(name, &block)
1059 * self.class.send(:define_method, name, &block)
1061 * define_method(:wilma) { puts "Charge it!" }
1064 * define_method(:barney, instance_method(:fred))
1069 * a.create_method(:betty) { p self }
1072 * <em>produces:</em>
1080 rb_mod_define_method(int argc
, VALUE
*argv
, VALUE mod
)
1085 int noex
= NOEX_PUBLIC
;
1088 id
= rb_to_id(argv
[0]);
1089 body
= rb_block_lambda();
1091 else if (argc
== 2) {
1092 id
= rb_to_id(argv
[0]);
1094 if (!rb_obj_is_method(body
) && !rb_obj_is_proc(body
)) {
1095 rb_raise(rb_eTypeError
,
1096 "wrong argument type %s (expected Proc/Method)",
1097 rb_obj_classname(body
));
1101 rb_raise(rb_eArgError
, "wrong number of arguments (%d for 1)", argc
);
1104 if (RDATA(body
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
1105 struct METHOD
*method
= (struct METHOD
*)DATA_PTR(body
);
1106 VALUE rclass
= method
->rclass
;
1107 if (rclass
!= mod
) {
1108 if (FL_TEST(rclass
, FL_SINGLETON
)) {
1109 rb_raise(rb_eTypeError
,
1110 "can't bind singleton method to a different class");
1112 if (!RTEST(rb_class_inherited_p(mod
, rclass
))) {
1113 rb_raise(rb_eTypeError
,
1114 "bind argument must be a subclass of %s",
1115 rb_class2name(rclass
));
1118 node
= method
->body
;
1120 else if (rb_obj_is_proc(body
)) {
1122 body
= proc_dup(body
);
1123 GetProcPtr(body
, proc
);
1124 if (BUILTIN_TYPE(proc
->block
.iseq
) != T_NODE
) {
1125 proc
->block
.iseq
->defined_method_id
= id
;
1126 proc
->block
.iseq
->klass
= mod
;
1127 proc
->is_lambda
= Qtrue
;
1128 proc
->is_from_method
= Qtrue
;
1130 node
= NEW_BMETHOD(body
);
1134 rb_raise(rb_eTypeError
, "wrong argument type (expected Proc/Method)");
1137 /* TODO: visibility */
1139 rb_add_method(mod
, id
, node
, noex
);
1144 rb_obj_define_method(int argc
, VALUE
*argv
, VALUE obj
)
1146 VALUE klass
= rb_singleton_class(obj
);
1148 return rb_mod_define_method(argc
, argv
, klass
);
1153 * MISSING: documentation
1157 method_clone(VALUE self
)
1160 struct METHOD
*orig
, *data
;
1162 Data_Get_Struct(self
, struct METHOD
, orig
);
1163 clone
= Data_Make_Struct(CLASS_OF(self
), struct METHOD
, bm_mark
, -1, data
);
1164 CLONESETUP(clone
, self
);
1172 * meth.call(args, ...) => obj
1173 * meth[args, ...] => obj
1175 * Invokes the <i>meth</i> with the specified arguments, returning the
1176 * method's return value.
1178 * m = 12.method("+")
1184 rb_method_call(int argc
, VALUE
*argv
, VALUE method
)
1186 VALUE result
= Qnil
; /* OK */
1187 struct METHOD
*data
;
1189 volatile int safe
= -1;
1191 Data_Get_Struct(method
, struct METHOD
, data
);
1192 if (data
->recv
== Qundef
) {
1193 rb_raise(rb_eTypeError
, "can't call unbound method; bind first");
1196 if (OBJ_TAINTED(method
)) {
1197 safe
= rb_safe_level();
1198 if (rb_safe_level() < 4) {
1199 rb_set_safe_level_force(4);
1202 if ((state
= EXEC_TAG()) == 0) {
1203 rb_thread_t
*th
= GET_THREAD();
1204 VALUE
rb_vm_call(rb_thread_t
* th
, VALUE klass
, VALUE recv
, VALUE id
, ID oid
,
1205 int argc
, const VALUE
*argv
, const NODE
*body
, int nosuper
);
1207 PASS_PASSED_BLOCK_TH(th
);
1208 result
= rb_vm_call(th
, data
->oclass
, data
->recv
, data
->id
, data
->oid
,
1209 argc
, argv
, data
->body
, 0);
1213 rb_set_safe_level_force(safe
);
1219 /**********************************************************************
1221 * Document-class: UnboundMethod
1223 * Ruby supports two forms of objectified methods. Class
1224 * <code>Method</code> is used to represent methods that are associated
1225 * with a particular object: these method objects are bound to that
1226 * object. Bound method objects for an object can be created using
1227 * <code>Object#method</code>.
1229 * Ruby also supports unbound methods; methods objects that are not
1230 * associated with a particular object. These can be created either by
1231 * calling <code>Module#instance_method</code> or by calling
1232 * <code>unbind</code> on a bound method object. The result of both of
1233 * these is an <code>UnboundMethod</code> object.
1235 * Unbound methods can only be called after they are bound to an
1236 * object. That object must be be a kind_of? the method's original
1243 * def initialize(side)
1248 * area_un = Square.instance_method(:area)
1250 * s = Square.new(12)
1251 * area = area_un.bind(s)
1254 * Unbound methods are a reference to the method at the time it was
1255 * objectified: subsequent changes to the underlying class will not
1256 * affect the unbound method.
1263 * um = Test.instance_method(:test)
1270 * t.test #=> :modified
1271 * um.bind(t).call #=> :original
1277 * umeth.bind(obj) -> method
1279 * Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
1280 * from which <i>umeth</i> was obtained,
1281 * <code>obj.kind_of?(Klass)</code> must be true.
1285 * puts "In test, class = #{self.class}"
1294 * um = B.instance_method(:test)
1295 * bm = um.bind(C.new)
1297 * bm = um.bind(B.new)
1299 * bm = um.bind(A.new)
1302 * <em>produces:</em>
1304 * In test, class = C
1305 * In test, class = B
1306 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
1311 umethod_bind(VALUE method
, VALUE recv
)
1313 struct METHOD
*data
, *bound
;
1315 Data_Get_Struct(method
, struct METHOD
, data
);
1316 if (data
->rclass
!= CLASS_OF(recv
)) {
1317 if (FL_TEST(data
->rclass
, FL_SINGLETON
)) {
1318 rb_raise(rb_eTypeError
,
1319 "singleton method called for a different object");
1321 if (!rb_obj_is_kind_of(recv
, data
->rclass
)) {
1322 rb_raise(rb_eTypeError
, "bind argument must be an instance of %s",
1323 rb_class2name(data
->rclass
));
1327 method
= Data_Make_Struct(rb_cMethod
, struct METHOD
, bm_mark
, -1, bound
);
1330 bound
->rclass
= CLASS_OF(recv
);
1336 rb_node_arity(NODE
* body
)
1338 switch (nd_type(body
)) {
1340 if (body
->nd_argc
< 0)
1342 return body
->nd_argc
;
1350 return rb_proc_arity(body
->nd_cval
);
1351 case RUBY_VM_METHOD_NODE
:
1354 GetISeqPtr((VALUE
)body
->nd_body
, iseq
);
1355 if (iseq
->arg_rest
== -1 && iseq
->arg_opts
== 0) {
1359 return -(iseq
->argc
+ 1 + iseq
->arg_post_len
);
1363 rb_raise(rb_eArgError
, "invalid node 0x%x", nd_type(body
));
1369 * meth.arity => fixnum
1371 * Returns an indication of the number of arguments accepted by a
1372 * method. Returns a nonnegative integer for methods that take a fixed
1373 * number of arguments. For Ruby methods that take a variable number of
1374 * arguments, returns -n-1, where n is the number of required
1375 * arguments. For methods written in C, returns -1 if the call takes a
1376 * variable number of arguments.
1381 * def three(*a); end
1382 * def four(a, b); end
1383 * def five(a, b, *c); end
1384 * def six(a, b, *c, &d); end
1387 * c.method(:one).arity #=> 0
1388 * c.method(:two).arity #=> 1
1389 * c.method(:three).arity #=> -1
1390 * c.method(:four).arity #=> 2
1391 * c.method(:five).arity #=> -3
1392 * c.method(:six).arity #=> -3
1394 * "cat".method(:size).arity #=> 0
1395 * "cat".method(:replace).arity #=> 1
1396 * "cat".method(:squeeze).arity #=> -1
1397 * "cat".method(:count).arity #=> -1
1401 method_arity_m(VALUE method
)
1403 int n
= method_arity(method
);
1408 method_arity(VALUE method
)
1410 struct METHOD
*data
;
1412 Data_Get_Struct(method
, struct METHOD
, data
);
1413 return rb_node_arity(data
->body
);
1417 rb_mod_method_arity(VALUE mod
, ID id
)
1419 NODE
*node
= rb_method_node(mod
, id
);
1420 return rb_node_arity(node
);
1424 rb_obj_method_arity(VALUE obj
, ID id
)
1426 return rb_mod_method_arity(CLASS_OF(obj
), id
);
1431 * meth.to_s => string
1432 * meth.inspect => string
1434 * Show the name of the underlying method.
1436 * "cat".method(:count).inspect #=> "#<Method: String#count>"
1440 method_inspect(VALUE method
)
1442 struct METHOD
*data
;
1445 const char *sharp
= "#";
1447 Data_Get_Struct(method
, struct METHOD
, data
);
1448 str
= rb_str_buf_new2("#<");
1449 s
= rb_obj_classname(method
);
1450 rb_str_buf_cat2(str
, s
);
1451 rb_str_buf_cat2(str
, ": ");
1453 if (FL_TEST(data
->oclass
, FL_SINGLETON
)) {
1454 VALUE v
= rb_iv_get(data
->oclass
, "__attached__");
1456 if (data
->recv
== Qundef
) {
1457 rb_str_buf_append(str
, rb_inspect(data
->oclass
));
1459 else if (data
->recv
== v
) {
1460 rb_str_buf_append(str
, rb_inspect(v
));
1464 rb_str_buf_append(str
, rb_inspect(data
->recv
));
1465 rb_str_buf_cat2(str
, "(");
1466 rb_str_buf_append(str
, rb_inspect(v
));
1467 rb_str_buf_cat2(str
, ")");
1472 rb_str_buf_cat2(str
, rb_class2name(data
->rclass
));
1473 if (data
->rclass
!= data
->oclass
) {
1474 rb_str_buf_cat2(str
, "(");
1475 rb_str_buf_cat2(str
, rb_class2name(data
->oclass
));
1476 rb_str_buf_cat2(str
, ")");
1479 rb_str_buf_cat2(str
, sharp
);
1480 rb_str_append(str
, rb_id2str(data
->oid
));
1481 rb_str_buf_cat2(str
, ">");
1489 return rb_funcall(Qnil
, rb_intern("proc"), 0);
1493 mlambda(VALUE method
)
1495 return rb_funcall(Qnil
, rb_intern("lambda"), 0);
1499 bmcall(VALUE args
, VALUE method
)
1503 if (CLASS_OF(args
) != rb_cArray
) {
1504 args
= rb_ary_new3(1, args
);
1508 return rb_method_call(RARRAY_LEN(a
), RARRAY_PTR(a
), method
);
1513 VALUE (*func
)(ANYARGS
), /* VALUE yieldarg[, VALUE procarg] */
1516 VALUE procval
= rb_iterate(mproc
, 0, func
, val
);
1522 * meth.to_proc => prc
1524 * Returns a <code>Proc</code> object corresponding to this method.
1528 method_proc(VALUE method
)
1541 procval
= rb_iterate(mlambda
, 0, bmcall
, method
);
1542 GetProcPtr(procval
, proc
);
1543 proc
->is_from_method
= 1;
1548 rb_obj_is_method(VALUE m
)
1550 if (TYPE(m
) == T_DATA
&& RDATA(m
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
1558 * local_jump_error.exit_value => obj
1560 * Returns the exit value associated with this +LocalJumpError+.
1563 localjump_xvalue(VALUE exc
)
1565 return rb_iv_get(exc
, "@exit_value");
1570 * local_jump_error.reason => symbol
1572 * The reason this block was terminated:
1573 * :break, :redo, :retry, :next, :return, or :noreason.
1577 localjump_reason(VALUE exc
)
1579 return rb_iv_get(exc
, "@reason");
1584 * prc.binding => binding
1586 * Returns the binding associated with <i>prc</i>. Note that
1587 * <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
1588 * <code>Binding</code> object as its second parameter.
1595 * eval("param", b.binding) #=> 99
1598 proc_binding(VALUE self
)
1601 VALUE bindval
= binding_alloc(rb_cBinding
);
1604 GetProcPtr(self
, proc
);
1605 GetBindingPtr(bindval
, bind
);
1607 if (TYPE(proc
->block
.iseq
) == T_NODE
) {
1608 rb_raise(rb_eArgError
, "Can't create Binding from C level Proc");
1611 bind
->env
= proc
->envval
;
1615 static VALUE
curry(VALUE dummy
, VALUE args
, int argc
, VALUE
*argv
, VALUE passed_proc
);
1618 make_curry_proc(VALUE proc
, VALUE passed
, VALUE arity
)
1620 VALUE args
= rb_ary_new2(3);
1621 RARRAY_PTR(args
)[0] = proc
;
1622 RARRAY_PTR(args
)[1] = passed
;
1623 RARRAY_PTR(args
)[2] = arity
;
1624 RARRAY_LEN(args
) = 3;
1625 rb_ary_freeze(passed
);
1626 rb_ary_freeze(args
);
1627 return rb_proc_new(curry
, args
);
1631 curry(VALUE dummy
, VALUE args
, int argc
, VALUE
*argv
, VALUE passed_proc
)
1633 VALUE proc
, passed
, arity
;
1634 proc
= RARRAY_PTR(args
)[0];
1635 passed
= RARRAY_PTR(args
)[1];
1636 arity
= RARRAY_PTR(args
)[2];
1638 passed
= rb_ary_plus(passed
, rb_ary_new4(argc
, argv
));
1639 rb_ary_freeze(passed
);
1641 if(RARRAY_LEN(passed
) < FIX2INT(arity
)) {
1642 if (!NIL_P(passed_proc
)) {
1643 rb_warn("given block not used");
1645 arity
= make_curry_proc(proc
, passed
, arity
);
1649 return rb_proc_call_with_block(proc
, RARRAY_LEN(passed
), RARRAY_PTR(passed
), passed_proc
);
1655 * prc.curry => a_proc
1656 * prc.curry(arity) => a_proc
1658 * Returns a curried proc. If the optional <i>arity</i> argument is given,
1659 * it determines the number of arguments.
1660 * A curried proc receives some arguments. If a sufficient number of
1661 * arguments are supplied, it passes the supplied arguments to the original
1662 * proc and returns the result. Otherwise, returns another curried proc that
1663 * takes the rest of arguments.
1665 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
1666 * p b.curry[1][2][3] #=> 6
1667 * p b.curry[1, 2][3, 4] #=> 6
1668 * p b.curry(5)[1][2][3][4][5] #=> 6
1669 * p b.curry(5)[1, 2][3, 4][5] #=> 6
1670 * p b.curry(1)[1] #=> 1
1672 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1673 * p b.curry[1][2][3] #=> 6
1674 * p b.curry[1, 2][3, 4] #=> 10
1675 * p b.curry(5)[1][2][3][4][5] #=> 15
1676 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1677 * p b.curry(1)[1] #=> 1
1679 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
1680 * p b.curry[1][2][3] #=> 6
1681 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (4 or 3)
1682 * p b.curry(5) #=> wrong number of arguments (5 or 3)
1683 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1685 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1686 * p b.curry[1][2][3] #=> 6
1687 * p b.curry[1, 2][3, 4] #=> 10
1688 * p b.curry(5)[1][2][3][4][5] #=> 15
1689 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1690 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1693 * p b.curry[] #=> :foo
1696 proc_curry(int argc
, VALUE
*argv
, VALUE self
)
1698 int sarity
, marity
= FIX2INT(proc_arity(self
));
1699 VALUE arity
, opt
= Qfalse
;
1702 marity
= -marity
- 1;
1706 rb_scan_args(argc
, argv
, "01", &arity
);
1708 arity
= INT2FIX(marity
);
1711 sarity
= FIX2INT(arity
);
1712 if (proc_lambda_p(self
) && (sarity
< marity
|| (sarity
> marity
&& !opt
))) {
1713 rb_raise(rb_eArgError
, "wrong number of arguments (%d for %d)", sarity
, marity
);
1717 return make_curry_proc(self
, rb_ary_new(), arity
);
1721 * <code>Proc</code> objects are blocks of code that have been bound to
1722 * a set of local variables. Once bound, the code may be called in
1723 * different contexts and still access those variables.
1725 * def gen_times(factor)
1726 * return Proc.new {|n| n*factor }
1729 * times3 = gen_times(3)
1730 * times5 = gen_times(5)
1732 * times3.call(12) #=> 36
1733 * times5.call(5) #=> 25
1734 * times3.call(times5.call(4)) #=> 60
1742 rb_cProc
= rb_define_class("Proc", rb_cObject
);
1743 rb_undef_alloc_func(rb_cProc
);
1744 rb_define_singleton_method(rb_cProc
, "new", rb_proc_s_new
, -1);
1745 rb_define_method(rb_cProc
, "call", proc_call
, -1);
1746 rb_define_method(rb_cProc
, "[]", proc_call
, -1);
1747 rb_define_method(rb_cProc
, "yield", proc_call
, -1);
1748 rb_define_method(rb_cProc
, "to_proc", proc_to_proc
, 0);
1749 rb_define_method(rb_cProc
, "arity", proc_arity
, 0);
1750 rb_define_method(rb_cProc
, "clone", proc_clone
, 0);
1751 rb_define_method(rb_cProc
, "dup", proc_dup
, 0);
1752 rb_define_method(rb_cProc
, "==", proc_eq
, 1);
1753 rb_define_method(rb_cProc
, "eql?", proc_eq
, 1);
1754 rb_define_method(rb_cProc
, "hash", proc_hash
, 0);
1755 rb_define_method(rb_cProc
, "to_s", proc_to_s
, 0);
1756 rb_define_method(rb_cProc
, "lambda?", proc_lambda_p
, 0);
1757 rb_define_method(rb_cProc
, "binding", proc_binding
, 0);
1758 rb_define_method(rb_cProc
, "curry", proc_curry
, -1);
1761 rb_eLocalJumpError
= rb_define_class("LocalJumpError", rb_eStandardError
);
1762 rb_define_method(rb_eLocalJumpError
, "exit_value", localjump_xvalue
, 0);
1763 rb_define_method(rb_eLocalJumpError
, "reason", localjump_reason
, 0);
1765 rb_eSysStackError
= rb_define_class("SystemStackError", rb_eException
);
1766 sysstack_error
= rb_exc_new3(rb_eSysStackError
,
1767 rb_obj_freeze(rb_str_new2("stack level too deep")));
1768 OBJ_TAINT(sysstack_error
);
1769 OBJ_FREEZE(sysstack_error
);
1771 /* utility functions */
1772 rb_define_global_function("proc", rb_block_proc
, 0);
1773 rb_define_global_function("lambda", proc_lambda
, 0);
1776 rb_cMethod
= rb_define_class("Method", rb_cObject
);
1777 rb_undef_alloc_func(rb_cMethod
);
1778 rb_undef_method(CLASS_OF(rb_cMethod
), "new");
1779 rb_define_method(rb_cMethod
, "==", method_eq
, 1);
1780 rb_define_method(rb_cMethod
, "eql?", method_eq
, 1);
1781 rb_define_method(rb_cMethod
, "hash", method_hash
, 0);
1782 rb_define_method(rb_cMethod
, "clone", method_clone
, 0);
1783 rb_define_method(rb_cMethod
, "call", rb_method_call
, -1);
1784 rb_define_method(rb_cMethod
, "[]", rb_method_call
, -1);
1785 rb_define_method(rb_cMethod
, "arity", method_arity_m
, 0);
1786 rb_define_method(rb_cMethod
, "inspect", method_inspect
, 0);
1787 rb_define_method(rb_cMethod
, "to_s", method_inspect
, 0);
1788 rb_define_method(rb_cMethod
, "to_proc", method_proc
, 0);
1789 rb_define_method(rb_cMethod
, "receiver", method_receiver
, 0);
1790 rb_define_method(rb_cMethod
, "name", method_name
, 0);
1791 rb_define_method(rb_cMethod
, "owner", method_owner
, 0);
1792 rb_define_method(rb_cMethod
, "unbind", method_unbind
, 0);
1793 rb_define_method(rb_mKernel
, "method", rb_obj_method
, 1);
1794 rb_define_method(rb_mKernel
, "public_method", rb_obj_public_method
, 1);
1797 rb_cUnboundMethod
= rb_define_class("UnboundMethod", rb_cObject
);
1798 rb_undef_alloc_func(rb_cUnboundMethod
);
1799 rb_undef_method(CLASS_OF(rb_cUnboundMethod
), "new");
1800 rb_define_method(rb_cUnboundMethod
, "==", method_eq
, 1);
1801 rb_define_method(rb_cUnboundMethod
, "eql?", method_eq
, 1);
1802 rb_define_method(rb_cUnboundMethod
, "hash", method_hash
, 0);
1803 rb_define_method(rb_cUnboundMethod
, "clone", method_clone
, 0);
1804 rb_define_method(rb_cUnboundMethod
, "arity", method_arity_m
, 0);
1805 rb_define_method(rb_cUnboundMethod
, "inspect", method_inspect
, 0);
1806 rb_define_method(rb_cUnboundMethod
, "to_s", method_inspect
, 0);
1807 rb_define_method(rb_cUnboundMethod
, "name", method_name
, 0);
1808 rb_define_method(rb_cUnboundMethod
, "owner", method_owner
, 0);
1809 rb_define_method(rb_cUnboundMethod
, "bind", umethod_bind
, 1);
1811 /* Module#*_method */
1812 rb_define_method(rb_cModule
, "instance_method", rb_mod_instance_method
, 1);
1813 rb_define_method(rb_cModule
, "public_instance_method", rb_mod_public_instance_method
, 1);
1814 rb_define_private_method(rb_cModule
, "define_method", rb_mod_define_method
, -1);
1817 rb_define_method(rb_mKernel
, "define_singleton_method", rb_obj_define_method
, -1);
1821 * Objects of class <code>Binding</code> encapsulate the execution
1822 * context at some particular place in the code and retain this context
1823 * for future use. The variables, methods, value of <code>self</code>,
1824 * and possibly an iterator block that can be accessed in this context
1825 * are all retained. Binding objects can be created using
1826 * <code>Kernel#binding</code>, and are made available to the callback
1827 * of <code>Kernel#set_trace_func</code>.
1829 * These binding objects can be passed as the second argument of the
1830 * <code>Kernel#eval</code> method, establishing an environment for the
1843 * b1 = k1.getBinding
1845 * b2 = k2.getBinding
1847 * eval("@secret", b1) #=> 99
1848 * eval("@secret", b2) #=> -3
1849 * eval("@secret") #=> nil
1851 * Binding objects have no class-specific methods.
1858 rb_cBinding
= rb_define_class("Binding", rb_cObject
);
1859 rb_undef_alloc_func(rb_cBinding
);
1860 rb_undef_method(CLASS_OF(rb_cBinding
), "new");
1861 rb_define_method(rb_cBinding
, "clone", binding_clone
, 0);
1862 rb_define_method(rb_cBinding
, "dup", binding_dup
, 0);
1863 rb_define_method(rb_cBinding
, "eval", bind_eval
, -1);
1864 rb_define_global_function("binding", rb_f_binding
, 0);