* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / proc.c
blob3bcb6cfbc8ffd958c42a1d9ac83d9af870def4db
1 /**********************************************************************
3 proc.c - Proc, Binding, Env
5 $Author$
6 created at: Wed Jan 17 12:13:14 2007
8 Copyright (C) 2004-2007 Koichi Sasada
10 **********************************************************************/
12 #include "eval_intern.h"
13 #include "gc.h"
15 struct METHOD {
16 VALUE oclass; /* class that holds the method */
17 VALUE rclass; /* class of the receiver */
18 VALUE recv;
19 ID id, oid;
20 NODE *body;
23 VALUE rb_cUnboundMethod;
24 VALUE rb_cMethod;
25 VALUE rb_cBinding;
26 VALUE rb_cProc;
28 static VALUE bmcall(VALUE, VALUE);
29 static int method_arity(VALUE);
30 static VALUE rb_obj_is_method(VALUE m);
32 /* Proc */
34 static void
35 proc_free(void *ptr)
37 RUBY_FREE_ENTER("proc");
38 if (ptr) {
39 ruby_xfree(ptr);
41 RUBY_FREE_LEAVE("proc");
44 static void
45 proc_mark(void *ptr)
47 rb_proc_t *proc;
48 RUBY_MARK_ENTER("proc");
49 if (ptr) {
50 proc = ptr;
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");
62 VALUE
63 rb_proc_alloc(VALUE klass)
65 VALUE obj;
66 rb_proc_t *proc;
67 obj = Data_Make_Struct(klass, rb_proc_t, proc_mark, proc_free, proc);
68 MEMZERO(proc, rb_proc_t, 1);
69 return obj;
72 VALUE
73 rb_obj_is_proc(VALUE proc)
75 if (TYPE(proc) == T_DATA &&
76 RDATA(proc)->dfree == (RUBY_DATA_FUNC) proc_free) {
77 return Qtrue;
79 else {
80 return Qfalse;
84 static VALUE
85 proc_dup(VALUE self)
87 VALUE procval = rb_proc_alloc(rb_cProc);
88 rb_proc_t *src, *dst;
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;
98 return procval;
101 static VALUE
102 proc_clone(VALUE self)
104 VALUE procval = proc_dup(self);
105 CLONESETUP(procval, self);
106 return procval;
110 * call-seq:
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
158 * n {} => false
160 * The & argument preserves the tricks if a Proc object is given
161 * by & argument.
163 * n(&lambda {}) => true
164 * n(&proc {}) => false
165 * n(&Proc.new {}) => false
167 * A Proc object converted from a method has no tricks.
169 * def m() end
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.
178 * class C
179 * define_method(:d) {}
180 * end
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.
188 * class C
189 * define_method(:e, &proc {})
190 * end
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.
197 * class << C
198 * def def2(name, &body)
199 * define_method(name, &body)
200 * end
201 * end
202 * class C
203 * def2(:f) {}
204 * end
205 * C.new.f(1,2) => ArgumentError
207 * The wrapper, def2, defines a method which has no tricks.
211 static VALUE
212 proc_lambda_p(VALUE procval)
214 rb_proc_t *proc;
215 GetProcPtr(procval, proc);
217 return proc->is_lambda ? Qtrue : Qfalse;
220 /* Binding */
222 static void
223 binding_free(void *ptr)
225 rb_binding_t *bind;
226 RUBY_FREE_ENTER("binding");
227 if (ptr) {
228 bind = ptr;
229 ruby_xfree(ptr);
231 RUBY_FREE_LEAVE("binding");
234 static void
235 binding_mark(void *ptr)
237 rb_binding_t *bind;
238 RUBY_MARK_ENTER("binding");
239 if (ptr) {
240 bind = ptr;
241 RUBY_MARK_UNLESS_NULL(bind->env);
243 RUBY_MARK_LEAVE("binding");
246 static VALUE
247 binding_alloc(VALUE klass)
249 VALUE obj;
250 rb_binding_t *bind;
251 obj = Data_Make_Struct(klass, rb_binding_t, binding_mark, binding_free, bind);
252 return obj;
255 static VALUE
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);
262 dst->env = src->env;
263 return bindval;
266 static VALUE
267 binding_clone(VALUE self)
269 VALUE bindval = binding_dup(self);
270 CLONESETUP(bindval, self);
271 return bindval;
274 rb_control_frame_t *vm_get_ruby_level_next_cfp(rb_thread_t *th, rb_control_frame_t *cfp);
276 VALUE
277 rb_binding_new(void)
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);
282 rb_binding_t *bind;
284 if (cfp == 0) {
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);
290 return bindval;
294 * call-seq:
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)
303 * return binding
304 * end
305 * b = getBinding("hello")
306 * eval("param", b) #=> "hello"
309 static VALUE
310 rb_f_binding(VALUE self)
312 return rb_binding_new();
316 * call-seq:
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)
325 * return binding
326 * end
327 * b = getBinding("hello")
328 * b.eval("param") #=> "hello"
331 static VALUE
332 bind_eval(int argc, VALUE *argv, VALUE bindval)
334 VALUE args[4];
336 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
337 args[1] = bindval;
338 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
341 static VALUE
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;
347 rb_block_t *block;
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);
355 else {
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]);
363 if (block->proc) {
364 return block->proc;
367 /* TODO: check more (cfp limit, called via cfunc, etc) */
368 while (cfp->dfp != block->dfp) {
369 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
372 if (is_lambda) {
373 rb_warn("tried to create Proc object without a block");
376 else {
377 rb_raise(rb_eArgError,
378 "tried to create Proc object without a block");
382 if (block->proc) {
383 return block->proc;
386 procval = vm_make_proc(th, cfp, block);
388 if (is_lambda) {
389 rb_proc_t *proc;
390 GetProcPtr(procval, proc);
391 proc->is_lambda = Qtrue;
393 return procval;
397 * call-seq:
398 * Proc.new {|...| block } => a_proc
399 * Proc.new => 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.
406 * def proc_from
407 * Proc.new
408 * end
409 * proc = proc_from { "hello" }
410 * proc.call #=> "hello"
413 static VALUE
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);
419 return block;
423 * call-seq:
424 * proc { |...| block } => a_proc
426 * Equivalent to <code>Proc.new</code>.
429 VALUE
430 rb_block_proc(void)
432 return proc_new(rb_cProc, Qfalse);
435 VALUE
436 rb_block_lambda(void)
438 return proc_new(rb_cProc, Qtrue);
441 VALUE
442 rb_f_lambda(void)
444 rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
445 return rb_block_lambda();
449 * call-seq:
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.
456 static VALUE
457 proc_lambda(void)
459 return rb_block_lambda();
462 /* CHECKME: are the argument checking semantics correct? */
465 * call-seq:
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
473 * to an array).
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}
487 * a_proc.call(1,2,3)
489 * <em>produces:</em>
491 * prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
492 * from prog.rb:4:in `call'
493 * from prog.rb:5
496 static VALUE
497 proc_call(int argc, VALUE *argv, VALUE procval)
499 rb_proc_t *proc;
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()) {
507 rb_proc_t *proc;
508 VALUE procval;
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);
519 VALUE
520 rb_proc_call(VALUE self, VALUE args)
522 rb_proc_t *proc;
523 GetProcPtr(self, proc);
524 return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
525 RARRAY_LEN(args), RARRAY_PTR(args), 0);
528 VALUE
529 rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval)
531 rb_proc_t *proc;
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,
542 argc, argv, block);
546 * call-seq:
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
566 static VALUE
567 proc_arity(VALUE self)
569 rb_proc_t *proc;
570 rb_iseq_t *iseq;
571 GetProcPtr(self, proc);
572 iseq = proc->block.iseq;
573 if (iseq) {
574 if (BUILTIN_TYPE(iseq) != T_NODE) {
575 if (iseq->arg_rest < 0) {
576 return INT2FIX(iseq->argc);
578 else {
579 return INT2FIX(-(iseq->argc + 1 + iseq->arg_post_len));
582 else {
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));
590 return INT2FIX(-1);
594 rb_proc_arity(VALUE proc)
596 return FIX2INT(proc_arity(proc));
599 static rb_iseq_t *
600 get_proc_iseq(VALUE self)
602 rb_proc_t *proc;
603 rb_iseq_t *iseq;
605 GetProcPtr(self, proc);
606 iseq = proc->block.iseq;
607 if (!RUBY_VM_NORMAL_ISEQ_P(iseq))
608 return 0;
609 return iseq;
612 VALUE
613 rb_proc_location(VALUE self)
615 rb_iseq_t *iseq = get_proc_iseq(self);
616 VALUE loc[2];
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);
623 else {
624 loc[1] = Qnil;
626 return rb_ary_new4(2, loc);
630 * call-seq:
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.
637 static VALUE
638 proc_eq(VALUE self, VALUE other)
640 if (self == other) {
641 return Qtrue;
643 else {
644 if (TYPE(other) == T_DATA &&
645 RBASIC(other)->klass == rb_cProc &&
646 CLASS_OF(self) == CLASS_OF(other)) {
647 rb_proc_t *p1, *p2;
648 GetProcPtr(self, p1);
649 GetProcPtr(other, p2);
650 if (p1->block.iseq == p2->block.iseq && p1->envval == p2->envval) {
651 return Qtrue;
655 return Qfalse;
659 * call-seq:
660 * prc.hash => integer
662 * Return hash value corresponding to proc body.
665 static VALUE
666 proc_hash(VALUE self)
668 int hash;
669 rb_proc_t *proc;
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);
678 * call-seq:
679 * prc.to_s => string
681 * Shows the unique identifier for this proc, along with
682 * an indication of where the proc was defined.
685 static VALUE
686 proc_to_s(VALUE self)
688 VALUE str = 0;
689 rb_proc_t *proc;
690 const char *cname = rb_obj_classname(self);
691 rb_iseq_t *iseq;
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)) {
699 int line_no = 0;
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),
706 line_no, is_lambda);
708 else {
709 str = rb_sprintf("#<%s:%p%s>", cname, proc->block.iseq,
710 is_lambda);
713 if (OBJ_TAINTED(self)) {
714 OBJ_TAINT(str);
716 return str;
720 * call-seq:
721 * prc.to_proc -> prc
723 * Part of the protocol for converting objects to <code>Proc</code>
724 * objects. Instances of class <code>Proc</code> simply return
725 * themselves.
728 static VALUE
729 proc_to_proc(VALUE self)
731 return self;
734 static void
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);
743 NODE *
744 rb_method_body(VALUE method)
746 struct METHOD *data;
748 if (TYPE(method) == T_DATA &&
749 RDATA(method)->dmark == (RUBY_DATA_FUNC) bm_mark) {
750 Data_Get_Struct(method, struct METHOD, data);
751 return data->body;
753 else {
754 return 0;
758 NODE *rb_get_method_body(VALUE klass, ID id, ID *idp);
760 static VALUE
761 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
763 VALUE method;
764 NODE *body;
765 struct METHOD *data;
766 VALUE rclass = klass;
767 ID oid = id;
769 again:
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);
782 goto again;
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;
793 data->recv = obj;
795 data->id = id;
796 data->body = body;
797 data->rclass = rclass;
798 data->oid = oid;
799 OBJ_INFECT(method, klass);
801 return method;
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
814 * another.
816 * class Thing
817 * def square(n)
818 * n*n
819 * end
820 * end
821 * thing = Thing.new
822 * meth = thing.method(:square)
824 * meth.call(9) #=> 81
825 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
830 * call-seq:
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.
838 static VALUE
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)
845 return Qfalse;
846 if (CLASS_OF(method) != CLASS_OF(other))
847 return Qfalse;
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)
854 return Qfalse;
856 return Qtrue;
860 * call-seq:
861 * meth.hash => integer
863 * Return a hash value corresponding to the method object.
866 static VALUE
867 method_hash(VALUE method)
869 struct METHOD *m;
870 long hash;
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);
882 * call-seq:
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>).
890 static VALUE
891 method_unbind(VALUE obj)
893 VALUE method;
894 struct METHOD *orig, *data;
896 Data_Get_Struct(obj, struct METHOD, orig);
897 method =
898 Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, -1, data);
899 data->oclass = orig->oclass;
900 data->recv = Qundef;
901 data->id = orig->id;
902 data->body = orig->body;
903 data->rclass = orig->rclass;
904 data->oid = orig->oid;
905 OBJ_INFECT(method, obj);
907 return method;
911 * call-seq:
912 * meth.receiver => object
914 * Returns the bound receiver of the method object.
917 static VALUE
918 method_receiver(VALUE obj)
920 struct METHOD *data;
922 Data_Get_Struct(obj, struct METHOD, data);
923 return data->recv;
927 * call-seq:
928 * meth.name => symbol
930 * Returns the name of the method.
933 static VALUE
934 method_name(VALUE obj)
936 struct METHOD *data;
938 Data_Get_Struct(obj, struct METHOD, data);
939 return ID2SYM(data->id);
943 * call-seq:
944 * meth.owner => class_or_module
946 * Returns the class or module that defines the method.
949 static VALUE
950 method_owner(VALUE obj)
952 struct METHOD *data;
954 Data_Get_Struct(obj, struct METHOD, data);
955 return data->oclass;
959 * call-seq:
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>
966 * remain available.
968 * class Demo
969 * def initialize(n)
970 * @iv = n
971 * end
972 * def hello()
973 * "Hello, @iv = #{@iv}"
974 * end
975 * end
977 * k = Demo.new(99)
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"
986 VALUE
987 rb_obj_method(VALUE obj, VALUE vid)
989 return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qfalse);
992 VALUE
993 rb_obj_public_method(VALUE obj, VALUE vid)
995 return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qtrue);
999 * call-seq:
1000 * mod.instance_method(symbol) => unbound_method
1002 * Returns an +UnboundMethod+ representing the given
1003 * instance method in _mod_.
1005 * class Interpreter
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
1010 * Dispatcher = {
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 }
1018 * end
1019 * end
1022 * interpreter = Interpreter.new
1023 * interpreter.interpret('dave')
1025 * <em>produces:</em>
1027 * Hello there, Dave!
1030 static VALUE
1031 rb_mod_instance_method(VALUE mod, VALUE vid)
1033 return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qfalse);
1036 static VALUE
1037 rb_mod_public_instance_method(VALUE mod, VALUE vid)
1039 return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qtrue);
1043 * call-seq:
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.)
1054 * class A
1055 * def fred
1056 * puts "In Fred"
1057 * end
1058 * def create_method(name, &block)
1059 * self.class.send(:define_method, name, &block)
1060 * end
1061 * define_method(:wilma) { puts "Charge it!" }
1062 * end
1063 * class B < A
1064 * define_method(:barney, instance_method(:fred))
1065 * end
1066 * a = B.new
1067 * a.barney
1068 * a.wilma
1069 * a.create_method(:betty) { p self }
1070 * a.betty
1072 * <em>produces:</em>
1074 * In Fred
1075 * Charge it!
1076 * #<B:0x401b39e8>
1079 static VALUE
1080 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
1082 ID id;
1083 VALUE body;
1084 NODE *node;
1085 int noex = NOEX_PUBLIC;
1087 if (argc == 1) {
1088 id = rb_to_id(argv[0]);
1089 body = rb_block_lambda();
1091 else if (argc == 2) {
1092 id = rb_to_id(argv[0]);
1093 body = argv[1];
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));
1100 else {
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)) {
1121 rb_proc_t *proc;
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);
1132 else {
1133 /* type error */
1134 rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
1137 /* TODO: visibility */
1139 rb_add_method(mod, id, node, noex);
1140 return body;
1143 static VALUE
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
1156 static VALUE
1157 method_clone(VALUE self)
1159 VALUE clone;
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);
1165 *data = *orig;
1167 return clone;
1171 * call-seq:
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("+")
1179 * m.call(3) #=> 15
1180 * m.call(20) #=> 32
1183 VALUE
1184 rb_method_call(int argc, VALUE *argv, VALUE method)
1186 VALUE result = Qnil; /* OK */
1187 struct METHOD *data;
1188 int state;
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");
1195 PUSH_TAG();
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);
1211 POP_TAG();
1212 if (safe >= 0)
1213 rb_set_safe_level_force(safe);
1214 if (state)
1215 JUMP_TAG(state);
1216 return result;
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
1237 * class.
1239 * class Square
1240 * def area
1241 * @side * @side
1242 * end
1243 * def initialize(side)
1244 * @side = side
1245 * end
1246 * end
1248 * area_un = Square.instance_method(:area)
1250 * s = Square.new(12)
1251 * area = area_un.bind(s)
1252 * area.call #=> 144
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.
1258 * class Test
1259 * def test
1260 * :original
1261 * end
1262 * end
1263 * um = Test.instance_method(:test)
1264 * class Test
1265 * def test
1266 * :modified
1267 * end
1268 * end
1269 * t = Test.new
1270 * t.test #=> :modified
1271 * um.bind(t).call #=> :original
1276 * call-seq:
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.
1283 * class A
1284 * def test
1285 * puts "In test, class = #{self.class}"
1286 * end
1287 * end
1288 * class B < A
1289 * end
1290 * class C < B
1291 * end
1294 * um = B.instance_method(:test)
1295 * bm = um.bind(C.new)
1296 * bm.call
1297 * bm = um.bind(B.new)
1298 * bm.call
1299 * bm = um.bind(A.new)
1300 * bm.call
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)
1307 * from prog.rb:16
1310 static VALUE
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);
1328 *bound = *data;
1329 bound->recv = recv;
1330 bound->rclass = CLASS_OF(recv);
1332 return method;
1336 rb_node_arity(NODE* body)
1338 switch (nd_type(body)) {
1339 case NODE_CFUNC:
1340 if (body->nd_argc < 0)
1341 return -1;
1342 return body->nd_argc;
1343 case NODE_ZSUPER:
1344 return -1;
1345 case NODE_ATTRSET:
1346 return 1;
1347 case NODE_IVAR:
1348 return 0;
1349 case NODE_BMETHOD:
1350 return rb_proc_arity(body->nd_cval);
1351 case RUBY_VM_METHOD_NODE:
1353 rb_iseq_t *iseq;
1354 GetISeqPtr((VALUE)body->nd_body, iseq);
1355 if (iseq->arg_rest == -1 && iseq->arg_opts == 0) {
1356 return iseq->argc;
1358 else {
1359 return -(iseq->argc + 1 + iseq->arg_post_len);
1362 default:
1363 rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body));
1368 * call-seq:
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.
1378 * class C
1379 * def one; end
1380 * def two(a); end
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
1385 * end
1386 * c = C.new
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
1400 static VALUE
1401 method_arity_m(VALUE method)
1403 int n = method_arity(method);
1404 return INT2FIX(n);
1407 static int
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);
1430 * call-seq:
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>"
1439 static VALUE
1440 method_inspect(VALUE method)
1442 struct METHOD *data;
1443 VALUE str;
1444 const char *s;
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));
1461 sharp = ".";
1463 else {
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, ")");
1468 sharp = ".";
1471 else {
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, ">");
1483 return str;
1486 static VALUE
1487 mproc(VALUE method)
1489 return rb_funcall(Qnil, rb_intern("proc"), 0);
1492 static VALUE
1493 mlambda(VALUE method)
1495 return rb_funcall(Qnil, rb_intern("lambda"), 0);
1498 static VALUE
1499 bmcall(VALUE args, VALUE method)
1501 volatile VALUE a;
1503 if (CLASS_OF(args) != rb_cArray) {
1504 args = rb_ary_new3(1, args);
1507 a = args;
1508 return rb_method_call(RARRAY_LEN(a), RARRAY_PTR(a), method);
1511 VALUE
1512 rb_proc_new(
1513 VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */
1514 VALUE val)
1516 VALUE procval = rb_iterate(mproc, 0, func, val);
1517 return procval;
1521 * call-seq:
1522 * meth.to_proc => prc
1524 * Returns a <code>Proc</code> object corresponding to this method.
1527 static VALUE
1528 method_proc(VALUE method)
1530 VALUE procval;
1531 rb_proc_t *proc;
1533 * class Method
1534 * def to_proc
1535 * proc{|*args|
1536 * self.call(*args)
1538 * end
1539 * end
1541 procval = rb_iterate(mlambda, 0, bmcall, method);
1542 GetProcPtr(procval, proc);
1543 proc->is_from_method = 1;
1544 return procval;
1547 static VALUE
1548 rb_obj_is_method(VALUE m)
1550 if (TYPE(m) == T_DATA && RDATA(m)->dmark == (RUBY_DATA_FUNC) bm_mark) {
1551 return Qtrue;
1553 return Qfalse;
1557 * call_seq:
1558 * local_jump_error.exit_value => obj
1560 * Returns the exit value associated with this +LocalJumpError+.
1562 static VALUE
1563 localjump_xvalue(VALUE exc)
1565 return rb_iv_get(exc, "@exit_value");
1569 * call-seq:
1570 * local_jump_error.reason => symbol
1572 * The reason this block was terminated:
1573 * :break, :redo, :retry, :next, :return, or :noreason.
1576 static VALUE
1577 localjump_reason(VALUE exc)
1579 return rb_iv_get(exc, "@reason");
1583 * call-seq:
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.
1590 * def fred(param)
1591 * proc {}
1592 * end
1594 * b = fred(99)
1595 * eval("param", b.binding) #=> 99
1597 static VALUE
1598 proc_binding(VALUE self)
1600 rb_proc_t *proc;
1601 VALUE bindval = binding_alloc(rb_cBinding);
1602 rb_binding_t *bind;
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;
1612 return bindval;
1615 static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc);
1617 static VALUE
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);
1630 static VALUE
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);
1646 return arity;
1648 else {
1649 return rb_proc_call_with_block(proc, RARRAY_LEN(passed), RARRAY_PTR(passed), passed_proc);
1654 * call-seq:
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)
1692 * b = proc { :foo }
1693 * p b.curry[] #=> :foo
1695 static VALUE
1696 proc_curry(int argc, VALUE *argv, VALUE self)
1698 int sarity, marity = FIX2INT(proc_arity(self));
1699 VALUE arity, opt = Qfalse;
1701 if (marity < 0) {
1702 marity = -marity - 1;
1703 opt = Qtrue;
1706 rb_scan_args(argc, argv, "01", &arity);
1707 if (NIL_P(arity)) {
1708 arity = INT2FIX(marity);
1710 else {
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 }
1727 * end
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
1738 void
1739 Init_Proc(void)
1741 /* Proc */
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);
1760 /* Exceptions */
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);
1775 /* Method */
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);
1796 /* UnboundMethod */
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);
1816 /* Kernel */
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
1831 * evaluation.
1833 * class Demo
1834 * def initialize(n)
1835 * @secret = n
1836 * end
1837 * def getBinding
1838 * return binding()
1839 * end
1840 * end
1842 * k1 = Demo.new(99)
1843 * b1 = k1.getBinding
1844 * k2 = Demo.new(-3)
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.
1855 void
1856 Init_Binding(void)
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);