OSDN Git Service

b366a42e492195fb3b2d4f06b8d06cbb760df06f
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / proc.c
1 /**********************************************************************
2
3   proc.c - Proc, Binding, Env
4
5   $Author: yugui $
6   created at: Wed Jan 17 12:13:14 2007
7
8   Copyright (C) 2004-2007 Koichi Sasada
9
10 **********************************************************************/
11
12 #include "eval_intern.h"
13 #include "gc.h"
14
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;
21 };
22
23 VALUE rb_cUnboundMethod;
24 VALUE rb_cMethod;
25 VALUE rb_cBinding;
26 VALUE rb_cProc;
27
28 static VALUE bmcall(VALUE, VALUE);
29 static int method_arity(VALUE);
30 static VALUE rb_obj_is_method(VALUE m);
31
32 /* Proc */
33
34 static void
35 proc_free(void *ptr)
36 {
37     RUBY_FREE_ENTER("proc");
38     if (ptr) {
39         ruby_xfree(ptr);
40     }
41     RUBY_FREE_LEAVE("proc");
42 }
43
44 static void
45 proc_mark(void *ptr)
46 {
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));
57         }
58     }
59     RUBY_MARK_LEAVE("proc");
60 }
61
62 VALUE
63 rb_proc_alloc(VALUE klass)
64 {
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;
70 }
71
72 VALUE
73 rb_obj_is_proc(VALUE proc)
74 {
75     if (TYPE(proc) == T_DATA &&
76         RDATA(proc)->dfree == (RUBY_DATA_FUNC) proc_free) {
77         return Qtrue;
78     }
79     else {
80         return Qfalse;
81     }
82 }
83
84 static VALUE
85 proc_dup(VALUE self)
86 {
87     VALUE procval = rb_proc_alloc(rb_cProc);
88     rb_proc_t *src, *dst;
89     GetProcPtr(self, src);
90     GetProcPtr(procval, dst);
91
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;
97
98     return procval;
99 }
100
101 static VALUE
102 proc_clone(VALUE self)
103 {
104     VALUE procval = proc_dup(self);
105     CLONESETUP(procval, self);
106     return procval;
107 }
108
109 /*
110  * call-seq:
111  *   prc.lambda? => true or false
112  *
113  * Returns true for a Proc object which argument handling is rigid.
114  * Such procs are typically generated by lambda.
115  *
116  * A Proc object generated by proc ignore extra arguments.
117  *
118  *   proc {|a,b| [a,b] }.call(1,2,3)    => [1,2]
119  *
120  * It provides nil for lacked arguments.
121  *
122  *   proc {|a,b| [a,b] }.call(1)        => [1,nil]
123  *
124  * It expand single-array argument.
125  *
126  *   proc {|a,b| [a,b] }.call([1,2])    => [1,2]
127  *
128  * A Proc object generated by lambda doesn't have such tricks.
129  *
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
133  *
134  * Proc#lambda? is a predicate for the tricks.
135  * It returns true if no tricks.
136  *
137  *   lambda {}.lambda?          => true
138  *   proc {}.lambda?            => false
139  *
140  * Proc.new is same as proc.
141  *
142  *   Proc.new {}.lambda?        => false
143  *
144  * lambda, proc and Proc.new preserves the tricks of
145  * a Proc object given by & argument.
146  *
147  *   lambda(&lambda {}).lambda?   => true
148  *   proc(&lambda {}).lambda?     => true
149  *   Proc.new(&lambda {}).lambda? => true
150  *
151  *   lambda(&proc {}).lambda?   => false
152  *   proc(&proc {}).lambda?     => false
153  *   Proc.new(&proc {}).lambda? => false
154  *
155  * A Proc object generated by & argument has the tricks
156  *
157  *   def n(&b) b.lambda? end
158  *   n {}                       => false
159  *
160  * The & argument preserves the tricks if a Proc object is given
161  * by & argument.
162  *
163  *   n(&lambda {})              => true
164  *   n(&proc {})                => false
165  *   n(&Proc.new {})            => false
166  *
167  * A Proc object converted from a method has no tricks.
168  *
169  *   def m() end
170  *   method(:m).to_proc.lambda? => true
171  *
172  *   n(&method(:m))             => true
173  *   n(&method(:m).to_proc)     => true
174  *
175  * define_method is treated same as method definition.
176  * The defined method has no tricks.
177  *
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
183  *
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.
187  *
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
193  *
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.
196  *
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
206  *
207  * The wrapper, def2, defines a method which has no tricks.
208  *
209  */
210
211 static VALUE
212 proc_lambda_p(VALUE procval)
213 {
214     rb_proc_t *proc;
215     GetProcPtr(procval, proc);
216
217     return proc->is_lambda ? Qtrue : Qfalse;
218 }
219
220 /* Binding */
221
222 static void
223 binding_free(void *ptr)
224 {
225     rb_binding_t *bind;
226     RUBY_FREE_ENTER("binding");
227     if (ptr) {
228         bind = ptr;
229         ruby_xfree(ptr);
230     }
231     RUBY_FREE_LEAVE("binding");
232 }
233
234 static void
235 binding_mark(void *ptr)
236 {
237     rb_binding_t *bind;
238     RUBY_MARK_ENTER("binding");
239     if (ptr) {
240         bind = ptr;
241         RUBY_MARK_UNLESS_NULL(bind->env);
242     }
243     RUBY_MARK_LEAVE("binding");
244 }
245
246 static VALUE
247 binding_alloc(VALUE klass)
248 {
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;
253 }
254
255 static VALUE
256 binding_dup(VALUE self)
257 {
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;
264 }
265
266 static VALUE
267 binding_clone(VALUE self)
268 {
269     VALUE bindval = binding_dup(self);
270     CLONESETUP(bindval, self);
271     return bindval;
272 }
273
274 rb_control_frame_t *vm_get_ruby_level_next_cfp(rb_thread_t *th, rb_control_frame_t *cfp);
275
276 VALUE
277 rb_binding_new(void)
278 {
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;
283
284     if (cfp == 0) {
285         rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber.");
286     }
287
288     GetBindingPtr(bindval, bind);
289     bind->env = vm_make_env_object(th, cfp);
290     return bindval;
291 }
292
293 /*
294  *  call-seq:
295  *     binding -> a_binding
296  *  
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+.
301  *     
302  *     def getBinding(param)
303  *       return binding
304  *     end
305  *     b = getBinding("hello")
306  *     eval("param", b)   #=> "hello"
307  */
308
309 static VALUE
310 rb_f_binding(VALUE self)
311 {
312     return rb_binding_new();
313 }
314
315 /*
316  *  call-seq:
317  *     binding.eval(string [, filename [,lineno]])  => obj
318  *
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.
323  *
324  *     def getBinding(param)
325  *       return binding
326  *     end
327  *     b = getBinding("hello")
328  *     b.eval("param")   #=> "hello"
329  */
330
331 static VALUE
332 bind_eval(int argc, VALUE *argv, VALUE bindval)
333 {
334     VALUE args[4];
335
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 */);
339 }
340
341 static VALUE
342 proc_new(VALUE klass, int is_lambda)
343 {
344     VALUE procval = Qnil;
345     rb_thread_t *th = GET_THREAD();
346     rb_control_frame_t *cfp = th->cfp;
347     rb_block_t *block;
348
349     if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 &&
350         !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) {
351
352         block = GC_GUARDED_PTR_REF(cfp->lfp[0]);
353     }
354     else {
355         cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
356
357         if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 &&
358             !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) {
359
360             block = GC_GUARDED_PTR_REF(cfp->lfp[0]);
361
362             if (is_lambda) {
363                 rb_warn("tried to create Proc object without a block");
364             }
365         }
366         else {
367             rb_raise(rb_eArgError,
368                      "tried to create Proc object without a block");
369         }
370     }
371
372     procval = block->proc;
373
374     if (procval) {
375         if (RBASIC(procval)->klass == klass) {
376             return procval;
377         }
378         else {
379             VALUE newprocval = proc_dup(procval);
380             RBASIC(newprocval)->klass = klass;
381             return newprocval;
382         }
383     }
384
385     procval = vm_make_proc(th, block, klass);
386
387     if (is_lambda) {
388         rb_proc_t *proc;
389         GetProcPtr(procval, proc);
390         proc->is_lambda = Qtrue;
391     }
392     return procval;
393 }
394
395 /*
396  *  call-seq:
397  *     Proc.new {|...| block } => a_proc
398  *     Proc.new                => a_proc
399  *  
400  *  Creates a new <code>Proc</code> object, bound to the current
401  *  context. <code>Proc::new</code> may be called without a block only
402  *  within a method with an attached block, in which case that block is
403  *  converted to the <code>Proc</code> object.
404  *     
405  *     def proc_from
406  *       Proc.new
407  *     end
408  *     proc = proc_from { "hello" }
409  *     proc.call   #=> "hello"
410  */
411
412 static VALUE
413 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
414 {
415     VALUE block = proc_new(klass, Qfalse);
416
417     rb_obj_call_init(block, argc, argv);
418     return block;
419 }
420
421 /*
422  * call-seq:
423  *   proc   { |...| block }  => a_proc
424  *
425  * Equivalent to <code>Proc.new</code>.
426  */
427
428 VALUE
429 rb_block_proc(void)
430 {
431     return proc_new(rb_cProc, Qfalse);
432 }
433
434 VALUE
435 rb_block_lambda(void)
436 {
437     return proc_new(rb_cProc, Qtrue);
438 }
439
440 VALUE
441 rb_f_lambda(void)
442 {
443     rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
444     return rb_block_lambda();
445 }
446
447 /*
448  * call-seq:
449  *   lambda { |...| block }  => a_proc
450  *
451  * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
452  * check the number of parameters passed when called.
453  */
454
455 static VALUE
456 proc_lambda(void)
457 {
458     return rb_block_lambda();
459 }
460
461 /* CHECKME: are the argument checking semantics correct? */
462
463 /*
464  *  call-seq:
465  *     prc.call(params,...)   => obj
466  *     prc[params,...]        => obj
467  *     prc.(params,...)       => obj
468  *  
469  *  Invokes the block, setting the block's parameters to the values in
470  *  <i>params</i> using something close to method calling semantics.
471  *  Generates a warning if multiple values are passed to a proc that
472  *  expects just one (previously this silently converted the parameters
473  *  to an array).  Note that prc.() invokes prc.call() with the parameters
474  *  given.  It's a syntax sugar to hide "call".
475  *
476  *  For procs created using <code>Kernel.proc</code>, generates an
477  *  error if the wrong number of parameters
478  *  are passed to a proc with multiple parameters. For procs created using
479  *  <code>Proc.new</code>, extra parameters are silently discarded.
480  *
481  *  Returns the value of the last expression evaluated in the block. See
482  *  also <code>Proc#yield</code>.
483  *     
484  *     a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
485  *     a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
486  *     a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
487  *     a_proc = Proc.new {|a,b| a}
488  *     a_proc.call(1,2,3)
489  *     
490  *  <em>produces:</em>
491  *     
492  *     prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
493  *      from prog.rb:4:in `call'
494  *      from prog.rb:5
495  */
496
497 /*
498  *  call-seq:
499  *     prc === obj   => obj
500  *  
501  *  Invokes the block, with <i>obj</i> as the block's parameter.  It is
502  *  to allow a proc object to be a target of when clause in the case statement.
503  */
504
505 static VALUE
506 proc_call(int argc, VALUE *argv, VALUE procval)
507 {
508     rb_proc_t *proc;
509     rb_block_t *blockptr = 0;
510     rb_iseq_t *iseq;
511     GetProcPtr(procval, proc);
512
513     iseq = proc->block.iseq;
514     if (BUILTIN_TYPE(iseq) == T_NODE || iseq->arg_block != -1) {
515         if (rb_block_given_p()) {
516             rb_proc_t *proc;
517             VALUE procval;
518             procval = rb_block_proc();
519             GetProcPtr(procval, proc);
520             blockptr = &proc->block;
521         }
522     }
523
524     return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
525                           argc, argv, blockptr);
526 }
527
528 VALUE
529 rb_proc_call(VALUE self, VALUE args)
530 {
531     rb_proc_t *proc;
532     GetProcPtr(self, proc);
533     return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
534                           RARRAY_LEN(args), RARRAY_PTR(args), 0);
535 }
536
537 VALUE
538 rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval)
539 {
540     rb_proc_t *proc;
541     rb_block_t *block = 0;
542     GetProcPtr(self, proc);
543
544     if (!NIL_P(pass_procval)) {
545         rb_proc_t *pass_proc;
546         GetProcPtr(pass_procval, pass_proc);
547         block = &pass_proc->block;
548     }
549
550     return vm_invoke_proc(GET_THREAD(), proc, proc->block.self,
551                           argc, argv, block);
552 }
553
554 /*
555  *  call-seq:
556  *     prc.arity -> fixnum
557  *  
558  *  Returns the number of arguments that would not be ignored. If the block
559  *  is declared to take no arguments, returns 0. If the block is known
560  *  to take exactly n arguments, returns n. If the block has optional
561  *  arguments, return -n-1, where n is the number of mandatory
562  *  arguments. A <code>proc</code> with no argument declarations
563  *  is the same a block declaring <code>||</code> as its arguments.
564  *     
565  *     Proc.new {}.arity          #=>  0
566  *     Proc.new {||}.arity        #=>  0
567  *     Proc.new {|a|}.arity       #=>  1
568  *     Proc.new {|a,b|}.arity     #=>  2
569  *     Proc.new {|a,b,c|}.arity   #=>  3
570  *     Proc.new {|*a|}.arity      #=> -1
571  *     Proc.new {|a,*b|}.arity    #=> -2
572  *     Proc.new {|a,*b, c|}.arity    #=> -3
573  */
574
575 static VALUE
576 proc_arity(VALUE self)
577 {
578     rb_proc_t *proc;
579     rb_iseq_t *iseq;
580     GetProcPtr(self, proc);
581     iseq = proc->block.iseq;
582     if (iseq) {
583         if (BUILTIN_TYPE(iseq) != T_NODE) {
584             if (iseq->arg_rest < 0) {
585                 return INT2FIX(iseq->argc);
586             }
587             else {
588                 return INT2FIX(-(iseq->argc + 1 + iseq->arg_post_len));
589             }
590         }
591         else {
592             NODE *node = (NODE *)iseq;
593             if (nd_type(node) == NODE_IFUNC && node->nd_cfnc == bmcall) {
594                 /* method(:foo).to_proc.arity */
595                 return INT2FIX(method_arity(node->nd_tval));
596             }
597         }
598     }
599     return INT2FIX(-1);
600 }
601
602 int
603 rb_proc_arity(VALUE proc)
604 {
605     return FIX2INT(proc_arity(proc));
606 }
607
608 static rb_iseq_t *
609 get_proc_iseq(VALUE self)
610 {
611     rb_proc_t *proc;
612     rb_iseq_t *iseq;
613
614     GetProcPtr(self, proc);
615     iseq = proc->block.iseq;
616     if (!RUBY_VM_NORMAL_ISEQ_P(iseq))
617         return 0;
618     return iseq;
619 }
620
621 static VALUE
622 iseq_location(rb_iseq_t *iseq)
623 {
624     VALUE loc[2];
625
626     if (!iseq) return Qnil;
627     loc[0] = iseq->filename;
628     if (iseq->insn_info_table) {
629         loc[1] = INT2FIX(rb_iseq_first_lineno(iseq));
630     }
631     else {
632         loc[1] = Qnil;
633     }
634     return rb_ary_new4(2, loc);
635 }
636
637 /*
638  * call-seq:
639  *    prc.source_location  => [String, Fixnum]
640  *
641  * returns the ruby source filename and line number containing this proc
642  * or nil if this proc was not defined in ruby (i.e. native)
643  */
644
645 VALUE
646 rb_proc_location(VALUE self)
647 {
648     return iseq_location(get_proc_iseq(self));
649 }
650
651 /*
652  * call-seq:
653  *   prc == other_proc   =>  true or false
654  *
655  * Return <code>true</code> if <i>prc</i> is the same object as
656  * <i>other_proc</i>, or if they are both procs with the same body.
657  */
658
659 static VALUE
660 proc_eq(VALUE self, VALUE other)
661 {
662     if (self == other) {
663         return Qtrue;
664     }
665     else {
666         if (TYPE(other)          == T_DATA &&
667             RDATA(other)->dmark  == proc_mark) {
668             rb_proc_t *p1, *p2;
669             GetProcPtr(self, p1);
670             GetProcPtr(other, p2);
671             if (p1->envval == p2->envval &&
672                 p1->block.iseq->iseq_size == p2->block.iseq->iseq_size &&
673                 p1->block.iseq->local_size == p2->block.iseq->local_size &&
674                 MEMCMP(p1->block.iseq->iseq, p2->block.iseq->iseq, VALUE,
675                        p1->block.iseq->iseq_size) == 0) {
676                 return Qtrue;
677             }
678         }
679     }
680     return Qfalse;
681 }
682
683 /*
684  * call-seq:
685  *   prc.hash   =>  integer
686  *
687  * Return hash value corresponding to proc body.
688  */
689
690 static VALUE
691 proc_hash(VALUE self)
692 {
693     int hash;
694     rb_proc_t *proc;
695     GetProcPtr(self, proc);
696     hash = (long)proc->block.iseq;
697     hash ^= (long)proc->envval;
698     hash ^= (long)proc->block.lfp >> 16;
699     return INT2FIX(hash);
700 }
701
702 /*
703  * call-seq:
704  *   prc.to_s   => string
705  *
706  * Shows the unique identifier for this proc, along with
707  * an indication of where the proc was defined.
708  */
709
710 static VALUE
711 proc_to_s(VALUE self)
712 {
713     VALUE str = 0;
714     rb_proc_t *proc;
715     const char *cname = rb_obj_classname(self);
716     rb_iseq_t *iseq;
717     const char *is_lambda;
718     
719     GetProcPtr(self, proc);
720     iseq = proc->block.iseq;
721     is_lambda = proc->is_lambda ? " (lambda)" : "";
722
723     if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
724         int line_no = 0;
725         
726         if (iseq->insn_info_table) {
727             line_no = rb_iseq_first_lineno(iseq);
728         }
729         str = rb_sprintf("#<%s:%p@%s:%d%s>", cname, (void *)self,
730                          RSTRING_PTR(iseq->filename),
731                          line_no, is_lambda);
732     }
733     else {
734         str = rb_sprintf("#<%s:%p%s>", cname, (void *)proc->block.iseq,
735                          is_lambda);
736     }
737
738     if (OBJ_TAINTED(self)) {
739         OBJ_TAINT(str);
740     }
741     return str;
742 }
743
744 /*
745  *  call-seq:
746  *     prc.to_proc -> prc
747  *  
748  *  Part of the protocol for converting objects to <code>Proc</code>
749  *  objects. Instances of class <code>Proc</code> simply return
750  *  themselves.
751  */
752
753 static VALUE
754 proc_to_proc(VALUE self)
755 {
756     return self;
757 }
758
759 static void
760 bm_mark(struct METHOD *data)
761 {
762     rb_gc_mark(data->rclass);
763     rb_gc_mark(data->oclass);
764     rb_gc_mark(data->recv);
765     rb_gc_mark((VALUE)data->body);
766 }
767
768 NODE *
769 rb_method_body(VALUE method)
770 {
771     struct METHOD *data;
772
773     if (TYPE(method) == T_DATA &&
774         RDATA(method)->dmark == (RUBY_DATA_FUNC) bm_mark) {
775         Data_Get_Struct(method, struct METHOD, data);
776         return data->body;
777     }
778     else {
779         return 0;
780     }
781 }
782
783 NODE *rb_get_method_body(VALUE klass, ID id, ID *idp);
784
785 static VALUE
786 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
787 {
788     VALUE method;
789     NODE *body;
790     struct METHOD *data;
791     VALUE rclass = klass;
792     ID oid = id;
793
794   again:
795     if ((body = rb_get_method_body(klass, id, 0)) == 0) {
796         rb_print_undef(rclass, oid, 0);
797     }
798     if (scope && (body->nd_noex & NOEX_MASK) != NOEX_PUBLIC) {
799         rb_print_undef(rclass, oid, (body->nd_noex & NOEX_MASK));
800     }
801
802     klass = body->nd_clss;
803     body = body->nd_body;
804
805     if (nd_type(body) == NODE_ZSUPER) {
806         klass = RCLASS_SUPER(klass);
807         goto again;
808     }
809
810     while (rclass != klass &&
811            (FL_TEST(rclass, FL_SINGLETON) || TYPE(rclass) == T_ICLASS)) {
812         rclass = RCLASS_SUPER(rclass);
813     }
814     if (TYPE(klass) == T_ICLASS)
815         klass = RBASIC(klass)->klass;
816     method = Data_Make_Struct(mclass, struct METHOD, bm_mark, -1, data);
817     data->oclass = klass;
818     data->recv = obj;
819
820     data->id = id;
821     data->body = body;
822     data->rclass = rclass;
823     data->oid = oid;
824     OBJ_INFECT(method, klass);
825
826     return method;
827 }
828
829
830 /**********************************************************************
831  *
832  * Document-class : Method
833  *
834  *  Method objects are created by <code>Object#method</code>, and are
835  *  associated with a particular object (not just with a class). They
836  *  may be used to invoke the method within the object, and as a block
837  *  associated with an iterator. They may also be unbound from one
838  *  object (creating an <code>UnboundMethod</code>) and bound to
839  *  another.
840  *     
841  *     class Thing
842  *       def square(n)
843  *         n*n
844  *       end
845  *     end
846  *     thing = Thing.new
847  *     meth  = thing.method(:square)
848  *     
849  *     meth.call(9)                 #=> 81
850  *     [ 1, 2, 3 ].collect(&meth)   #=> [1, 4, 9]
851  *     
852  */
853
854 /*
855  * call-seq:
856  *   meth == other_meth  => true or false
857  *
858  * Two method objects are equal if that are bound to the same
859  * object and contain the same body.
860  */
861
862
863 static VALUE
864 method_eq(VALUE method, VALUE other)
865 {
866     struct METHOD *m1, *m2;
867
868     if (TYPE(other) != T_DATA
869         || RDATA(other)->dmark != (RUBY_DATA_FUNC) bm_mark)
870         return Qfalse;
871     if (CLASS_OF(method) != CLASS_OF(other))
872         return Qfalse;
873
874     Data_Get_Struct(method, struct METHOD, m1);
875     Data_Get_Struct(other, struct METHOD, m2);
876
877     if (m1->oclass != m2->oclass || m1->rclass != m2->rclass ||
878         m1->recv != m2->recv || m1->body != m2->body)
879         return Qfalse;
880
881     return Qtrue;
882 }
883
884 /*
885  * call-seq:
886  *    meth.hash   => integer
887  *
888  * Return a hash value corresponding to the method object.
889  */
890
891 static VALUE
892 method_hash(VALUE method)
893 {
894     struct METHOD *m;
895     long hash;
896
897     Data_Get_Struct(method, struct METHOD, m);
898     hash = (long)m->oclass;
899     hash ^= (long)m->rclass;
900     hash ^= (long)m->recv;
901     hash ^= (long)m->body;
902
903     return INT2FIX(hash);
904 }
905
906 /*
907  *  call-seq:
908  *     meth.unbind    => unbound_method
909  *  
910  *  Dissociates <i>meth</i> from it's current receiver. The resulting
911  *  <code>UnboundMethod</code> can subsequently be bound to a new object
912  *  of the same class (see <code>UnboundMethod</code>).
913  */
914
915 static VALUE
916 method_unbind(VALUE obj)
917 {
918     VALUE method;
919     struct METHOD *orig, *data;
920
921     Data_Get_Struct(obj, struct METHOD, orig);
922     method =
923         Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, -1, data);
924     data->oclass = orig->oclass;
925     data->recv = Qundef;
926     data->id = orig->id;
927     data->body = orig->body;
928     data->rclass = orig->rclass;
929     data->oid = orig->oid;
930     OBJ_INFECT(method, obj);
931
932     return method;
933 }
934
935 /*
936  *  call-seq:
937  *     meth.receiver    => object
938  *  
939  *  Returns the bound receiver of the method object.
940  */
941
942 static VALUE
943 method_receiver(VALUE obj)
944 {
945     struct METHOD *data;
946
947     Data_Get_Struct(obj, struct METHOD, data);
948     return data->recv;
949 }
950
951 /*
952  *  call-seq:
953  *     meth.name    => symbol
954  *  
955  *  Returns the name of the method.
956  */
957
958 static VALUE
959 method_name(VALUE obj)
960 {
961     struct METHOD *data;
962
963     Data_Get_Struct(obj, struct METHOD, data);
964     return ID2SYM(data->id);
965 }
966
967 /*
968  *  call-seq:
969  *     meth.owner    => class_or_module
970  *  
971  *  Returns the class or module that defines the method.
972  */
973
974 static VALUE
975 method_owner(VALUE obj)
976 {
977     struct METHOD *data;
978
979     Data_Get_Struct(obj, struct METHOD, data);
980     return data->oclass;
981 }
982
983 /*
984  *  call-seq:
985  *     obj.method(sym)    => method
986  *  
987  *  Looks up the named method as a receiver in <i>obj</i>, returning a
988  *  <code>Method</code> object (or raising <code>NameError</code>). The
989  *  <code>Method</code> object acts as a closure in <i>obj</i>'s object
990  *  instance, so instance variables and the value of <code>self</code>
991  *  remain available.
992  *     
993  *     class Demo
994  *       def initialize(n)
995  *         @iv = n
996  *       end
997  *       def hello()
998  *         "Hello, @iv = #{@iv}"
999  *       end
1000  *     end
1001  *     
1002  *     k = Demo.new(99)
1003  *     m = k.method(:hello)
1004  *     m.call   #=> "Hello, @iv = 99"
1005  *     
1006  *     l = Demo.new('Fred')
1007  *     m = l.method("hello")
1008  *     m.call   #=> "Hello, @iv = Fred"
1009  */
1010
1011 VALUE
1012 rb_obj_method(VALUE obj, VALUE vid)
1013 {
1014     return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qfalse);
1015 }
1016
1017 VALUE
1018 rb_obj_public_method(VALUE obj, VALUE vid)
1019 {
1020     return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qtrue);
1021 }
1022
1023 /*
1024  *  call-seq:
1025  *     mod.instance_method(symbol)   => unbound_method
1026  *  
1027  *  Returns an +UnboundMethod+ representing the given
1028  *  instance method in _mod_.
1029  *     
1030  *     class Interpreter
1031  *       def do_a() print "there, "; end
1032  *       def do_d() print "Hello ";  end
1033  *       def do_e() print "!\n";     end
1034  *       def do_v() print "Dave";    end
1035  *       Dispatcher = {
1036  *        ?a => instance_method(:do_a),
1037  *        ?d => instance_method(:do_d),
1038  *        ?e => instance_method(:do_e),
1039  *        ?v => instance_method(:do_v)
1040  *       }
1041  *       def interpret(string)
1042  *         string.each_byte {|b| Dispatcher[b].bind(self).call }
1043  *       end
1044  *     end
1045  *     
1046  *     
1047  *     interpreter = Interpreter.new
1048  *     interpreter.interpret('dave')
1049  *     
1050  *  <em>produces:</em>
1051  *     
1052  *     Hello there, Dave!
1053  */
1054
1055 static VALUE
1056 rb_mod_instance_method(VALUE mod, VALUE vid)
1057 {
1058     return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qfalse);
1059 }
1060
1061 static VALUE
1062 rb_mod_public_instance_method(VALUE mod, VALUE vid)
1063 {
1064     return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qtrue);
1065 }
1066
1067 /*
1068  *  call-seq:
1069  *     define_method(symbol, method)     => new_method
1070  *     define_method(symbol) { block }   => proc
1071  *  
1072  *  Defines an instance method in the receiver. The _method_
1073  *  parameter can be a +Proc+ or +Method+ object.
1074  *  If a block is specified, it is used as the method body. This block
1075  *  is evaluated using <code>instance_eval</code>, a point that is
1076  *  tricky to demonstrate because <code>define_method</code> is private.
1077  *  (This is why we resort to the +send+ hack in this example.)
1078  *     
1079  *     class A
1080  *       def fred
1081  *         puts "In Fred"
1082  *       end
1083  *       def create_method(name, &block)
1084  *         self.class.send(:define_method, name, &block)
1085  *       end
1086  *       define_method(:wilma) { puts "Charge it!" }
1087  *     end
1088  *     class B < A
1089  *       define_method(:barney, instance_method(:fred))
1090  *     end
1091  *     a = B.new
1092  *     a.barney
1093  *     a.wilma
1094  *     a.create_method(:betty) { p self }
1095  *     a.betty
1096  *     
1097  *  <em>produces:</em>
1098  *     
1099  *     In Fred
1100  *     Charge it!
1101  *     #<B:0x401b39e8>
1102  */
1103
1104 static VALUE
1105 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
1106 {
1107     ID id;
1108     VALUE body;
1109     NODE *node;
1110     int noex = NOEX_PUBLIC;
1111
1112     if (argc == 1) {
1113         id = rb_to_id(argv[0]);
1114         body = rb_block_lambda();
1115     }
1116     else if (argc == 2) {
1117         id = rb_to_id(argv[0]);
1118         body = argv[1];
1119         if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) {
1120             rb_raise(rb_eTypeError,
1121                      "wrong argument type %s (expected Proc/Method)",
1122                      rb_obj_classname(body));
1123         }
1124     }
1125     else {
1126         rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
1127     }
1128
1129     if (RDATA(body)->dmark == (RUBY_DATA_FUNC) bm_mark) {
1130         struct METHOD *method = (struct METHOD *)DATA_PTR(body);
1131         VALUE rclass = method->rclass;
1132         if (rclass != mod) {
1133             if (FL_TEST(rclass, FL_SINGLETON)) {
1134                 rb_raise(rb_eTypeError,
1135                          "can't bind singleton method to a different class");
1136             }
1137             if (!RTEST(rb_class_inherited_p(mod, rclass))) {
1138                 rb_raise(rb_eTypeError,
1139                          "bind argument must be a subclass of %s",
1140                          rb_class2name(rclass));
1141             }
1142         }
1143         node = method->body;
1144     }
1145     else if (rb_obj_is_proc(body)) {
1146         rb_proc_t *proc;
1147         body = proc_dup(body);
1148         GetProcPtr(body, proc);
1149         if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) {
1150             proc->block.iseq->defined_method_id = id;
1151             proc->block.iseq->klass = mod;
1152             proc->is_lambda = Qtrue;
1153             proc->is_from_method = Qtrue;
1154         }
1155         node = NEW_BMETHOD(body);
1156     }
1157     else {
1158         /* type error */
1159         rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
1160     }
1161
1162     /* TODO: visibility */
1163
1164     rb_add_method(mod, id, node, noex);
1165     return body;
1166 }
1167
1168 static VALUE
1169 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
1170 {
1171     VALUE klass = rb_singleton_class(obj);
1172
1173     return rb_mod_define_method(argc, argv, klass);
1174 }
1175
1176
1177 /*
1178  * MISSING: documentation
1179  */
1180
1181 static VALUE
1182 method_clone(VALUE self)
1183 {
1184     VALUE clone;
1185     struct METHOD *orig, *data;
1186
1187     Data_Get_Struct(self, struct METHOD, orig);
1188     clone = Data_Make_Struct(CLASS_OF(self), struct METHOD, bm_mark, -1, data);
1189     CLONESETUP(clone, self);
1190     *data = *orig;
1191
1192     return clone;
1193 }
1194
1195 /*
1196  *  call-seq:
1197  *     meth.call(args, ...)    => obj
1198  *     meth[args, ...]         => obj
1199  *  
1200  *  Invokes the <i>meth</i> with the specified arguments, returning the
1201  *  method's return value.
1202  *     
1203  *     m = 12.method("+")
1204  *     m.call(3)    #=> 15
1205  *     m.call(20)   #=> 32
1206  */
1207
1208 VALUE
1209 rb_method_call(int argc, VALUE *argv, VALUE method)
1210 {
1211     VALUE result = Qnil;        /* OK */
1212     struct METHOD *data;
1213     int state;
1214     volatile int safe = -1;
1215
1216     Data_Get_Struct(method, struct METHOD, data);
1217     if (data->recv == Qundef) {
1218         rb_raise(rb_eTypeError, "can't call unbound method; bind first");
1219     }
1220     PUSH_TAG();
1221     if (OBJ_TAINTED(method)) {
1222         safe = rb_safe_level();
1223         if (rb_safe_level() < 4) {
1224             rb_set_safe_level_force(4);
1225         }
1226     }
1227     if ((state = EXEC_TAG()) == 0) {
1228         rb_thread_t *th = GET_THREAD();
1229         VALUE rb_vm_call(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid,
1230                          int argc, const VALUE *argv, const NODE *body, int nosuper);
1231
1232         PASS_PASSED_BLOCK_TH(th);
1233         result = rb_vm_call(th, data->oclass, data->recv, data->id, data->oid,
1234                             argc, argv, data->body, 0);
1235     }
1236     POP_TAG();
1237     if (safe >= 0)
1238         rb_set_safe_level_force(safe);
1239     if (state)
1240         JUMP_TAG(state);
1241     return result;
1242 }
1243
1244 /**********************************************************************
1245  *
1246  * Document-class: UnboundMethod
1247  *
1248  *  Ruby supports two forms of objectified methods. Class
1249  *  <code>Method</code> is used to represent methods that are associated
1250  *  with a particular object: these method objects are bound to that
1251  *  object. Bound method objects for an object can be created using
1252  *  <code>Object#method</code>.
1253  *     
1254  *  Ruby also supports unbound methods; methods objects that are not
1255  *  associated with a particular object. These can be created either by
1256  *  calling <code>Module#instance_method</code> or by calling
1257  *  <code>unbind</code> on a bound method object. The result of both of
1258  *  these is an <code>UnboundMethod</code> object.
1259  *     
1260  *  Unbound methods can only be called after they are bound to an
1261  *  object. That object must be be a kind_of? the method's original
1262  *  class.
1263  *     
1264  *     class Square
1265  *       def area
1266  *         @side * @side
1267  *       end
1268  *       def initialize(side)
1269  *         @side = side
1270  *       end
1271  *     end
1272  *     
1273  *     area_un = Square.instance_method(:area)
1274  *     
1275  *     s = Square.new(12)
1276  *     area = area_un.bind(s)
1277  *     area.call   #=> 144
1278  *     
1279  *  Unbound methods are a reference to the method at the time it was
1280  *  objectified: subsequent changes to the underlying class will not
1281  *  affect the unbound method.
1282  *     
1283  *     class Test
1284  *       def test
1285  *         :original
1286  *       end
1287  *     end
1288  *     um = Test.instance_method(:test)
1289  *     class Test
1290  *       def test
1291  *         :modified
1292  *       end
1293  *     end
1294  *     t = Test.new
1295  *     t.test            #=> :modified
1296  *     um.bind(t).call   #=> :original
1297  *     
1298  */
1299
1300 /*
1301  *  call-seq:
1302  *     umeth.bind(obj) -> method
1303  *  
1304  *  Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
1305  *  from which <i>umeth</i> was obtained,
1306  *  <code>obj.kind_of?(Klass)</code> must be true.
1307  *     
1308  *     class A
1309  *       def test
1310  *         puts "In test, class = #{self.class}"
1311  *       end
1312  *     end
1313  *     class B < A
1314  *     end
1315  *     class C < B
1316  *     end
1317  *     
1318  *     
1319  *     um = B.instance_method(:test)
1320  *     bm = um.bind(C.new)
1321  *     bm.call
1322  *     bm = um.bind(B.new)
1323  *     bm.call
1324  *     bm = um.bind(A.new)
1325  *     bm.call
1326  *     
1327  *  <em>produces:</em>
1328  *     
1329  *     In test, class = C
1330  *     In test, class = B
1331  *     prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
1332  *      from prog.rb:16
1333  */
1334
1335 static VALUE
1336 umethod_bind(VALUE method, VALUE recv)
1337 {
1338     struct METHOD *data, *bound;
1339
1340     Data_Get_Struct(method, struct METHOD, data);
1341     if (data->rclass != CLASS_OF(recv)) {
1342         if (FL_TEST(data->rclass, FL_SINGLETON)) {
1343             rb_raise(rb_eTypeError,
1344                      "singleton method called for a different object");
1345         }
1346         if (!rb_obj_is_kind_of(recv, data->rclass)) {
1347             rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
1348                      rb_class2name(data->rclass));
1349         }
1350     }
1351
1352     method = Data_Make_Struct(rb_cMethod, struct METHOD, bm_mark, -1, bound);
1353     *bound = *data;
1354     bound->recv = recv;
1355     bound->rclass = CLASS_OF(recv);
1356
1357     return method;
1358 }
1359
1360 int
1361 rb_node_arity(NODE* body)
1362 {
1363     switch (nd_type(body)) {
1364       case NODE_CFUNC:
1365         if (body->nd_argc < 0)
1366             return -1;
1367         return body->nd_argc;
1368       case NODE_ZSUPER:
1369         return -1;
1370       case NODE_ATTRSET:
1371         return 1;
1372       case NODE_IVAR:
1373         return 0;
1374       case NODE_BMETHOD:
1375         return rb_proc_arity(body->nd_cval);
1376       case RUBY_VM_METHOD_NODE:
1377         {
1378             rb_iseq_t *iseq;
1379             GetISeqPtr((VALUE)body->nd_body, iseq);
1380             if (iseq->arg_rest == -1 && iseq->arg_opts == 0) {
1381                 return iseq->argc;
1382             }
1383             else {
1384                 return -(iseq->argc + 1 + iseq->arg_post_len);
1385             }
1386         }
1387       default:
1388         rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body));
1389     }
1390 }
1391
1392 /*
1393  *  call-seq:
1394  *     meth.arity    => fixnum
1395  *  
1396  *  Returns an indication of the number of arguments accepted by a
1397  *  method. Returns a nonnegative integer for methods that take a fixed
1398  *  number of arguments. For Ruby methods that take a variable number of
1399  *  arguments, returns -n-1, where n is the number of required
1400  *  arguments. For methods written in C, returns -1 if the call takes a
1401  *  variable number of arguments.
1402  *     
1403  *     class C
1404  *       def one;    end
1405  *       def two(a); end
1406  *       def three(*a);  end
1407  *       def four(a, b); end
1408  *       def five(a, b, *c);    end
1409  *       def six(a, b, *c, &d); end
1410  *     end
1411  *     c = C.new
1412  *     c.method(:one).arity     #=> 0
1413  *     c.method(:two).arity     #=> 1
1414  *     c.method(:three).arity   #=> -1
1415  *     c.method(:four).arity    #=> 2
1416  *     c.method(:five).arity    #=> -3
1417  *     c.method(:six).arity     #=> -3
1418  *     
1419  *     "cat".method(:size).arity      #=> 0
1420  *     "cat".method(:replace).arity   #=> 1
1421  *     "cat".method(:squeeze).arity   #=> -1
1422  *     "cat".method(:count).arity     #=> -1
1423  */
1424
1425 static VALUE
1426 method_arity_m(VALUE method)
1427 {
1428     int n = method_arity(method);
1429     return INT2FIX(n);
1430 }
1431
1432 static int
1433 method_arity(VALUE method)
1434 {
1435     struct METHOD *data;
1436
1437     Data_Get_Struct(method, struct METHOD, data);
1438     return rb_node_arity(data->body);
1439 }
1440
1441 int
1442 rb_mod_method_arity(VALUE mod, ID id)
1443 {
1444     NODE *node = rb_method_node(mod, id);
1445     return rb_node_arity(node);
1446 }
1447
1448 int
1449 rb_obj_method_arity(VALUE obj, ID id)
1450 {
1451     return rb_mod_method_arity(CLASS_OF(obj), id);
1452 }
1453
1454 static rb_iseq_t *
1455 get_method_iseq(VALUE method)
1456 {
1457     struct METHOD *data;
1458     NODE *body;
1459     rb_iseq_t *iseq;
1460
1461     Data_Get_Struct(method, struct METHOD, data);
1462     body = data->body;
1463     switch (nd_type(body)) {
1464       case RUBY_VM_METHOD_NODE:
1465         GetISeqPtr((VALUE)body->nd_body, iseq);
1466         if (RUBY_VM_NORMAL_ISEQ_P(iseq)) break;
1467       default:
1468         return 0;
1469     }
1470     return iseq;
1471 }
1472
1473 /*
1474  * call-seq:
1475  *    meth.source_location  => [String, Fixnum]
1476  *
1477  * returns the ruby source filename and line number containing this method
1478  * or nil if this method was not defined in ruby (i.e. native)
1479  */
1480
1481 VALUE
1482 rb_method_location(VALUE method)
1483 {
1484     return iseq_location(get_method_iseq(method));
1485 }
1486
1487 /*
1488  *  call-seq:
1489  *   meth.to_s      =>  string
1490  *   meth.inspect   =>  string
1491  *
1492  *  Show the name of the underlying method.
1493  *
1494  *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
1495  */
1496
1497 static VALUE
1498 method_inspect(VALUE method)
1499 {
1500     struct METHOD *data;
1501     VALUE str;
1502     const char *s;
1503     const char *sharp = "#";
1504
1505     Data_Get_Struct(method, struct METHOD, data);
1506     str = rb_str_buf_new2("#<");
1507     s = rb_obj_classname(method);
1508     rb_str_buf_cat2(str, s);
1509     rb_str_buf_cat2(str, ": ");
1510
1511     if (FL_TEST(data->oclass, FL_SINGLETON)) {
1512         VALUE v = rb_iv_get(data->oclass, "__attached__");
1513
1514         if (data->recv == Qundef) {
1515             rb_str_buf_append(str, rb_inspect(data->oclass));
1516         }
1517         else if (data->recv == v) {
1518             rb_str_buf_append(str, rb_inspect(v));
1519             sharp = ".";
1520         }
1521         else {
1522             rb_str_buf_append(str, rb_inspect(data->recv));
1523             rb_str_buf_cat2(str, "(");
1524             rb_str_buf_append(str, rb_inspect(v));
1525             rb_str_buf_cat2(str, ")");
1526             sharp = ".";
1527         }
1528     }
1529     else {
1530         rb_str_buf_cat2(str, rb_class2name(data->rclass));
1531         if (data->rclass != data->oclass) {
1532             rb_str_buf_cat2(str, "(");
1533             rb_str_buf_cat2(str, rb_class2name(data->oclass));
1534             rb_str_buf_cat2(str, ")");
1535         }
1536     }
1537     rb_str_buf_cat2(str, sharp);
1538     rb_str_append(str, rb_id2str(data->oid));
1539     rb_str_buf_cat2(str, ">");
1540
1541     return str;
1542 }
1543
1544 static VALUE
1545 mproc(VALUE method)
1546 {
1547     return rb_funcall(Qnil, rb_intern("proc"), 0);
1548 }
1549
1550 static VALUE
1551 mlambda(VALUE method)
1552 {
1553     return rb_funcall(Qnil, rb_intern("lambda"), 0);
1554 }
1555
1556 static VALUE
1557 bmcall(VALUE args, VALUE method)
1558 {
1559     volatile VALUE a;
1560
1561     if (CLASS_OF(args) != rb_cArray) {
1562         args = rb_ary_new3(1, args);
1563     }
1564
1565     a = args;
1566     return rb_method_call(RARRAY_LEN(a), RARRAY_PTR(a), method);
1567 }
1568
1569 VALUE
1570 rb_proc_new(
1571     VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */
1572     VALUE val)
1573 {
1574     VALUE procval = rb_iterate(mproc, 0, func, val);
1575     return procval;
1576 }
1577
1578 /*
1579  *  call-seq:
1580  *     meth.to_proc    => prc
1581  *  
1582  *  Returns a <code>Proc</code> object corresponding to this method.
1583  */
1584
1585 static VALUE
1586 method_proc(VALUE method)
1587 {
1588     VALUE procval;
1589     rb_proc_t *proc;
1590     /*
1591      * class Method
1592      *   def to_proc
1593      *     proc{|*args|
1594      *       self.call(*args)
1595      *     }
1596      *   end
1597      * end
1598      */
1599     procval = rb_iterate(mlambda, 0, bmcall, method);
1600     GetProcPtr(procval, proc);
1601     proc->is_from_method = 1;
1602     return procval;
1603 }
1604
1605 static VALUE
1606 rb_obj_is_method(VALUE m)
1607 {
1608     if (TYPE(m) == T_DATA && RDATA(m)->dmark == (RUBY_DATA_FUNC) bm_mark) {
1609         return Qtrue;
1610     }
1611     return Qfalse;
1612 }
1613
1614 /*
1615  * call_seq:
1616  *   local_jump_error.exit_value  => obj
1617  *
1618  * Returns the exit value associated with this +LocalJumpError+.
1619  */
1620 static VALUE
1621 localjump_xvalue(VALUE exc)
1622 {
1623     return rb_iv_get(exc, "@exit_value");
1624 }
1625
1626 /*
1627  * call-seq:
1628  *    local_jump_error.reason   => symbol
1629  *
1630  * The reason this block was terminated:
1631  * :break, :redo, :retry, :next, :return, or :noreason.
1632  */
1633
1634 static VALUE
1635 localjump_reason(VALUE exc)
1636 {
1637     return rb_iv_get(exc, "@reason");
1638 }
1639
1640 /*
1641  *  call-seq:
1642  *     prc.binding    => binding
1643  *  
1644  *  Returns the binding associated with <i>prc</i>. Note that
1645  *  <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
1646  *  <code>Binding</code> object as its second parameter.
1647  *     
1648  *     def fred(param)
1649  *       proc {}
1650  *     end
1651  *     
1652  *     b = fred(99)
1653  *     eval("param", b.binding)   #=> 99
1654  */
1655 static VALUE
1656 proc_binding(VALUE self)
1657 {
1658     rb_proc_t *proc;
1659     VALUE bindval = binding_alloc(rb_cBinding);
1660     rb_binding_t *bind;
1661
1662     GetProcPtr(self, proc);
1663     GetBindingPtr(bindval, bind);
1664
1665     if (TYPE(proc->block.iseq) == T_NODE) {
1666         rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
1667     }
1668
1669     bind->env = proc->envval;
1670     return bindval;
1671 }
1672
1673 static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc);
1674
1675 static VALUE
1676 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
1677 {
1678     VALUE args = rb_ary_new3(3, proc, passed, arity);
1679     rb_ary_freeze(passed);
1680     rb_ary_freeze(args);
1681     return rb_proc_new(curry, args);
1682 }
1683
1684 static VALUE
1685 curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc)
1686 {
1687     VALUE proc, passed, arity;
1688     proc = RARRAY_PTR(args)[0];
1689     passed = RARRAY_PTR(args)[1];
1690     arity = RARRAY_PTR(args)[2];
1691
1692     passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
1693     rb_ary_freeze(passed);
1694
1695     if(RARRAY_LEN(passed) < FIX2INT(arity)) {
1696         if (!NIL_P(passed_proc)) {
1697             rb_warn("given block not used");
1698         }
1699         arity = make_curry_proc(proc, passed, arity);
1700         return arity;
1701     }
1702     else {
1703         return rb_proc_call_with_block(proc, RARRAY_LEN(passed), RARRAY_PTR(passed), passed_proc);
1704     }
1705 }
1706
1707  /*
1708   *  call-seq:
1709   *     prc.curry         => a_proc
1710   *     prc.curry(arity)  => a_proc
1711   *
1712   *  Returns a curried proc. If the optional <i>arity</i> argument is given,
1713   *  it determines the number of arguments.
1714   *  A curried proc receives some arguments. If a sufficient number of
1715   *  arguments are supplied, it passes the supplied arguments to the original
1716   *  proc and returns the result. Otherwise, returns another curried proc that
1717   *  takes the rest of arguments.
1718   *
1719   *     b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
1720   *     p b.curry[1][2][3]           #=> 6
1721   *     p b.curry[1, 2][3, 4]        #=> 6
1722   *     p b.curry(5)[1][2][3][4][5]  #=> 6
1723   *     p b.curry(5)[1, 2][3, 4][5]  #=> 6
1724   *     p b.curry(1)[1]              #=> 1
1725   *
1726   *     b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1727   *     p b.curry[1][2][3]           #=> 6
1728   *     p b.curry[1, 2][3, 4]        #=> 10
1729   *     p b.curry(5)[1][2][3][4][5]  #=> 15
1730   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
1731   *     p b.curry(1)[1]              #=> 1
1732   *
1733   *     b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
1734   *     p b.curry[1][2][3]           #=> 6
1735   *     p b.curry[1, 2][3, 4]        #=> wrong number of arguments (4 or 3)
1736   *     p b.curry(5)                 #=> wrong number of arguments (5 or 3)
1737   *     p b.curry(1)                 #=> wrong number of arguments (1 or 3)
1738   *
1739   *     b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
1740   *     p b.curry[1][2][3]           #=> 6
1741   *     p b.curry[1, 2][3, 4]        #=> 10
1742   *     p b.curry(5)[1][2][3][4][5]  #=> 15
1743   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
1744   *     p b.curry(1)                 #=> wrong number of arguments (1 or 3)
1745   *
1746   *     b = proc { :foo }
1747   *     p b.curry[]                  #=> :foo
1748   */
1749 static VALUE
1750 proc_curry(int argc, VALUE *argv, VALUE self)
1751 {
1752     int sarity, marity = FIX2INT(proc_arity(self));
1753     VALUE arity, opt = Qfalse;
1754
1755     if (marity < 0) {
1756         marity = -marity - 1;
1757         opt = Qtrue;
1758     }
1759
1760     rb_scan_args(argc, argv, "01", &arity);
1761     if (NIL_P(arity)) {
1762         arity = INT2FIX(marity);
1763     }
1764     else {
1765         sarity = FIX2INT(arity);
1766         if (proc_lambda_p(self) && (sarity < marity || (sarity > marity && !opt))) {
1767             rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", sarity, marity);
1768         }
1769     }
1770
1771     return make_curry_proc(self, rb_ary_new(), arity);
1772 }
1773
1774 /*
1775  *  <code>Proc</code> objects are blocks of code that have been bound to
1776  *  a set of local variables. Once bound, the code may be called in
1777  *  different contexts and still access those variables.
1778  *     
1779  *     def gen_times(factor)
1780  *       return Proc.new {|n| n*factor }
1781  *     end
1782  *     
1783  *     times3 = gen_times(3)
1784  *     times5 = gen_times(5)
1785  *     
1786  *     times3.call(12)               #=> 36
1787  *     times5.call(5)                #=> 25
1788  *     times3.call(times5.call(4))   #=> 60
1789  *     
1790  */
1791
1792 void
1793 Init_Proc(void)
1794 {
1795     /* Proc */
1796     rb_cProc = rb_define_class("Proc", rb_cObject);
1797     rb_undef_alloc_func(rb_cProc);
1798     rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
1799     rb_define_method(rb_cProc, "call", proc_call, -1);
1800     rb_define_method(rb_cProc, "[]", proc_call, -1);
1801     rb_define_method(rb_cProc, "===", proc_call, -1);
1802     rb_define_method(rb_cProc, "yield", proc_call, -1);
1803     rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
1804     rb_define_method(rb_cProc, "arity", proc_arity, 0);
1805     rb_define_method(rb_cProc, "clone", proc_clone, 0);
1806     rb_define_method(rb_cProc, "dup", proc_dup, 0);
1807     rb_define_method(rb_cProc, "==", proc_eq, 1);
1808     rb_define_method(rb_cProc, "eql?", proc_eq, 1);
1809     rb_define_method(rb_cProc, "hash", proc_hash, 0);
1810     rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
1811     rb_define_method(rb_cProc, "lambda?", proc_lambda_p, 0);
1812     rb_define_method(rb_cProc, "binding", proc_binding, 0);
1813     rb_define_method(rb_cProc, "curry", proc_curry, -1);
1814     rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
1815
1816     /* Exceptions */
1817     rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
1818     rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
1819     rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
1820
1821     rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
1822     sysstack_error = rb_exc_new3(rb_eSysStackError,
1823                                  rb_obj_freeze(rb_str_new2("stack level too deep")));
1824     OBJ_TAINT(sysstack_error);
1825     OBJ_FREEZE(sysstack_error);
1826
1827     /* utility functions */
1828     rb_define_global_function("proc", rb_block_proc, 0);
1829     rb_define_global_function("lambda", proc_lambda, 0);
1830
1831     /* Method */
1832     rb_cMethod = rb_define_class("Method", rb_cObject);
1833     rb_undef_alloc_func(rb_cMethod);
1834     rb_undef_method(CLASS_OF(rb_cMethod), "new");
1835     rb_define_method(rb_cMethod, "==", method_eq, 1);
1836     rb_define_method(rb_cMethod, "eql?", method_eq, 1);
1837     rb_define_method(rb_cMethod, "hash", method_hash, 0);
1838     rb_define_method(rb_cMethod, "clone", method_clone, 0);
1839     rb_define_method(rb_cMethod, "call", rb_method_call, -1);
1840     rb_define_method(rb_cMethod, "[]", rb_method_call, -1);
1841     rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
1842     rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
1843     rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
1844     rb_define_method(rb_cMethod, "to_proc", method_proc, 0);
1845     rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
1846     rb_define_method(rb_cMethod, "name", method_name, 0);
1847     rb_define_method(rb_cMethod, "owner", method_owner, 0);
1848     rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
1849     rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
1850     rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
1851     rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
1852
1853     /* UnboundMethod */
1854     rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
1855     rb_undef_alloc_func(rb_cUnboundMethod);
1856     rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
1857     rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
1858     rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
1859     rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
1860     rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
1861     rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
1862     rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
1863     rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
1864     rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
1865     rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
1866     rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
1867     rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
1868
1869     /* Module#*_method */
1870     rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
1871     rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
1872     rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
1873
1874     /* Kernel */
1875     rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
1876 }
1877
1878 /*
1879  *  Objects of class <code>Binding</code> encapsulate the execution
1880  *  context at some particular place in the code and retain this context
1881  *  for future use. The variables, methods, value of <code>self</code>,
1882  *  and possibly an iterator block that can be accessed in this context
1883  *  are all retained. Binding objects can be created using
1884  *  <code>Kernel#binding</code>, and are made available to the callback
1885  *  of <code>Kernel#set_trace_func</code>.
1886  *     
1887  *  These binding objects can be passed as the second argument of the
1888  *  <code>Kernel#eval</code> method, establishing an environment for the
1889  *  evaluation.
1890  *     
1891  *     class Demo
1892  *       def initialize(n)
1893  *         @secret = n
1894  *       end
1895  *       def getBinding
1896  *         return binding()
1897  *       end
1898  *     end
1899  *     
1900  *     k1 = Demo.new(99)
1901  *     b1 = k1.getBinding
1902  *     k2 = Demo.new(-3)
1903  *     b2 = k2.getBinding
1904  *     
1905  *     eval("@secret", b1)   #=> 99
1906  *     eval("@secret", b2)   #=> -3
1907  *     eval("@secret")       #=> nil
1908  *     
1909  *  Binding objects have no class-specific methods.
1910  *     
1911  */
1912
1913 void
1914 Init_Binding(void)
1915 {
1916     rb_cBinding = rb_define_class("Binding", rb_cObject);
1917     rb_undef_alloc_func(rb_cBinding);
1918     rb_undef_method(CLASS_OF(rb_cBinding), "new");
1919     rb_define_method(rb_cBinding, "clone", binding_clone, 0);
1920     rb_define_method(rb_cBinding, "dup", binding_dup, 0);
1921     rb_define_method(rb_cBinding, "eval", bind_eval, -1);
1922     rb_define_global_function("binding", rb_f_binding, 0);
1923 }
1924