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
);
277 rb_thread_t
*th
= GET_THREAD();
278 rb_control_frame_t
*cfp
= vm_get_ruby_level_caller_cfp(th
, th
->cfp
);
279 VALUE bindval
= binding_alloc(rb_cBinding
);
283 rb_raise(rb_eRuntimeError
, "Can't create Binding Object on top of Fiber.");
286 GetBindingPtr(bindval
, bind
);
287 bind
->env
= vm_make_env_object(th
, cfp
);
293 * binding -> a_binding
295 * Returns a +Binding+ object, describing the variable and
296 * method bindings at the point of call. This object can be used when
297 * calling +eval+ to execute the evaluated command in this
298 * environment. Also see the description of class +Binding+.
300 * def getBinding(param)
303 * b = getBinding("hello")
304 * eval("param", b) #=> "hello"
308 rb_f_binding(VALUE self
)
310 return rb_binding_new();
315 * binding.eval(string [, filename [,lineno]]) => obj
317 * Evaluates the Ruby expression(s) in <em>string</em>, in the
318 * <em>binding</em>'s context. If the optional <em>filename</em> and
319 * <em>lineno</em> parameters are present, they will be used when
320 * reporting syntax errors.
322 * def getBinding(param)
325 * b = getBinding("hello")
326 * b.eval("param") #=> "hello"
330 bind_eval(int argc
, VALUE
*argv
, VALUE bindval
)
334 rb_scan_args(argc
, argv
, "12", &args
[0], &args
[2], &args
[3]);
336 return rb_f_eval(argc
+1, args
, Qnil
/* self will be searched in eval */);
340 proc_new(VALUE klass
, int is_lambda
)
342 VALUE procval
= Qnil
;
343 rb_thread_t
*th
= GET_THREAD();
344 rb_control_frame_t
*cfp
= th
->cfp
;
347 if ((GC_GUARDED_PTR_REF(cfp
->lfp
[0])) != 0 &&
348 !RUBY_VM_CLASS_SPECIAL_P(cfp
->lfp
[0])) {
350 block
= GC_GUARDED_PTR_REF(cfp
->lfp
[0]);
351 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
354 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
356 if ((GC_GUARDED_PTR_REF(cfp
->lfp
[0])) != 0 &&
357 !RUBY_VM_CLASS_SPECIAL_P(cfp
->lfp
[0])) {
359 block
= GC_GUARDED_PTR_REF(cfp
->lfp
[0]);
361 /* TODO: check more (cfp limit, called via cfunc, etc) */
362 while (cfp
->dfp
!= block
->dfp
) {
363 cfp
= RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp
);
367 rb_warn("tried to create Proc object without a block");
371 rb_raise(rb_eArgError
,
372 "tried to create Proc object without a block");
380 procval
= vm_make_proc(th
, cfp
, block
);
384 GetProcPtr(procval
, proc
);
385 proc
->is_lambda
= Qtrue
;
392 * Proc.new {|...| block } => a_proc
395 * Creates a new <code>Proc</code> object, bound to the current
396 * context. <code>Proc::new</code> may be called without a block only
397 * within a method with an attached block, in which case that block is
398 * converted to the <code>Proc</code> object.
403 * proc = proc_from { "hello" }
404 * proc.call #=> "hello"
408 rb_proc_s_new(int argc
, VALUE
*argv
, VALUE klass
)
410 VALUE block
= proc_new(klass
, Qfalse
);
412 rb_obj_call_init(block
, argc
, argv
);
418 * proc { |...| block } => a_proc
420 * Equivalent to <code>Proc.new</code>.
426 return proc_new(rb_cProc
, Qfalse
);
430 rb_block_lambda(void)
432 return proc_new(rb_cProc
, Qtrue
);
438 rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
439 return rb_block_lambda();
444 * lambda { |...| block } => a_proc
446 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
447 * check the number of parameters passed when called.
453 return rb_block_lambda();
456 /* CHECKME: are the argument checking semantics correct? */
460 * prc.call(params,...) => obj
461 * prc[params,...] => obj
463 * Invokes the block, setting the block's parameters to the values in
464 * <i>params</i> using something close to method calling semantics.
465 * Generates a warning if multiple values are passed to a proc that
466 * expects just one (previously this silently converted the parameters
469 * For procs created using <code>Kernel.proc</code>, generates an
470 * error if the wrong number of parameters
471 * are passed to a proc with multiple parameters. For procs created using
472 * <code>Proc.new</code>, extra parameters are silently discarded.
474 * Returns the value of the last expression evaluated in the block. See
475 * also <code>Proc#yield</code>.
477 * a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
478 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
479 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
480 * a_proc = Proc.new {|a,b| a}
485 * prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
486 * from prog.rb:4:in `call'
491 proc_call(int argc
, VALUE
*argv
, VALUE procval
)
494 rb_block_t
*blockptr
= 0;
495 GetProcPtr(procval
, proc
);
497 if (BUILTIN_TYPE(proc
->block
.iseq
) == T_NODE
||
498 proc
->block
.iseq
->arg_block
!= -1) {
500 if (rb_block_given_p()) {
503 procval
= rb_block_proc();
504 GetProcPtr(procval
, proc
);
505 blockptr
= &proc
->block
;
509 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
510 argc
, argv
, blockptr
);
514 rb_proc_call(VALUE self
, VALUE args
)
517 GetProcPtr(self
, proc
);
518 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
519 RARRAY_LEN(args
), RARRAY_PTR(args
), 0);
523 rb_proc_call_with_block(VALUE self
, int argc
, VALUE
*argv
, VALUE pass_procval
)
525 rb_proc_t
*proc
, *pass_proc
= 0;
526 GetProcPtr(self
, proc
);
528 if (!NIL_P(pass_procval
)) {
529 GetProcPtr(pass_procval
, pass_proc
);
532 return vm_invoke_proc(GET_THREAD(), proc
, proc
->block
.self
,
533 argc
, argv
, &pass_proc
->block
);
538 * prc.arity -> fixnum
540 * Returns the number of arguments that would not be ignored. If the block
541 * is declared to take no arguments, returns 0. If the block is known
542 * to take exactly n arguments, returns n. If the block has optional
543 * arguments, return -n-1, where n is the number of mandatory
544 * arguments. A <code>proc</code> with no argument declarations
545 * is the same a block declaring <code>||</code> as its arguments.
547 * Proc.new {}.arity #=> 0
548 * Proc.new {||}.arity #=> 0
549 * Proc.new {|a|}.arity #=> 1
550 * Proc.new {|a,b|}.arity #=> 2
551 * Proc.new {|a,b,c|}.arity #=> 3
552 * Proc.new {|*a|}.arity #=> -1
553 * Proc.new {|a,*b|}.arity #=> -2
554 * Proc.new {|a,*b, c|}.arity #=> -3
558 proc_arity(VALUE self
)
562 GetProcPtr(self
, proc
);
563 iseq
= proc
->block
.iseq
;
565 if (BUILTIN_TYPE(iseq
) != T_NODE
) {
566 if (iseq
->arg_rest
< 0) {
567 return INT2FIX(iseq
->argc
);
570 return INT2FIX(-(iseq
->argc
+ 1 + iseq
->arg_post_len
));
574 NODE
*node
= (NODE
*)iseq
;
575 if (nd_type(node
) == NODE_IFUNC
&& node
->nd_cfnc
== bmcall
) {
576 /* method(:foo).to_proc.arity */
577 return INT2FIX(method_arity(node
->nd_tval
));
585 rb_proc_arity(VALUE proc
)
587 return FIX2INT(proc_arity(proc
));
591 get_proc_iseq(VALUE self
)
596 GetProcPtr(self
, proc
);
597 iseq
= proc
->block
.iseq
;
598 if (!RUBY_VM_NORMAL_ISEQ_P(iseq
))
604 rb_proc_location(VALUE self
)
606 rb_iseq_t
*iseq
= get_proc_iseq(self
);
609 if (!iseq
) return Qnil
;
610 loc
[0] = iseq
->filename
;
611 if (iseq
->insn_info_table
) {
612 loc
[1] = INT2FIX(iseq
->insn_info_table
[0].line_no
);
617 return rb_ary_new4(2, loc
);
622 * prc == other_proc => true or false
624 * Return <code>true</code> if <i>prc</i> is the same object as
625 * <i>other_proc</i>, or if they are both procs with the same body.
629 proc_eq(VALUE self
, VALUE other
)
635 if (TYPE(other
) == T_DATA
&&
636 RBASIC(other
)->klass
== rb_cProc
&&
637 CLASS_OF(self
) == CLASS_OF(other
)) {
639 GetProcPtr(self
, p1
);
640 GetProcPtr(other
, p2
);
641 if (p1
->block
.iseq
== p2
->block
.iseq
&& p1
->envval
== p2
->envval
) {
651 * prc.hash => integer
653 * Return hash value corresponding to proc body.
657 proc_hash(VALUE self
)
661 GetProcPtr(self
, proc
);
662 hash
= (long)proc
->block
.iseq
;
663 hash
^= (long)proc
->envval
;
664 hash
^= (long)proc
->block
.lfp
>> 16;
665 return INT2FIX(hash
);
672 * Shows the unique identifier for this proc, along with
673 * an indication of where the proc was defined.
677 proc_to_s(VALUE self
)
681 const char *cname
= rb_obj_classname(self
);
683 const char *is_lambda
;
685 GetProcPtr(self
, proc
);
686 iseq
= proc
->block
.iseq
;
687 is_lambda
= proc
->is_lambda
? " (lambda)" : "";
689 if (RUBY_VM_NORMAL_ISEQ_P(iseq
)) {
692 if (iseq
->insn_info_table
) {
693 line_no
= iseq
->insn_info_table
[0].line_no
;
695 str
= rb_sprintf("#<%s:%p@%s:%d%s>", cname
, (void *)self
,
696 RSTRING_PTR(iseq
->filename
),
700 str
= rb_sprintf("#<%s:%p%s>", cname
, proc
->block
.iseq
,
704 if (OBJ_TAINTED(self
)) {
714 * Part of the protocol for converting objects to <code>Proc</code>
715 * objects. Instances of class <code>Proc</code> simply return
720 proc_to_proc(VALUE self
)
726 bm_mark(struct METHOD
*data
)
728 rb_gc_mark(data
->rclass
);
729 rb_gc_mark(data
->oclass
);
730 rb_gc_mark(data
->recv
);
731 rb_gc_mark((VALUE
)data
->body
);
735 rb_method_body(VALUE method
)
739 if (TYPE(method
) == T_DATA
&&
740 RDATA(method
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
741 Data_Get_Struct(method
, struct METHOD
, data
);
749 NODE
*rb_get_method_body(VALUE klass
, ID id
, ID
*idp
);
752 mnew(VALUE klass
, VALUE obj
, ID id
, VALUE mclass
, int scope
)
757 VALUE rclass
= klass
;
761 if ((body
= rb_get_method_body(klass
, id
, 0)) == 0) {
762 rb_print_undef(rclass
, oid
, 0);
764 if (scope
&& (body
->nd_noex
& NOEX_MASK
) != NOEX_PUBLIC
) {
765 rb_print_undef(rclass
, oid
, (body
->nd_noex
& NOEX_MASK
));
768 klass
= body
->nd_clss
;
769 body
= body
->nd_body
;
771 if (nd_type(body
) == NODE_ZSUPER
) {
772 klass
= RCLASS_SUPER(klass
);
776 while (rclass
!= klass
&&
777 (FL_TEST(rclass
, FL_SINGLETON
) || TYPE(rclass
) == T_ICLASS
)) {
778 rclass
= RCLASS_SUPER(rclass
);
780 if (TYPE(klass
) == T_ICLASS
)
781 klass
= RBASIC(klass
)->klass
;
782 method
= Data_Make_Struct(mclass
, struct METHOD
, bm_mark
, -1, data
);
783 data
->oclass
= klass
;
788 data
->rclass
= rclass
;
790 OBJ_INFECT(method
, klass
);
796 /**********************************************************************
798 * Document-class : Method
800 * Method objects are created by <code>Object#method</code>, and are
801 * associated with a particular object (not just with a class). They
802 * may be used to invoke the method within the object, and as a block
803 * associated with an iterator. They may also be unbound from one
804 * object (creating an <code>UnboundMethod</code>) and bound to
813 * meth = thing.method(:square)
815 * meth.call(9) #=> 81
816 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
822 * meth == other_meth => true or false
824 * Two method objects are equal if that are bound to the same
825 * object and contain the same body.
830 method_eq(VALUE method
, VALUE other
)
832 struct METHOD
*m1
, *m2
;
834 if (TYPE(other
) != T_DATA
835 || RDATA(other
)->dmark
!= (RUBY_DATA_FUNC
) bm_mark
)
837 if (CLASS_OF(method
) != CLASS_OF(other
))
840 Data_Get_Struct(method
, struct METHOD
, m1
);
841 Data_Get_Struct(other
, struct METHOD
, m2
);
843 if (m1
->oclass
!= m2
->oclass
|| m1
->rclass
!= m2
->rclass
||
844 m1
->recv
!= m2
->recv
|| m1
->body
!= m2
->body
)
852 * meth.hash => integer
854 * Return a hash value corresponding to the method object.
858 method_hash(VALUE method
)
863 Data_Get_Struct(method
, struct METHOD
, m
);
864 hash
= (long)m
->oclass
;
865 hash
^= (long)m
->rclass
;
866 hash
^= (long)m
->recv
;
867 hash
^= (long)m
->body
;
869 return INT2FIX(hash
);
874 * meth.unbind => unbound_method
876 * Dissociates <i>meth</i> from it's current receiver. The resulting
877 * <code>UnboundMethod</code> can subsequently be bound to a new object
878 * of the same class (see <code>UnboundMethod</code>).
882 method_unbind(VALUE obj
)
885 struct METHOD
*orig
, *data
;
887 Data_Get_Struct(obj
, struct METHOD
, orig
);
889 Data_Make_Struct(rb_cUnboundMethod
, struct METHOD
, bm_mark
, -1, data
);
890 data
->oclass
= orig
->oclass
;
893 data
->body
= orig
->body
;
894 data
->rclass
= orig
->rclass
;
895 data
->oid
= orig
->oid
;
896 OBJ_INFECT(method
, obj
);
903 * meth.receiver => object
905 * Returns the bound receiver of the method object.
909 method_receiver(VALUE obj
)
913 Data_Get_Struct(obj
, struct METHOD
, data
);
919 * meth.name => symbol
921 * Returns the name of the method.
925 method_name(VALUE obj
)
929 Data_Get_Struct(obj
, struct METHOD
, data
);
930 return ID2SYM(data
->id
);
935 * meth.owner => class_or_module
937 * Returns the class or module that defines the method.
941 method_owner(VALUE obj
)
945 Data_Get_Struct(obj
, struct METHOD
, data
);
951 * obj.method(sym) => method
953 * Looks up the named method as a receiver in <i>obj</i>, returning a
954 * <code>Method</code> object (or raising <code>NameError</code>). The
955 * <code>Method</code> object acts as a closure in <i>obj</i>'s object
956 * instance, so instance variables and the value of <code>self</code>
964 * "Hello, @iv = #{@iv}"
969 * m = k.method(:hello)
970 * m.call #=> "Hello, @iv = 99"
972 * l = Demo.new('Fred')
973 * m = l.method("hello")
974 * m.call #=> "Hello, @iv = Fred"
978 rb_obj_method(VALUE obj
, VALUE vid
)
980 return mnew(CLASS_OF(obj
), obj
, rb_to_id(vid
), rb_cMethod
, Qfalse
);
984 rb_obj_public_method(VALUE obj
, VALUE vid
)
986 return mnew(CLASS_OF(obj
), obj
, rb_to_id(vid
), rb_cMethod
, Qtrue
);
991 * mod.instance_method(symbol) => unbound_method
993 * Returns an +UnboundMethod+ representing the given
994 * instance method in _mod_.
997 * def do_a() print "there, "; end
998 * def do_d() print "Hello "; end
999 * def do_e() print "!\n"; end
1000 * def do_v() print "Dave"; end
1002 * ?a => instance_method(:do_a),
1003 * ?d => instance_method(:do_d),
1004 * ?e => instance_method(:do_e),
1005 * ?v => instance_method(:do_v)
1007 * def interpret(string)
1008 * string.each_byte {|b| Dispatcher[b].bind(self).call }
1013 * interpreter = Interpreter.new
1014 * interpreter.interpret('dave')
1016 * <em>produces:</em>
1018 * Hello there, Dave!
1022 rb_mod_instance_method(VALUE mod
, VALUE vid
)
1024 return mnew(mod
, Qundef
, rb_to_id(vid
), rb_cUnboundMethod
, Qfalse
);
1028 rb_mod_public_instance_method(VALUE mod
, VALUE vid
)
1030 return mnew(mod
, Qundef
, rb_to_id(vid
), rb_cUnboundMethod
, Qtrue
);
1035 * define_method(symbol, method) => new_method
1036 * define_method(symbol) { block } => proc
1038 * Defines an instance method in the receiver. The _method_
1039 * parameter can be a +Proc+ or +Method+ object.
1040 * If a block is specified, it is used as the method body. This block
1041 * is evaluated using <code>instance_eval</code>, a point that is
1042 * tricky to demonstrate because <code>define_method</code> is private.
1043 * (This is why we resort to the +send+ hack in this example.)
1049 * def create_method(name, &block)
1050 * self.class.send(:define_method, name, &block)
1052 * define_method(:wilma) { puts "Charge it!" }
1055 * define_method(:barney, instance_method(:fred))
1060 * a.create_method(:betty) { p self }
1063 * <em>produces:</em>
1071 rb_mod_define_method(int argc
, VALUE
*argv
, VALUE mod
)
1076 int noex
= NOEX_PUBLIC
;
1079 id
= rb_to_id(argv
[0]);
1080 body
= rb_block_lambda();
1082 else if (argc
== 2) {
1083 id
= rb_to_id(argv
[0]);
1085 if (!rb_obj_is_method(body
) && !rb_obj_is_proc(body
)) {
1086 rb_raise(rb_eTypeError
,
1087 "wrong argument type %s (expected Proc/Method)",
1088 rb_obj_classname(body
));
1092 rb_raise(rb_eArgError
, "wrong number of arguments (%d for 1)", argc
);
1095 if (RDATA(body
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
1096 struct METHOD
*method
= (struct METHOD
*)DATA_PTR(body
);
1097 VALUE rclass
= method
->rclass
;
1098 if (rclass
!= mod
) {
1099 if (FL_TEST(rclass
, FL_SINGLETON
)) {
1100 rb_raise(rb_eTypeError
,
1101 "can't bind singleton method to a different class");
1103 if (!RTEST(rb_class_inherited_p(mod
, rclass
))) {
1104 rb_raise(rb_eTypeError
,
1105 "bind argument must be a subclass of %s",
1106 rb_class2name(rclass
));
1109 node
= method
->body
;
1111 else if (rb_obj_is_proc(body
)) {
1113 body
= proc_dup(body
);
1114 GetProcPtr(body
, proc
);
1115 if (BUILTIN_TYPE(proc
->block
.iseq
) != T_NODE
) {
1116 proc
->block
.iseq
->defined_method_id
= id
;
1117 proc
->block
.iseq
->klass
= mod
;
1118 proc
->is_lambda
= Qtrue
;
1119 proc
->is_from_method
= Qtrue
;
1121 node
= NEW_BMETHOD(body
);
1125 rb_raise(rb_eTypeError
, "wrong argument type (expected Proc/Method)");
1128 /* TODO: visibility */
1130 rb_add_method(mod
, id
, node
, noex
);
1135 rb_obj_define_method(int argc
, VALUE
*argv
, VALUE obj
)
1137 VALUE klass
= rb_singleton_class(obj
);
1139 return rb_mod_define_method(argc
, argv
, klass
);
1144 * MISSING: documentation
1148 method_clone(VALUE self
)
1151 struct METHOD
*orig
, *data
;
1153 Data_Get_Struct(self
, struct METHOD
, orig
);
1154 clone
= Data_Make_Struct(CLASS_OF(self
), struct METHOD
, bm_mark
, -1, data
);
1155 CLONESETUP(clone
, self
);
1163 * meth.call(args, ...) => obj
1164 * meth[args, ...] => obj
1166 * Invokes the <i>meth</i> with the specified arguments, returning the
1167 * method's return value.
1169 * m = 12.method("+")
1175 rb_method_call(int argc
, VALUE
*argv
, VALUE method
)
1177 VALUE result
= Qnil
; /* OK */
1178 struct METHOD
*data
;
1180 volatile int safe
= -1;
1182 Data_Get_Struct(method
, struct METHOD
, data
);
1183 if (data
->recv
== Qundef
) {
1184 rb_raise(rb_eTypeError
, "can't call unbound method; bind first");
1187 if (OBJ_TAINTED(method
)) {
1188 safe
= rb_safe_level();
1189 if (rb_safe_level() < 4) {
1190 rb_set_safe_level_force(4);
1193 if ((state
= EXEC_TAG()) == 0) {
1194 rb_thread_t
*th
= GET_THREAD();
1195 VALUE
rb_vm_call(rb_thread_t
* th
, VALUE klass
, VALUE recv
, VALUE id
, ID oid
,
1196 int argc
, const VALUE
*argv
, const NODE
*body
, int nosuper
);
1198 PASS_PASSED_BLOCK_TH(th
);
1199 result
= rb_vm_call(th
, data
->oclass
, data
->recv
, data
->id
, data
->oid
,
1200 argc
, argv
, data
->body
, 0);
1204 rb_set_safe_level_force(safe
);
1210 /**********************************************************************
1212 * Document-class: UnboundMethod
1214 * Ruby supports two forms of objectified methods. Class
1215 * <code>Method</code> is used to represent methods that are associated
1216 * with a particular object: these method objects are bound to that
1217 * object. Bound method objects for an object can be created using
1218 * <code>Object#method</code>.
1220 * Ruby also supports unbound methods; methods objects that are not
1221 * associated with a particular object. These can be created either by
1222 * calling <code>Module#instance_method</code> or by calling
1223 * <code>unbind</code> on a bound method object. The result of both of
1224 * these is an <code>UnboundMethod</code> object.
1226 * Unbound methods can only be called after they are bound to an
1227 * object. That object must be be a kind_of? the method's original
1234 * def initialize(side)
1239 * area_un = Square.instance_method(:area)
1241 * s = Square.new(12)
1242 * area = area_un.bind(s)
1245 * Unbound methods are a reference to the method at the time it was
1246 * objectified: subsequent changes to the underlying class will not
1247 * affect the unbound method.
1254 * um = Test.instance_method(:test)
1261 * t.test #=> :modified
1262 * um.bind(t).call #=> :original
1268 * umeth.bind(obj) -> method
1270 * Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
1271 * from which <i>umeth</i> was obtained,
1272 * <code>obj.kind_of?(Klass)</code> must be true.
1276 * puts "In test, class = #{self.class}"
1285 * um = B.instance_method(:test)
1286 * bm = um.bind(C.new)
1288 * bm = um.bind(B.new)
1290 * bm = um.bind(A.new)
1293 * <em>produces:</em>
1295 * In test, class = C
1296 * In test, class = B
1297 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
1302 umethod_bind(VALUE method
, VALUE recv
)
1304 struct METHOD
*data
, *bound
;
1306 Data_Get_Struct(method
, struct METHOD
, data
);
1307 if (data
->rclass
!= CLASS_OF(recv
)) {
1308 if (FL_TEST(data
->rclass
, FL_SINGLETON
)) {
1309 rb_raise(rb_eTypeError
,
1310 "singleton method called for a different object");
1312 if (!rb_obj_is_kind_of(recv
, data
->rclass
)) {
1313 rb_raise(rb_eTypeError
, "bind argument must be an instance of %s",
1314 rb_class2name(data
->rclass
));
1318 method
= Data_Make_Struct(rb_cMethod
, struct METHOD
, bm_mark
, -1, bound
);
1321 bound
->rclass
= CLASS_OF(recv
);
1327 rb_node_arity(NODE
* body
)
1329 switch (nd_type(body
)) {
1331 if (body
->nd_argc
< 0)
1333 return body
->nd_argc
;
1341 return rb_proc_arity(body
->nd_cval
);
1342 case RUBY_VM_METHOD_NODE
:
1345 GetISeqPtr((VALUE
)body
->nd_body
, iseq
);
1346 if (iseq
->arg_rest
== -1 && iseq
->arg_opts
== 0) {
1350 return -(iseq
->argc
+ 1 + iseq
->arg_post_len
);
1354 rb_raise(rb_eArgError
, "invalid node 0x%x", nd_type(body
));
1360 * meth.arity => fixnum
1362 * Returns an indication of the number of arguments accepted by a
1363 * method. Returns a nonnegative integer for methods that take a fixed
1364 * number of arguments. For Ruby methods that take a variable number of
1365 * arguments, returns -n-1, where n is the number of required
1366 * arguments. For methods written in C, returns -1 if the call takes a
1367 * variable number of arguments.
1372 * def three(*a); end
1373 * def four(a, b); end
1374 * def five(a, b, *c); end
1375 * def six(a, b, *c, &d); end
1378 * c.method(:one).arity #=> 0
1379 * c.method(:two).arity #=> 1
1380 * c.method(:three).arity #=> -1
1381 * c.method(:four).arity #=> 2
1382 * c.method(:five).arity #=> -3
1383 * c.method(:six).arity #=> -3
1385 * "cat".method(:size).arity #=> 0
1386 * "cat".method(:replace).arity #=> 1
1387 * "cat".method(:squeeze).arity #=> -1
1388 * "cat".method(:count).arity #=> -1
1392 method_arity_m(VALUE method
)
1394 int n
= method_arity(method
);
1399 method_arity(VALUE method
)
1401 struct METHOD
*data
;
1403 Data_Get_Struct(method
, struct METHOD
, data
);
1404 return rb_node_arity(data
->body
);
1408 rb_mod_method_arity(VALUE mod
, ID id
)
1410 NODE
*node
= rb_method_node(mod
, id
);
1411 return rb_node_arity(node
);
1415 rb_obj_method_arity(VALUE obj
, ID id
)
1417 return rb_mod_method_arity(CLASS_OF(obj
), id
);
1422 * meth.to_s => string
1423 * meth.inspect => string
1425 * Show the name of the underlying method.
1427 * "cat".method(:count).inspect #=> "#<Method: String#count>"
1431 method_inspect(VALUE method
)
1433 struct METHOD
*data
;
1436 const char *sharp
= "#";
1438 Data_Get_Struct(method
, struct METHOD
, data
);
1439 str
= rb_str_buf_new2("#<");
1440 s
= rb_obj_classname(method
);
1441 rb_str_buf_cat2(str
, s
);
1442 rb_str_buf_cat2(str
, ": ");
1444 if (FL_TEST(data
->oclass
, FL_SINGLETON
)) {
1445 VALUE v
= rb_iv_get(data
->oclass
, "__attached__");
1447 if (data
->recv
== Qundef
) {
1448 rb_str_buf_append(str
, rb_inspect(data
->oclass
));
1450 else if (data
->recv
== v
) {
1451 rb_str_buf_append(str
, rb_inspect(v
));
1455 rb_str_buf_append(str
, rb_inspect(data
->recv
));
1456 rb_str_buf_cat2(str
, "(");
1457 rb_str_buf_append(str
, rb_inspect(v
));
1458 rb_str_buf_cat2(str
, ")");
1463 rb_str_buf_cat2(str
, rb_class2name(data
->rclass
));
1464 if (data
->rclass
!= data
->oclass
) {
1465 rb_str_buf_cat2(str
, "(");
1466 rb_str_buf_cat2(str
, rb_class2name(data
->oclass
));
1467 rb_str_buf_cat2(str
, ")");
1470 rb_str_buf_cat2(str
, sharp
);
1471 rb_str_append(str
, rb_id2str(data
->oid
));
1472 rb_str_buf_cat2(str
, ">");
1480 return rb_funcall(Qnil
, rb_intern("proc"), 0);
1484 mlambda(VALUE method
)
1486 return rb_funcall(Qnil
, rb_intern("lambda"), 0);
1490 bmcall(VALUE args
, VALUE method
)
1494 if (CLASS_OF(args
) != rb_cArray
) {
1495 args
= rb_ary_new3(1, args
);
1499 return rb_method_call(RARRAY_LEN(a
), RARRAY_PTR(a
), method
);
1504 VALUE (*func
)(ANYARGS
), /* VALUE yieldarg[, VALUE procarg] */
1507 VALUE procval
= rb_iterate(mproc
, 0, func
, val
);
1513 * meth.to_proc => prc
1515 * Returns a <code>Proc</code> object corresponding to this method.
1519 method_proc(VALUE method
)
1532 procval
= rb_iterate(mlambda
, 0, bmcall
, method
);
1533 GetProcPtr(procval
, proc
);
1534 proc
->is_from_method
= 1;
1539 rb_obj_is_method(VALUE m
)
1541 if (TYPE(m
) == T_DATA
&& RDATA(m
)->dmark
== (RUBY_DATA_FUNC
) bm_mark
) {
1549 * local_jump_error.exit_value => obj
1551 * Returns the exit value associated with this +LocalJumpError+.
1554 localjump_xvalue(VALUE exc
)
1556 return rb_iv_get(exc
, "@exit_value");
1561 * local_jump_error.reason => symbol
1563 * The reason this block was terminated:
1564 * :break, :redo, :retry, :next, :return, or :noreason.
1568 localjump_reason(VALUE exc
)
1570 return rb_iv_get(exc
, "@reason");
1575 * prc.binding => binding
1577 * Returns the binding associated with <i>prc</i>. Note that
1578 * <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
1579 * <code>Binding</code> object as its second parameter.
1586 * eval("param", b.binding) #=> 99
1589 proc_binding(VALUE self
)
1592 VALUE bindval
= binding_alloc(rb_cBinding
);
1595 GetProcPtr(self
, proc
);
1596 GetBindingPtr(bindval
, bind
);
1598 if (TYPE(proc
->block
.iseq
) == T_NODE
) {
1599 rb_raise(rb_eArgError
, "Can't create Binding from C level Proc");
1602 bind
->env
= proc
->envval
;
1606 static VALUE
curry(VALUE dummy
, VALUE args
, int argc
, VALUE
*argv
, VALUE passed_proc
);
1609 make_curry_proc(VALUE proc
, VALUE passed
, VALUE arity
)
1611 VALUE args
= rb_ary_new2(3);
1612 RARRAY_PTR(args
)[0] = proc
;
1613 RARRAY_PTR(args
)[1] = passed
;
1614 RARRAY_PTR(args
)[2] = arity
;
1615 RARRAY_LEN(args
) = 3;
1616 rb_ary_freeze(passed
);
1617 rb_ary_freeze(args
);
1618 return rb_proc_new(curry
, args
);
1622 curry(VALUE dummy
, VALUE args
, int argc
, VALUE
*argv
, VALUE passed_proc
)
1624 VALUE proc
, passed
, arity
;
1625 proc
= RARRAY_PTR(args
)[0];
1626 passed
= RARRAY_PTR(args
)[1];
1627 arity
= RARRAY_PTR(args
)[2];
1629 passed
= rb_ary_plus(passed
, rb_ary_new4(argc
, argv
));
1630 rb_ary_freeze(passed
);
1632 if(RARRAY_LEN(passed
) < FIX2INT(arity
)) {
1633 if (!NIL_P(passed_proc
)) {
1634 rb_warn("given block not used");
1636 arity
= make_curry_proc(proc
, passed
, arity
);
1640 return rb_proc_call_with_block(proc
, RARRAY_LEN(passed
), RARRAY_PTR(passed
), passed_proc
);
1646 * prc.curry => a_proc
1647 * prc.curry(arity) => a_proc
1649 * Returns a curried proc. If the optional <i>arity</i> argument is given,
1650 * it determines the number of arguments.
1651 * A curried proc receives some arguments. If a sufficient number of
1652 * arguments are supplied, it passes the supplied arguments to the original
1653 * proc and returns the result. Otherwise, returns another curried proc that
1654 * takes the rest of arguments.
1656 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
1657 * p b.curry[1][2][3] #=> 6
1658 * p b.curry[1, 2][3, 4] #=> 6
1659 * p b.curry(5)[1][2][3][4][5] #=> 6
1660 * p b.curry(5)[1, 2][3, 4][5] #=> 6
1661 * p b.curry(1)[1] #=> 1
1663 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1664 * p b.curry[1][2][3] #=> 6
1665 * p b.curry[1, 2][3, 4] #=> 10
1666 * p b.curry(5)[1][2][3][4][5] #=> 15
1667 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1668 * p b.curry(1)[1] #=> 1
1670 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
1671 * p b.curry[1][2][3] #=> 6
1672 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (4 or 3)
1673 * p b.curry(5) #=> wrong number of arguments (5 or 3)
1674 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1676 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1677 * p b.curry[1][2][3] #=> 6
1678 * p b.curry[1, 2][3, 4] #=> 10
1679 * p b.curry(5)[1][2][3][4][5] #=> 15
1680 * p b.curry(5)[1, 2][3, 4][5] #=> 15
1681 * p b.curry(1) #=> wrong number of arguments (1 or 3)
1684 * p b.curry[] #=> :foo
1687 proc_curry(int argc
, VALUE
*argv
, VALUE self
)
1689 int sarity
, marity
= FIX2INT(proc_arity(self
));
1690 VALUE arity
, opt
= Qfalse
;
1693 marity
= -marity
- 1;
1697 rb_scan_args(argc
, argv
, "01", &arity
);
1699 arity
= INT2FIX(marity
);
1702 sarity
= FIX2INT(arity
);
1703 if (proc_lambda_p(self
) && (sarity
< marity
|| (sarity
> marity
&& !opt
))) {
1704 rb_raise(rb_eArgError
, "wrong number of arguments (%d for %d)", sarity
, marity
);
1708 return make_curry_proc(self
, rb_ary_new(), arity
);
1712 * <code>Proc</code> objects are blocks of code that have been bound to
1713 * a set of local variables. Once bound, the code may be called in
1714 * different contexts and still access those variables.
1716 * def gen_times(factor)
1717 * return Proc.new {|n| n*factor }
1720 * times3 = gen_times(3)
1721 * times5 = gen_times(5)
1723 * times3.call(12) #=> 36
1724 * times5.call(5) #=> 25
1725 * times3.call(times5.call(4)) #=> 60
1733 rb_cProc
= rb_define_class("Proc", rb_cObject
);
1734 rb_undef_alloc_func(rb_cProc
);
1735 rb_define_singleton_method(rb_cProc
, "new", rb_proc_s_new
, -1);
1736 rb_define_method(rb_cProc
, "call", proc_call
, -1);
1737 rb_define_method(rb_cProc
, "[]", proc_call
, -1);
1738 rb_define_method(rb_cProc
, "yield", proc_call
, -1);
1739 rb_define_method(rb_cProc
, "to_proc", proc_to_proc
, 0);
1740 rb_define_method(rb_cProc
, "arity", proc_arity
, 0);
1741 rb_define_method(rb_cProc
, "clone", proc_clone
, 0);
1742 rb_define_method(rb_cProc
, "dup", proc_dup
, 0);
1743 rb_define_method(rb_cProc
, "==", proc_eq
, 1);
1744 rb_define_method(rb_cProc
, "eql?", proc_eq
, 1);
1745 rb_define_method(rb_cProc
, "hash", proc_hash
, 0);
1746 rb_define_method(rb_cProc
, "to_s", proc_to_s
, 0);
1747 rb_define_method(rb_cProc
, "lambda?", proc_lambda_p
, 0);
1748 rb_define_method(rb_cProc
, "binding", proc_binding
, 0);
1749 rb_define_method(rb_cProc
, "curry", proc_curry
, -1);
1752 rb_eLocalJumpError
= rb_define_class("LocalJumpError", rb_eStandardError
);
1753 rb_define_method(rb_eLocalJumpError
, "exit_value", localjump_xvalue
, 0);
1754 rb_define_method(rb_eLocalJumpError
, "reason", localjump_reason
, 0);
1756 rb_eSysStackError
= rb_define_class("SystemStackError", rb_eException
);
1757 sysstack_error
= rb_exc_new2(rb_eSysStackError
, "stack level too deep");
1758 OBJ_TAINT(sysstack_error
);
1759 rb_register_mark_object(sysstack_error
);
1761 /* utility functions */
1762 rb_define_global_function("proc", rb_block_proc
, 0);
1763 rb_define_global_function("lambda", proc_lambda
, 0);
1766 rb_cMethod
= rb_define_class("Method", rb_cObject
);
1767 rb_undef_alloc_func(rb_cMethod
);
1768 rb_undef_method(CLASS_OF(rb_cMethod
), "new");
1769 rb_define_method(rb_cMethod
, "==", method_eq
, 1);
1770 rb_define_method(rb_cMethod
, "eql?", method_eq
, 1);
1771 rb_define_method(rb_cMethod
, "hash", method_hash
, 0);
1772 rb_define_method(rb_cMethod
, "clone", method_clone
, 0);
1773 rb_define_method(rb_cMethod
, "call", rb_method_call
, -1);
1774 rb_define_method(rb_cMethod
, "[]", rb_method_call
, -1);
1775 rb_define_method(rb_cMethod
, "arity", method_arity_m
, 0);
1776 rb_define_method(rb_cMethod
, "inspect", method_inspect
, 0);
1777 rb_define_method(rb_cMethod
, "to_s", method_inspect
, 0);
1778 rb_define_method(rb_cMethod
, "to_proc", method_proc
, 0);
1779 rb_define_method(rb_cMethod
, "receiver", method_receiver
, 0);
1780 rb_define_method(rb_cMethod
, "name", method_name
, 0);
1781 rb_define_method(rb_cMethod
, "owner", method_owner
, 0);
1782 rb_define_method(rb_cMethod
, "unbind", method_unbind
, 0);
1783 rb_define_method(rb_mKernel
, "method", rb_obj_method
, 1);
1784 rb_define_method(rb_mKernel
, "public_method", rb_obj_public_method
, 1);
1787 rb_cUnboundMethod
= rb_define_class("UnboundMethod", rb_cObject
);
1788 rb_undef_alloc_func(rb_cUnboundMethod
);
1789 rb_undef_method(CLASS_OF(rb_cUnboundMethod
), "new");
1790 rb_define_method(rb_cUnboundMethod
, "==", method_eq
, 1);
1791 rb_define_method(rb_cUnboundMethod
, "eql?", method_eq
, 1);
1792 rb_define_method(rb_cUnboundMethod
, "hash", method_hash
, 0);
1793 rb_define_method(rb_cUnboundMethod
, "clone", method_clone
, 0);
1794 rb_define_method(rb_cUnboundMethod
, "arity", method_arity_m
, 0);
1795 rb_define_method(rb_cUnboundMethod
, "inspect", method_inspect
, 0);
1796 rb_define_method(rb_cUnboundMethod
, "to_s", method_inspect
, 0);
1797 rb_define_method(rb_cUnboundMethod
, "name", method_name
, 0);
1798 rb_define_method(rb_cUnboundMethod
, "owner", method_owner
, 0);
1799 rb_define_method(rb_cUnboundMethod
, "bind", umethod_bind
, 1);
1801 /* Module#*_method */
1802 rb_define_method(rb_cModule
, "instance_method", rb_mod_instance_method
, 1);
1803 rb_define_method(rb_cModule
, "public_instance_method", rb_mod_public_instance_method
, 1);
1804 rb_define_private_method(rb_cModule
, "define_method", rb_mod_define_method
, -1);
1807 rb_define_method(rb_mKernel
, "define_singleton_method", rb_obj_define_method
, -1);
1811 * Objects of class <code>Binding</code> encapsulate the execution
1812 * context at some particular place in the code and retain this context
1813 * for future use. The variables, methods, value of <code>self</code>,
1814 * and possibly an iterator block that can be accessed in this context
1815 * are all retained. Binding objects can be created using
1816 * <code>Kernel#binding</code>, and are made available to the callback
1817 * of <code>Kernel#set_trace_func</code>.
1819 * These binding objects can be passed as the second argument of the
1820 * <code>Kernel#eval</code> method, establishing an environment for the
1833 * b1 = k1.getBinding
1835 * b2 = k2.getBinding
1837 * eval("@secret", b1) #=> 99
1838 * eval("@secret", b2) #=> -3
1839 * eval("@secret") #=> nil
1841 * Binding objects have no class-specific methods.
1848 rb_cBinding
= rb_define_class("Binding", rb_cObject
);
1849 rb_undef_alloc_func(rb_cBinding
);
1850 rb_undef_method(CLASS_OF(rb_cBinding
), "new");
1851 rb_define_method(rb_cBinding
, "clone", binding_clone
, 0);
1852 rb_define_method(rb_cBinding
, "dup", binding_dup
, 0);
1853 rb_define_method(rb_cBinding
, "eval", bind_eval
, -1);
1854 rb_define_global_function("binding", rb_f_binding
, 0);