Ruby  2.0.0p481(2014-05-08revision45883)
proc.c
Go to the documentation of this file.
00001 /**********************************************************************
00002 
00003   proc.c - Proc, Binding, Env
00004 
00005   $Author: nagachika $
00006   created at: Wed Jan 17 12:13:14 2007
00007 
00008   Copyright (C) 2004-2007 Koichi Sasada
00009 
00010 **********************************************************************/
00011 
00012 #include "eval_intern.h"
00013 #include "internal.h"
00014 #include "gc.h"
00015 #include "iseq.h"
00016 
00017 struct METHOD {
00018     VALUE recv;
00019     VALUE rclass;
00020     VALUE defined_class;
00021     ID id;
00022     rb_method_entry_t *me;
00023     struct unlinked_method_entry_list_entry *ume;
00024 };
00025 
00026 VALUE rb_cUnboundMethod;
00027 VALUE rb_cMethod;
00028 VALUE rb_cBinding;
00029 VALUE rb_cProc;
00030 
00031 static VALUE bmcall(VALUE, VALUE, int, VALUE *, VALUE);
00032 static int method_arity(VALUE);
00033 static int method_min_max_arity(VALUE, int *max);
00034 static ID attached;
00035 
00036 /* Proc */
00037 
00038 #define IS_METHOD_PROC_NODE(node) (nd_type(node) == NODE_IFUNC && (node)->nd_cfnc == bmcall)
00039 
00040 static void
00041 proc_free(void *ptr)
00042 {
00043     RUBY_FREE_ENTER("proc");
00044     if (ptr) {
00045         ruby_xfree(ptr);
00046     }
00047     RUBY_FREE_LEAVE("proc");
00048 }
00049 
00050 static void
00051 proc_mark(void *ptr)
00052 {
00053     rb_proc_t *proc;
00054     RUBY_MARK_ENTER("proc");
00055     if (ptr) {
00056         proc = ptr;
00057         RUBY_MARK_UNLESS_NULL(proc->envval);
00058         RUBY_MARK_UNLESS_NULL(proc->blockprocval);
00059         RUBY_MARK_UNLESS_NULL(proc->block.proc);
00060         RUBY_MARK_UNLESS_NULL(proc->block.self);
00061         if (proc->block.iseq && RUBY_VM_IFUNC_P(proc->block.iseq)) {
00062             RUBY_MARK_UNLESS_NULL((VALUE)(proc->block.iseq));
00063         }
00064     }
00065     RUBY_MARK_LEAVE("proc");
00066 }
00067 
00068 static size_t
00069 proc_memsize(const void *ptr)
00070 {
00071     return ptr ? sizeof(rb_proc_t) : 0;
00072 }
00073 
00074 static const rb_data_type_t proc_data_type = {
00075     "proc",
00076     {
00077         proc_mark,
00078         proc_free,
00079         proc_memsize,
00080     },
00081 };
00082 
00083 VALUE
00084 rb_proc_alloc(VALUE klass)
00085 {
00086     rb_proc_t *proc;
00087     return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
00088 }
00089 
00090 VALUE
00091 rb_obj_is_proc(VALUE proc)
00092 {
00093     if (rb_typeddata_is_kind_of(proc, &proc_data_type)) {
00094         return Qtrue;
00095     }
00096     else {
00097         return Qfalse;
00098     }
00099 }
00100 
00101 /* :nodoc: */
00102 static VALUE
00103 proc_dup(VALUE self)
00104 {
00105     VALUE procval = rb_proc_alloc(rb_cProc);
00106     rb_proc_t *src, *dst;
00107     GetProcPtr(self, src);
00108     GetProcPtr(procval, dst);
00109 
00110     dst->block = src->block;
00111     dst->block.proc = procval;
00112     dst->blockprocval = src->blockprocval;
00113     dst->envval = src->envval;
00114     dst->safe_level = src->safe_level;
00115     dst->is_lambda = src->is_lambda;
00116 
00117     return procval;
00118 }
00119 
00120 /* :nodoc: */
00121 static VALUE
00122 proc_clone(VALUE self)
00123 {
00124     VALUE procval = proc_dup(self);
00125     CLONESETUP(procval, self);
00126     return procval;
00127 }
00128 
00129 /*
00130  * call-seq:
00131  *   prc.lambda? -> true or false
00132  *
00133  * Returns +true+ for a Proc object for which argument handling is rigid.
00134  * Such procs are typically generated by +lambda+.
00135  *
00136  * A Proc object generated by +proc+ ignores extra arguments.
00137  *
00138  *   proc {|a,b| [a,b] }.call(1,2,3)    #=> [1,2]
00139  *
00140  * It provides +nil+ for missing arguments.
00141  *
00142  *   proc {|a,b| [a,b] }.call(1)        #=> [1,nil]
00143  *
00144  * It expands a single array argument.
00145  *
00146  *   proc {|a,b| [a,b] }.call([1,2])    #=> [1,2]
00147  *
00148  * A Proc object generated by +lambda+ doesn't have such tricks.
00149  *
00150  *   lambda {|a,b| [a,b] }.call(1,2,3)  #=> ArgumentError
00151  *   lambda {|a,b| [a,b] }.call(1)      #=> ArgumentError
00152  *   lambda {|a,b| [a,b] }.call([1,2])  #=> ArgumentError
00153  *
00154  * Proc#lambda? is a predicate for the tricks.
00155  * It returns +true+ if no tricks apply.
00156  *
00157  *   lambda {}.lambda?            #=> true
00158  *   proc {}.lambda?              #=> false
00159  *
00160  * Proc.new is the same as +proc+.
00161  *
00162  *   Proc.new {}.lambda?          #=> false
00163  *
00164  * +lambda+, +proc+ and Proc.new preserve the tricks of
00165  * a Proc object given by <code>&</code> argument.
00166  *
00167  *   lambda(&lambda {}).lambda?   #=> true
00168  *   proc(&lambda {}).lambda?     #=> true
00169  *   Proc.new(&lambda {}).lambda? #=> true
00170  *
00171  *   lambda(&proc {}).lambda?     #=> false
00172  *   proc(&proc {}).lambda?       #=> false
00173  *   Proc.new(&proc {}).lambda?   #=> false
00174  *
00175  * A Proc object generated by <code>&</code> argument has the tricks
00176  *
00177  *   def n(&b) b.lambda? end
00178  *   n {}                         #=> false
00179  *
00180  * The <code>&</code> argument preserves the tricks if a Proc object
00181  * is given by <code>&</code> argument.
00182  *
00183  *   n(&lambda {})                #=> true
00184  *   n(&proc {})                  #=> false
00185  *   n(&Proc.new {})              #=> false
00186  *
00187  * A Proc object converted from a method has no tricks.
00188  *
00189  *   def m() end
00190  *   method(:m).to_proc.lambda?   #=> true
00191  *
00192  *   n(&method(:m))               #=> true
00193  *   n(&method(:m).to_proc)       #=> true
00194  *
00195  * +define_method+ is treated the same as method definition.
00196  * The defined method has no tricks.
00197  *
00198  *   class C
00199  *     define_method(:d) {}
00200  *   end
00201  *   C.new.d(1,2)       #=> ArgumentError
00202  *   C.new.method(:d).to_proc.lambda?   #=> true
00203  *
00204  * +define_method+ always defines a method without the tricks,
00205  * even if a non-lambda Proc object is given.
00206  * This is the only exception for which the tricks are not preserved.
00207  *
00208  *   class C
00209  *     define_method(:e, &proc {})
00210  *   end
00211  *   C.new.e(1,2)       #=> ArgumentError
00212  *   C.new.method(:e).to_proc.lambda?   #=> true
00213  *
00214  * This exception insures that methods never have tricks
00215  * and makes it easy to have wrappers to define methods that behave as usual.
00216  *
00217  *   class C
00218  *     def self.def2(name, &body)
00219  *       define_method(name, &body)
00220  *     end
00221  *
00222  *     def2(:f) {}
00223  *   end
00224  *   C.new.f(1,2)       #=> ArgumentError
00225  *
00226  * The wrapper <i>def2</i> defines a method which has no tricks.
00227  *
00228  */
00229 
00230 VALUE
00231 rb_proc_lambda_p(VALUE procval)
00232 {
00233     rb_proc_t *proc;
00234     GetProcPtr(procval, proc);
00235 
00236     return proc->is_lambda ? Qtrue : Qfalse;
00237 }
00238 
00239 /* Binding */
00240 
00241 static void
00242 binding_free(void *ptr)
00243 {
00244     rb_binding_t *bind;
00245     RUBY_FREE_ENTER("binding");
00246     if (ptr) {
00247         bind = ptr;
00248         ruby_xfree(bind);
00249     }
00250     RUBY_FREE_LEAVE("binding");
00251 }
00252 
00253 static void
00254 binding_mark(void *ptr)
00255 {
00256     rb_binding_t *bind;
00257     RUBY_MARK_ENTER("binding");
00258     if (ptr) {
00259         bind = ptr;
00260         RUBY_MARK_UNLESS_NULL(bind->env);
00261         RUBY_MARK_UNLESS_NULL(bind->path);
00262     }
00263     RUBY_MARK_LEAVE("binding");
00264 }
00265 
00266 static size_t
00267 binding_memsize(const void *ptr)
00268 {
00269     return ptr ? sizeof(rb_binding_t) : 0;
00270 }
00271 
00272 static const rb_data_type_t binding_data_type = {
00273     "binding",
00274     {
00275         binding_mark,
00276         binding_free,
00277         binding_memsize,
00278     },
00279 };
00280 
00281 static VALUE
00282 binding_alloc(VALUE klass)
00283 {
00284     VALUE obj;
00285     rb_binding_t *bind;
00286     obj = TypedData_Make_Struct(klass, rb_binding_t, &binding_data_type, bind);
00287     return obj;
00288 }
00289 
00290 /* :nodoc: */
00291 static VALUE
00292 binding_dup(VALUE self)
00293 {
00294     VALUE bindval = binding_alloc(rb_cBinding);
00295     rb_binding_t *src, *dst;
00296     GetBindingPtr(self, src);
00297     GetBindingPtr(bindval, dst);
00298     dst->env = src->env;
00299     dst->path = src->path;
00300     dst->first_lineno = src->first_lineno;
00301     return bindval;
00302 }
00303 
00304 /* :nodoc: */
00305 static VALUE
00306 binding_clone(VALUE self)
00307 {
00308     VALUE bindval = binding_dup(self);
00309     CLONESETUP(bindval, self);
00310     return bindval;
00311 }
00312 
00313 VALUE
00314 rb_binding_new_with_cfp(rb_thread_t *th, const rb_control_frame_t *src_cfp)
00315 {
00316     rb_control_frame_t *cfp = rb_vm_get_binding_creatable_next_cfp(th, src_cfp);
00317     rb_control_frame_t *ruby_level_cfp = rb_vm_get_ruby_level_next_cfp(th, src_cfp);
00318     VALUE bindval, envval;
00319     rb_binding_t *bind;
00320 
00321     if (cfp == 0 || ruby_level_cfp == 0) {
00322         rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber.");
00323     }
00324 
00325     while (1) {
00326         envval = rb_vm_make_env_object(th, cfp);
00327         if (cfp == ruby_level_cfp) {
00328             break;
00329         }
00330         cfp = rb_vm_get_binding_creatable_next_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp));
00331     }
00332 
00333     bindval = binding_alloc(rb_cBinding);
00334     GetBindingPtr(bindval, bind);
00335     bind->env = envval;
00336     bind->path = ruby_level_cfp->iseq->location.path;
00337     bind->first_lineno = rb_vm_get_sourceline(ruby_level_cfp);
00338 
00339     return bindval;
00340 }
00341 
00342 VALUE
00343 rb_binding_new(void)
00344 {
00345     rb_thread_t *th = GET_THREAD();
00346     return rb_binding_new_with_cfp(th, th->cfp);
00347 }
00348 
00349 /*
00350  *  call-seq:
00351  *     binding -> a_binding
00352  *
00353  *  Returns a +Binding+ object, describing the variable and
00354  *  method bindings at the point of call. This object can be used when
00355  *  calling +eval+ to execute the evaluated command in this
00356  *  environment. See also the description of class +Binding+.
00357  *
00358  *     def get_binding(param)
00359  *       return binding
00360  *     end
00361  *     b = get_binding("hello")
00362  *     eval("param", b)   #=> "hello"
00363  */
00364 
00365 static VALUE
00366 rb_f_binding(VALUE self)
00367 {
00368     return rb_binding_new();
00369 }
00370 
00371 /*
00372  *  call-seq:
00373  *     binding.eval(string [, filename [,lineno]])  -> obj
00374  *
00375  *  Evaluates the Ruby expression(s) in <em>string</em>, in the
00376  *  <em>binding</em>'s context.  If the optional <em>filename</em> and
00377  *  <em>lineno</em> parameters are present, they will be used when
00378  *  reporting syntax errors.
00379  *
00380  *     def get_binding(param)
00381  *       return binding
00382  *     end
00383  *     b = get_binding("hello")
00384  *     b.eval("param")   #=> "hello"
00385  */
00386 
00387 static VALUE
00388 bind_eval(int argc, VALUE *argv, VALUE bindval)
00389 {
00390     VALUE args[4];
00391 
00392     rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
00393     args[1] = bindval;
00394     return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
00395 }
00396 
00397 static VALUE
00398 proc_new(VALUE klass, int is_lambda)
00399 {
00400     VALUE procval = Qnil;
00401     rb_thread_t *th = GET_THREAD();
00402     rb_control_frame_t *cfp = th->cfp;
00403     rb_block_t *block;
00404 
00405     if ((block = rb_vm_control_frame_block_ptr(cfp)) != 0) {
00406         /* block found */
00407     }
00408     else {
00409         cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
00410 
00411         if ((block = rb_vm_control_frame_block_ptr(cfp)) != 0) {
00412             if (is_lambda) {
00413                 rb_warn("tried to create Proc object without a block");
00414             }
00415         }
00416         else {
00417             rb_raise(rb_eArgError,
00418                      "tried to create Proc object without a block");
00419         }
00420     }
00421 
00422     procval = block->proc;
00423 
00424     if (procval) {
00425         if (RBASIC(procval)->klass == klass) {
00426             return procval;
00427         }
00428         else {
00429             VALUE newprocval = proc_dup(procval);
00430             RBASIC(newprocval)->klass = klass;
00431             return newprocval;
00432         }
00433     }
00434 
00435     procval = rb_vm_make_proc(th, block, klass);
00436 
00437     if (is_lambda) {
00438         rb_proc_t *proc;
00439         GetProcPtr(procval, proc);
00440         proc->is_lambda = TRUE;
00441     }
00442     return procval;
00443 }
00444 
00445 /*
00446  *  call-seq:
00447  *     Proc.new {|...| block } -> a_proc
00448  *     Proc.new                -> a_proc
00449  *
00450  *  Creates a new <code>Proc</code> object, bound to the current
00451  *  context. <code>Proc::new</code> may be called without a block only
00452  *  within a method with an attached block, in which case that block is
00453  *  converted to the <code>Proc</code> object.
00454  *
00455  *     def proc_from
00456  *       Proc.new
00457  *     end
00458  *     proc = proc_from { "hello" }
00459  *     proc.call   #=> "hello"
00460  */
00461 
00462 static VALUE
00463 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
00464 {
00465     VALUE block = proc_new(klass, FALSE);
00466 
00467     rb_obj_call_init(block, argc, argv);
00468     return block;
00469 }
00470 
00471 /*
00472  * call-seq:
00473  *   proc   { |...| block }  -> a_proc
00474  *
00475  * Equivalent to <code>Proc.new</code>.
00476  */
00477 
00478 VALUE
00479 rb_block_proc(void)
00480 {
00481     return proc_new(rb_cProc, FALSE);
00482 }
00483 
00484 /*
00485  * call-seq:
00486  *   lambda { |...| block }  -> a_proc
00487  *
00488  * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
00489  * check the number of parameters passed when called.
00490  */
00491 
00492 VALUE
00493 rb_block_lambda(void)
00494 {
00495     return proc_new(rb_cProc, TRUE);
00496 }
00497 
00498 VALUE
00499 rb_f_lambda(void)
00500 {
00501     rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
00502     return rb_block_lambda();
00503 }
00504 
00505 /*  Document-method: ===
00506  *
00507  *  call-seq:
00508  *     proc === obj   -> result_of_proc
00509  *
00510  *  Invokes the block with +obj+ as the proc's parameter like Proc#call.  It
00511  *  is to allow a proc object to be a target of +when+ clause in a case
00512  *  statement.
00513  */
00514 
00515 /* CHECKME: are the argument checking semantics correct? */
00516 
00517 /*
00518  *  call-seq:
00519  *     prc.call(params,...)   -> obj
00520  *     prc[params,...]        -> obj
00521  *     prc.(params,...)       -> obj
00522  *
00523  *  Invokes the block, setting the block's parameters to the values in
00524  *  <i>params</i> using something close to method calling semantics.
00525  *  Generates a warning if multiple values are passed to a proc that
00526  *  expects just one (previously this silently converted the parameters
00527  *  to an array).  Note that prc.() invokes prc.call() with the parameters
00528  *  given.  It's a syntax sugar to hide "call".
00529  *
00530  *  For procs created using <code>lambda</code> or <code>->()</code> an error
00531  *  is generated if the wrong number of parameters are passed to a Proc with
00532  *  multiple parameters.  For procs created using <code>Proc.new</code> or
00533  *  <code>Kernel.proc</code>, extra parameters are silently discarded.
00534  *
00535  *  Returns the value of the last expression evaluated in the block. See
00536  *  also <code>Proc#yield</code>.
00537  *
00538  *     a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
00539  *     a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
00540  *     a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
00541  *     a_proc = lambda {|a,b| a}
00542  *     a_proc.call(1,2,3)
00543  *
00544  *  <em>produces:</em>
00545  *
00546  *     prog.rb:4:in `block in <main>': wrong number of arguments (3 for 2) (ArgumentError)
00547  *      from prog.rb:5:in `call'
00548  *      from prog.rb:5:in `<main>'
00549  *
00550  */
00551 
00552 static VALUE
00553 proc_call(int argc, VALUE *argv, VALUE procval)
00554 {
00555     VALUE vret;
00556     rb_proc_t *proc;
00557     rb_block_t *blockptr = 0;
00558     rb_iseq_t *iseq;
00559     VALUE passed_procval;
00560     GetProcPtr(procval, proc);
00561 
00562     iseq = proc->block.iseq;
00563     if (BUILTIN_TYPE(iseq) == T_NODE || iseq->arg_block != -1) {
00564         if (rb_block_given_p()) {
00565             rb_proc_t *passed_proc;
00566             RB_GC_GUARD(passed_procval) = rb_block_proc();
00567             GetProcPtr(passed_procval, passed_proc);
00568             blockptr = &passed_proc->block;
00569         }
00570     }
00571 
00572     vret = rb_vm_invoke_proc(GET_THREAD(), proc, argc, argv, blockptr);
00573     RB_GC_GUARD(procval);
00574     return vret;
00575 }
00576 
00577 #if SIZEOF_LONG > SIZEOF_INT
00578 static inline int
00579 check_argc(long argc)
00580 {
00581     if (argc > INT_MAX || argc < 0) {
00582         rb_raise(rb_eArgError, "too many arguments (%lu)",
00583                  (unsigned long)argc);
00584     }
00585     return (int)argc;
00586 }
00587 #else
00588 #define check_argc(argc) (argc)
00589 #endif
00590 
00591 VALUE
00592 rb_proc_call(VALUE self, VALUE args)
00593 {
00594     VALUE vret;
00595     rb_proc_t *proc;
00596     GetProcPtr(self, proc);
00597     vret = rb_vm_invoke_proc(GET_THREAD(), proc,
00598                              check_argc(RARRAY_LEN(args)), RARRAY_PTR(args), 0);
00599     RB_GC_GUARD(self);
00600     RB_GC_GUARD(args);
00601     return vret;
00602 }
00603 
00604 VALUE
00605 rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval)
00606 {
00607     VALUE vret;
00608     rb_proc_t *proc;
00609     rb_block_t *block = 0;
00610     GetProcPtr(self, proc);
00611 
00612     if (!NIL_P(pass_procval)) {
00613         rb_proc_t *pass_proc;
00614         GetProcPtr(pass_procval, pass_proc);
00615         block = &pass_proc->block;
00616     }
00617 
00618     vret = rb_vm_invoke_proc(GET_THREAD(), proc, argc, argv, block);
00619     RB_GC_GUARD(self);
00620     RB_GC_GUARD(pass_procval);
00621     return vret;
00622 }
00623 
00624 /*
00625  *  call-seq:
00626  *     prc.arity -> fixnum
00627  *
00628  *  Returns the number of arguments that would not be ignored. If the block
00629  *  is declared to take no arguments, returns 0. If the block is known
00630  *  to take exactly n arguments, returns n. If the block has optional
00631  *  arguments, return -n-1, where n is the number of mandatory
00632  *  arguments. A <code>proc</code> with no argument declarations
00633  *  is the same a block declaring <code>||</code> as its arguments.
00634  *
00635  *     proc {}.arity          #=>  0
00636  *     proc {||}.arity        #=>  0
00637  *     proc {|a|}.arity       #=>  1
00638  *     proc {|a,b|}.arity     #=>  2
00639  *     proc {|a,b,c|}.arity   #=>  3
00640  *     proc {|*a|}.arity      #=> -1
00641  *     proc {|a,*b|}.arity    #=> -2
00642  *     proc {|a,*b, c|}.arity #=> -3
00643  *
00644  *     proc   { |x = 0| }.arity       #=> 0
00645  *     lambda { |a = 0| }.arity       #=> -1
00646  *     proc   { |x=0, y| }.arity      #=> 0
00647  *     lambda { |x=0, y| }.arity      #=> -2
00648  *     proc   { |x=0, y=0| }.arity    #=> 0
00649  *     lambda { |x=0, y=0| }.arity    #=> -1
00650  *     proc   { |x, y=0| }.arity      #=> 1
00651  *     lambda { |x, y=0| }.arity      #=> -2
00652  *     proc   { |(x, y), z=0| }.arity #=> 1
00653  *     lambda { |(x, y), z=0| }.arity #=> -2
00654  */
00655 
00656 static VALUE
00657 proc_arity(VALUE self)
00658 {
00659     int arity = rb_proc_arity(self);
00660     return INT2FIX(arity);
00661 }
00662 
00663 static inline int
00664 rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
00665 {
00666     *max = iseq->arg_rest == -1 ?
00667         iseq->argc + iseq->arg_post_len + iseq->arg_opts - (iseq->arg_opts > 0)
00668       : UNLIMITED_ARGUMENTS;
00669     return iseq->argc + iseq->arg_post_len;
00670 }
00671 
00672 /*
00673  * Returns the number of required parameters and stores the maximum
00674  * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
00675  * For non-lambda procs, the maximum is the number of non-ignored
00676  * parameters even though there is no actual limit to the number of parameters
00677  */
00678 static int
00679 rb_proc_min_max_arity(VALUE self, int *max)
00680 {
00681     rb_proc_t *proc;
00682     rb_iseq_t *iseq;
00683     GetProcPtr(self, proc);
00684     iseq = proc->block.iseq;
00685     if (iseq) {
00686         if (BUILTIN_TYPE(iseq) != T_NODE) {
00687             return rb_iseq_min_max_arity(iseq, max);
00688         }
00689         else {
00690             NODE *node = (NODE *)iseq;
00691             if (IS_METHOD_PROC_NODE(node)) {
00692                 /* e.g. method(:foo).to_proc.arity */
00693                 return method_min_max_arity(node->nd_tval, max);
00694             }
00695         }
00696     }
00697     *max = UNLIMITED_ARGUMENTS;
00698     return 0;
00699 }
00700 
00701 int
00702 rb_proc_arity(VALUE self)
00703 {
00704     rb_proc_t *proc;
00705     int max, min = rb_proc_min_max_arity(self, &max);
00706     GetProcPtr(self, proc);
00707     return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
00708 }
00709 
00710 #define get_proc_iseq rb_proc_get_iseq
00711 
00712 rb_iseq_t *
00713 rb_proc_get_iseq(VALUE self, int *is_proc)
00714 {
00715     rb_proc_t *proc;
00716     rb_iseq_t *iseq;
00717 
00718     GetProcPtr(self, proc);
00719     iseq = proc->block.iseq;
00720     if (is_proc) *is_proc = !proc->is_lambda;
00721     if (!RUBY_VM_NORMAL_ISEQ_P(iseq)) {
00722         NODE *node = (NODE *)iseq;
00723         iseq = 0;
00724         if (IS_METHOD_PROC_NODE(node)) {
00725             /* method(:foo).to_proc */
00726             iseq = rb_method_get_iseq(node->nd_tval);
00727             if (is_proc) *is_proc = 0;
00728         }
00729     }
00730     return iseq;
00731 }
00732 
00733 static VALUE
00734 iseq_location(rb_iseq_t *iseq)
00735 {
00736     VALUE loc[2];
00737 
00738     if (!iseq) return Qnil;
00739     loc[0] = iseq->location.path;
00740     if (iseq->line_info_table) {
00741         loc[1] = INT2FIX(rb_iseq_first_lineno(iseq));
00742     }
00743     else {
00744         loc[1] = Qnil;
00745     }
00746     return rb_ary_new4(2, loc);
00747 }
00748 
00749 /*
00750  * call-seq:
00751  *    prc.source_location  -> [String, Fixnum]
00752  *
00753  * Returns the Ruby source filename and line number containing this proc
00754  * or +nil+ if this proc was not defined in Ruby (i.e. native)
00755  */
00756 
00757 VALUE
00758 rb_proc_location(VALUE self)
00759 {
00760     return iseq_location(get_proc_iseq(self, 0));
00761 }
00762 
00763 static VALUE
00764 unnamed_parameters(int arity)
00765 {
00766     VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
00767     int n = (arity < 0) ? ~arity : arity;
00768     ID req, rest;
00769     CONST_ID(req, "req");
00770     a = rb_ary_new3(1, ID2SYM(req));
00771     OBJ_FREEZE(a);
00772     for (; n; --n) {
00773         rb_ary_push(param, a);
00774     }
00775     if (arity < 0) {
00776         CONST_ID(rest, "rest");
00777         rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
00778     }
00779     return param;
00780 }
00781 
00782 /*
00783  * call-seq:
00784  *    prc.parameters  -> array
00785  *
00786  * Returns the parameter information of this proc.
00787  *
00788  *    prc = lambda{|x, y=42, *other|}
00789  *    prc.parameters  #=> [[:req, :x], [:opt, :y], [:rest, :other]]
00790  */
00791 
00792 static VALUE
00793 rb_proc_parameters(VALUE self)
00794 {
00795     int is_proc;
00796     rb_iseq_t *iseq = get_proc_iseq(self, &is_proc);
00797     if (!iseq) {
00798         return unnamed_parameters(rb_proc_arity(self));
00799     }
00800     return rb_iseq_parameters(iseq, is_proc);
00801 }
00802 
00803 st_index_t
00804 rb_hash_proc(st_index_t hash, VALUE prc)
00805 {
00806     rb_proc_t *proc;
00807     GetProcPtr(prc, proc);
00808     hash = rb_hash_uint(hash, (st_index_t)proc->block.iseq);
00809     hash = rb_hash_uint(hash, (st_index_t)proc->envval);
00810     return rb_hash_uint(hash, (st_index_t)proc->block.ep >> 16);
00811 }
00812 
00813 /*
00814  * call-seq:
00815  *   prc.hash   ->  integer
00816  *
00817  * Returns a hash value corresponding to proc body.
00818  */
00819 
00820 static VALUE
00821 proc_hash(VALUE self)
00822 {
00823     st_index_t hash;
00824     hash = rb_hash_start(0);
00825     hash = rb_hash_proc(hash, self);
00826     hash = rb_hash_end(hash);
00827     return LONG2FIX(hash);
00828 }
00829 
00830 /*
00831  * call-seq:
00832  *   prc.to_s   -> string
00833  *
00834  * Returns the unique identifier for this proc, along with
00835  * an indication of where the proc was defined.
00836  */
00837 
00838 static VALUE
00839 proc_to_s(VALUE self)
00840 {
00841     VALUE str = 0;
00842     rb_proc_t *proc;
00843     const char *cname = rb_obj_classname(self);
00844     rb_iseq_t *iseq;
00845     const char *is_lambda;
00846 
00847     GetProcPtr(self, proc);
00848     iseq = proc->block.iseq;
00849     is_lambda = proc->is_lambda ? " (lambda)" : "";
00850 
00851     if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
00852         int first_lineno = 0;
00853 
00854         if (iseq->line_info_table) {
00855             first_lineno = rb_iseq_first_lineno(iseq);
00856         }
00857         str = rb_sprintf("#<%s:%p@%s:%d%s>", cname, (void *)self,
00858                          RSTRING_PTR(iseq->location.path),
00859                          first_lineno, is_lambda);
00860     }
00861     else {
00862         str = rb_sprintf("#<%s:%p%s>", cname, (void *)proc->block.iseq,
00863                          is_lambda);
00864     }
00865 
00866     if (OBJ_TAINTED(self)) {
00867         OBJ_TAINT(str);
00868     }
00869     return str;
00870 }
00871 
00872 /*
00873  *  call-seq:
00874  *     prc.to_proc -> prc
00875  *
00876  *  Part of the protocol for converting objects to <code>Proc</code>
00877  *  objects. Instances of class <code>Proc</code> simply return
00878  *  themselves.
00879  */
00880 
00881 static VALUE
00882 proc_to_proc(VALUE self)
00883 {
00884     return self;
00885 }
00886 
00887 static void
00888 bm_mark(void *ptr)
00889 {
00890     struct METHOD *data = ptr;
00891     rb_gc_mark(data->defined_class);
00892     rb_gc_mark(data->rclass);
00893     rb_gc_mark(data->recv);
00894     if (data->me) rb_mark_method_entry(data->me);
00895 }
00896 
00897 static void
00898 bm_free(void *ptr)
00899 {
00900     struct METHOD *data = ptr;
00901     struct unlinked_method_entry_list_entry *ume = data->ume;
00902     data->me->mark = 0;
00903     ume->me = data->me;
00904     ume->next = GET_VM()->unlinked_method_entry_list;
00905     GET_VM()->unlinked_method_entry_list = ume;
00906     xfree(ptr);
00907 }
00908 
00909 static size_t
00910 bm_memsize(const void *ptr)
00911 {
00912     return ptr ? sizeof(struct METHOD) : 0;
00913 }
00914 
00915 static const rb_data_type_t method_data_type = {
00916     "method",
00917     {
00918         bm_mark,
00919         bm_free,
00920         bm_memsize,
00921     },
00922 };
00923 
00924 VALUE
00925 rb_obj_is_method(VALUE m)
00926 {
00927     if (rb_typeddata_is_kind_of(m, &method_data_type)) {
00928         return Qtrue;
00929     }
00930     else {
00931         return Qfalse;
00932     }
00933 }
00934 
00935 static VALUE
00936 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
00937 {
00938     VALUE method;
00939     VALUE rclass = klass, defined_class;
00940     ID rid = id;
00941     struct METHOD *data;
00942     rb_method_entry_t *me, meb;
00943     rb_method_definition_t *def = 0;
00944     rb_method_flag_t flag = NOEX_UNDEF;
00945 
00946   again:
00947     me = rb_method_entry_without_refinements(klass, id, &defined_class);
00948     if (UNDEFINED_METHOD_ENTRY_P(me)) {
00949         ID rmiss = idRespond_to_missing;
00950         VALUE sym = ID2SYM(id);
00951 
00952         if (obj != Qundef && !rb_method_basic_definition_p(klass, rmiss)) {
00953             if (RTEST(rb_funcall(obj, rmiss, 2, sym, scope ? Qfalse : Qtrue))) {
00954                 def = ALLOC(rb_method_definition_t);
00955                 def->type = VM_METHOD_TYPE_MISSING;
00956                 def->original_id = id;
00957                 def->alias_count = 0;
00958                 defined_class = klass;
00959 
00960                 meb.flag = 0;
00961                 meb.mark = 0;
00962                 meb.called_id = id;
00963                 meb.klass = klass;
00964                 meb.def = def;
00965                 me = &meb;
00966                 def = 0;
00967 
00968                 goto gen_method;
00969             }
00970         }
00971         rb_print_undef(klass, id, 0);
00972     }
00973     def = me->def;
00974     if (flag == NOEX_UNDEF) {
00975         flag = me->flag;
00976         if (scope && (flag & NOEX_MASK) != NOEX_PUBLIC) {
00977             const char *v = "";
00978             switch (flag & NOEX_MASK) {
00979                 case NOEX_PRIVATE: v = "private"; break;
00980                 case NOEX_PROTECTED: v = "protected"; break;
00981             }
00982             rb_name_error(id, "method `%s' for %s `%s' is %s",
00983                           rb_id2name(id),
00984                           (RB_TYPE_P(klass, T_MODULE)) ? "module" : "class",
00985                           rb_class2name(klass),
00986                           v);
00987         }
00988     }
00989     if (def && def->type == VM_METHOD_TYPE_ZSUPER) {
00990         klass = RCLASS_SUPER(defined_class);
00991         id = def->original_id;
00992         goto again;
00993     }
00994 
00995     klass = defined_class;
00996 
00997     while (rclass != klass &&
00998            (FL_TEST(rclass, FL_SINGLETON) || RB_TYPE_P(rclass, T_ICLASS))) {
00999         rclass = RCLASS_SUPER(rclass);
01000     }
01001 
01002   gen_method:
01003     method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
01004 
01005     data->recv = obj;
01006     data->rclass = rclass;
01007     data->defined_class = defined_class;
01008     data->id = rid;
01009     data->me = ALLOC(rb_method_entry_t);
01010     *data->me = *me;
01011     data->me->def->alias_count++;
01012     data->ume = ALLOC(struct unlinked_method_entry_list_entry);
01013 
01014     OBJ_INFECT(method, klass);
01015 
01016     return method;
01017 }
01018 
01019 
01020 /**********************************************************************
01021  *
01022  * Document-class : Method
01023  *
01024  *  Method objects are created by <code>Object#method</code>, and are
01025  *  associated with a particular object (not just with a class). They
01026  *  may be used to invoke the method within the object, and as a block
01027  *  associated with an iterator. They may also be unbound from one
01028  *  object (creating an <code>UnboundMethod</code>) and bound to
01029  *  another.
01030  *
01031  *     class Thing
01032  *       def square(n)
01033  *         n*n
01034  *       end
01035  *     end
01036  *     thing = Thing.new
01037  *     meth  = thing.method(:square)
01038  *
01039  *     meth.call(9)                 #=> 81
01040  *     [ 1, 2, 3 ].collect(&meth)   #=> [1, 4, 9]
01041  *
01042  */
01043 
01044 /*
01045  * call-seq:
01046  *   meth == other_meth  -> true or false
01047  *
01048  * Two method objects are equal if they are bound to the same
01049  * object and refer to the same method definition and their owners are the
01050  * same class or module.
01051  */
01052 
01053 static VALUE
01054 method_eq(VALUE method, VALUE other)
01055 {
01056     struct METHOD *m1, *m2;
01057 
01058     if (!rb_obj_is_method(other))
01059         return Qfalse;
01060     if (CLASS_OF(method) != CLASS_OF(other))
01061         return Qfalse;
01062 
01063     Check_TypedStruct(method, &method_data_type);
01064     m1 = (struct METHOD *)DATA_PTR(method);
01065     m2 = (struct METHOD *)DATA_PTR(other);
01066 
01067     if (!rb_method_entry_eq(m1->me, m2->me) ||
01068         m1->rclass != m2->rclass ||
01069         m1->recv != m2->recv) {
01070         return Qfalse;
01071     }
01072 
01073     return Qtrue;
01074 }
01075 
01076 /*
01077  * call-seq:
01078  *    meth.hash   -> integer
01079  *
01080  * Returns a hash value corresponding to the method object.
01081  */
01082 
01083 static VALUE
01084 method_hash(VALUE method)
01085 {
01086     struct METHOD *m;
01087     st_index_t hash;
01088 
01089     TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
01090     hash = rb_hash_start((st_index_t)m->rclass);
01091     hash = rb_hash_uint(hash, (st_index_t)m->recv);
01092     hash = rb_hash_method_entry(hash, m->me);
01093     hash = rb_hash_end(hash);
01094 
01095     return INT2FIX(hash);
01096 }
01097 
01098 /*
01099  *  call-seq:
01100  *     meth.unbind    -> unbound_method
01101  *
01102  *  Dissociates <i>meth</i> from its current receiver. The resulting
01103  *  <code>UnboundMethod</code> can subsequently be bound to a new object
01104  *  of the same class (see <code>UnboundMethod</code>).
01105  */
01106 
01107 static VALUE
01108 method_unbind(VALUE obj)
01109 {
01110     VALUE method;
01111     struct METHOD *orig, *data;
01112 
01113     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
01114     method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
01115                                    &method_data_type, data);
01116     data->recv = Qundef;
01117     data->id = orig->id;
01118     data->me = ALLOC(rb_method_entry_t);
01119     *data->me = *orig->me;
01120     if (orig->me->def) orig->me->def->alias_count++;
01121     data->rclass = orig->rclass;
01122     data->defined_class = orig->defined_class;
01123     data->ume = ALLOC(struct unlinked_method_entry_list_entry);
01124     OBJ_INFECT(method, obj);
01125 
01126     return method;
01127 }
01128 
01129 /*
01130  *  call-seq:
01131  *     meth.receiver    -> object
01132  *
01133  *  Returns the bound receiver of the method object.
01134  */
01135 
01136 static VALUE
01137 method_receiver(VALUE obj)
01138 {
01139     struct METHOD *data;
01140 
01141     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
01142     return data->recv;
01143 }
01144 
01145 /*
01146  *  call-seq:
01147  *     meth.name    -> symbol
01148  *
01149  *  Returns the name of the method.
01150  */
01151 
01152 static VALUE
01153 method_name(VALUE obj)
01154 {
01155     struct METHOD *data;
01156 
01157     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
01158     return ID2SYM(data->id);
01159 }
01160 
01161 /*
01162  *  call-seq:
01163  *     meth.owner    -> class_or_module
01164  *
01165  *  Returns the class or module that defines the method.
01166  */
01167 
01168 static VALUE
01169 method_owner(VALUE obj)
01170 {
01171     struct METHOD *data;
01172     VALUE defined_class;
01173 
01174     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
01175     defined_class = data->defined_class;
01176 
01177     if (RB_TYPE_P(defined_class, T_ICLASS)) {
01178         defined_class = RBASIC(defined_class)->klass;
01179     }
01180 
01181     return defined_class;
01182 }
01183 
01184 void
01185 rb_method_name_error(VALUE klass, VALUE str)
01186 {
01187     const char *s0 = " class";
01188     VALUE c = klass;
01189 
01190     if (FL_TEST(c, FL_SINGLETON)) {
01191         VALUE obj = rb_ivar_get(klass, attached);
01192 
01193         switch (TYPE(obj)) {
01194           case T_MODULE:
01195           case T_CLASS:
01196             c = obj;
01197             s0 = "";
01198         }
01199     }
01200     else if (RB_TYPE_P(c, T_MODULE)) {
01201         s0 = " module";
01202     }
01203     rb_name_error_str(str, "undefined method `%"PRIsVALUE"' for%s `%"PRIsVALUE"'",
01204                       QUOTE(str), s0, rb_class_name(c));
01205 }
01206 
01207 /*
01208  *  call-seq:
01209  *     obj.method(sym)    -> method
01210  *
01211  *  Looks up the named method as a receiver in <i>obj</i>, returning a
01212  *  <code>Method</code> object (or raising <code>NameError</code>). The
01213  *  <code>Method</code> object acts as a closure in <i>obj</i>'s object
01214  *  instance, so instance variables and the value of <code>self</code>
01215  *  remain available.
01216  *
01217  *     class Demo
01218  *       def initialize(n)
01219  *         @iv = n
01220  *       end
01221  *       def hello()
01222  *         "Hello, @iv = #{@iv}"
01223  *       end
01224  *     end
01225  *
01226  *     k = Demo.new(99)
01227  *     m = k.method(:hello)
01228  *     m.call   #=> "Hello, @iv = 99"
01229  *
01230  *     l = Demo.new('Fred')
01231  *     m = l.method("hello")
01232  *     m.call   #=> "Hello, @iv = Fred"
01233  */
01234 
01235 VALUE
01236 rb_obj_method(VALUE obj, VALUE vid)
01237 {
01238     ID id = rb_check_id(&vid);
01239     if (!id) {
01240         rb_method_name_error(CLASS_OF(obj), vid);
01241     }
01242     return mnew(CLASS_OF(obj), obj, id, rb_cMethod, FALSE);
01243 }
01244 
01245 /*
01246  *  call-seq:
01247  *     obj.public_method(sym)    -> method
01248  *
01249  *  Similar to _method_, searches public method only.
01250  */
01251 
01252 VALUE
01253 rb_obj_public_method(VALUE obj, VALUE vid)
01254 {
01255     ID id = rb_check_id(&vid);
01256     if (!id) {
01257         rb_method_name_error(CLASS_OF(obj), vid);
01258     }
01259     return mnew(CLASS_OF(obj), obj, id, rb_cMethod, TRUE);
01260 }
01261 
01262 /*
01263  *  call-seq:
01264  *     mod.instance_method(symbol)   -> unbound_method
01265  *
01266  *  Returns an +UnboundMethod+ representing the given
01267  *  instance method in _mod_.
01268  *
01269  *     class Interpreter
01270  *       def do_a() print "there, "; end
01271  *       def do_d() print "Hello ";  end
01272  *       def do_e() print "!\n";     end
01273  *       def do_v() print "Dave";    end
01274  *       Dispatcher = {
01275  *         "a" => instance_method(:do_a),
01276  *         "d" => instance_method(:do_d),
01277  *         "e" => instance_method(:do_e),
01278  *         "v" => instance_method(:do_v)
01279  *       }
01280  *       def interpret(string)
01281  *         string.each_char {|b| Dispatcher[b].bind(self).call }
01282  *       end
01283  *     end
01284  *
01285  *     interpreter = Interpreter.new
01286  *     interpreter.interpret('dave')
01287  *
01288  *  <em>produces:</em>
01289  *
01290  *     Hello there, Dave!
01291  */
01292 
01293 static VALUE
01294 rb_mod_instance_method(VALUE mod, VALUE vid)
01295 {
01296     ID id = rb_check_id(&vid);
01297     if (!id) {
01298         rb_method_name_error(mod, vid);
01299     }
01300     return mnew(mod, Qundef, id, rb_cUnboundMethod, FALSE);
01301 }
01302 
01303 /*
01304  *  call-seq:
01305  *     mod.public_instance_method(symbol)   -> unbound_method
01306  *
01307  *  Similar to _instance_method_, searches public method only.
01308  */
01309 
01310 static VALUE
01311 rb_mod_public_instance_method(VALUE mod, VALUE vid)
01312 {
01313     ID id = rb_check_id(&vid);
01314     if (!id) {
01315         rb_method_name_error(mod, vid);
01316     }
01317     return mnew(mod, Qundef, id, rb_cUnboundMethod, TRUE);
01318 }
01319 
01320 /*
01321  *  call-seq:
01322  *     define_method(symbol, method)     -> new_method
01323  *     define_method(symbol) { block }   -> proc
01324  *
01325  *  Defines an instance method in the receiver. The _method_
01326  *  parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
01327  *  If a block is specified, it is used as the method body. This block
01328  *  is evaluated using <code>instance_eval</code>, a point that is
01329  *  tricky to demonstrate because <code>define_method</code> is private.
01330  *  (This is why we resort to the +send+ hack in this example.)
01331  *
01332  *     class A
01333  *       def fred
01334  *         puts "In Fred"
01335  *       end
01336  *       def create_method(name, &block)
01337  *         self.class.send(:define_method, name, &block)
01338  *       end
01339  *       define_method(:wilma) { puts "Charge it!" }
01340  *     end
01341  *     class B < A
01342  *       define_method(:barney, instance_method(:fred))
01343  *     end
01344  *     a = B.new
01345  *     a.barney
01346  *     a.wilma
01347  *     a.create_method(:betty) { p self }
01348  *     a.betty
01349  *
01350  *  <em>produces:</em>
01351  *
01352  *     In Fred
01353  *     Charge it!
01354  *     #<B:0x401b39e8>
01355  */
01356 
01357 static VALUE
01358 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
01359 {
01360     ID id;
01361     VALUE body;
01362     int noex = NOEX_PUBLIC;
01363 
01364     if (argc == 1) {
01365         id = rb_to_id(argv[0]);
01366         body = rb_block_lambda();
01367     }
01368     else {
01369         rb_check_arity(argc, 1, 2);
01370         id = rb_to_id(argv[0]);
01371         body = argv[1];
01372         if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) {
01373             rb_raise(rb_eTypeError,
01374                      "wrong argument type %s (expected Proc/Method)",
01375                      rb_obj_classname(body));
01376         }
01377     }
01378 
01379     if (rb_obj_is_method(body)) {
01380         struct METHOD *method = (struct METHOD *)DATA_PTR(body);
01381         VALUE rclass = method->rclass;
01382         if (rclass != mod && !RB_TYPE_P(rclass, T_MODULE) &&
01383             !RTEST(rb_class_inherited_p(mod, rclass))) {
01384             if (FL_TEST(rclass, FL_SINGLETON)) {
01385                 rb_raise(rb_eTypeError,
01386                          "can't bind singleton method to a different class");
01387             }
01388             else {
01389                 rb_raise(rb_eTypeError,
01390                          "bind argument must be a subclass of %s",
01391                          rb_class2name(rclass));
01392             }
01393         }
01394         rb_method_entry_set(mod, id, method->me, noex);
01395     }
01396     else if (rb_obj_is_proc(body)) {
01397         rb_proc_t *proc;
01398         body = proc_dup(body);
01399         GetProcPtr(body, proc);
01400         if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) {
01401             proc->block.iseq->defined_method_id = id;
01402             proc->block.iseq->klass = mod;
01403             proc->is_lambda = TRUE;
01404             proc->is_from_method = TRUE;
01405             proc->block.klass = mod;
01406         }
01407         rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)body, noex);
01408     }
01409     else {
01410         /* type error */
01411         rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
01412     }
01413 
01414     return body;
01415 }
01416 
01417 /*
01418  *  call-seq:
01419  *     define_singleton_method(symbol, method) -> new_method
01420  *     define_singleton_method(symbol) { block } -> proc
01421  *
01422  *  Defines a singleton method in the receiver. The _method_
01423  *  parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
01424  *  If a block is specified, it is used as the method body.
01425  *
01426  *     class A
01427  *       class << self
01428  *         def class_name
01429  *           to_s
01430  *         end
01431  *       end
01432  *     end
01433  *     A.define_singleton_method(:who_am_i) do
01434  *       "I am: #{class_name}"
01435  *     end
01436  *     A.who_am_i   # ==> "I am: A"
01437  *
01438  *     guy = "Bob"
01439  *     guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
01440  *     guy.hello    #=>  "Bob: Hello there!"
01441  */
01442 
01443 static VALUE
01444 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
01445 {
01446     VALUE klass = rb_singleton_class(obj);
01447 
01448     return rb_mod_define_method(argc, argv, klass);
01449 }
01450 
01451 /*
01452  *     define_method(symbol, method)     -> new_method
01453  *     define_method(symbol) { block }   -> proc
01454  *
01455  *  Defines a global function by _method_ or the block.
01456  */
01457 
01458 static VALUE
01459 top_define_method(int argc, VALUE *argv, VALUE obj)
01460 {
01461     rb_thread_t *th = GET_THREAD();
01462     VALUE klass;
01463 
01464     rb_secure(4);
01465     klass = th->top_wrapper;
01466     if (klass) {
01467         rb_warning("main.define_method in the wrapped load is effective only in wrapper module");
01468     }
01469     else {
01470         klass = rb_cObject;
01471     }
01472     return rb_mod_define_method(argc, argv, klass);
01473 }
01474 
01475 /*
01476  *  call-seq:
01477  *    method.clone -> new_method
01478  *
01479  *  Returns a clone of this method.
01480  *
01481  *    class A
01482  *      def foo
01483  *        return "bar"
01484  *      end
01485  *    end
01486  *
01487  *    m = A.new.method(:foo)
01488  *    m.call # => "bar"
01489  *    n = m.clone.call # => "bar"
01490  */
01491 
01492 static VALUE
01493 method_clone(VALUE self)
01494 {
01495     VALUE clone;
01496     struct METHOD *orig, *data;
01497 
01498     TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
01499     clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
01500     CLONESETUP(clone, self);
01501     *data = *orig;
01502     data->me = ALLOC(rb_method_entry_t);
01503     *data->me = *orig->me;
01504     if (data->me->def) data->me->def->alias_count++;
01505     data->ume = ALLOC(struct unlinked_method_entry_list_entry);
01506 
01507     return clone;
01508 }
01509 
01510 /*
01511  *  call-seq:
01512  *     meth.call(args, ...)    -> obj
01513  *     meth[args, ...]         -> obj
01514  *
01515  *  Invokes the <i>meth</i> with the specified arguments, returning the
01516  *  method's return value.
01517  *
01518  *     m = 12.method("+")
01519  *     m.call(3)    #=> 15
01520  *     m.call(20)   #=> 32
01521  */
01522 
01523 VALUE
01524 rb_method_call(int argc, VALUE *argv, VALUE method)
01525 {
01526     VALUE proc = rb_block_given_p() ? rb_block_proc() : Qnil;
01527     return rb_method_call_with_block(argc, argv, method, proc);
01528 }
01529 
01530 VALUE
01531 rb_method_call_with_block(int argc, VALUE *argv, VALUE method, VALUE pass_procval)
01532 {
01533     VALUE result = Qnil;        /* OK */
01534     struct METHOD *data;
01535     int state;
01536     volatile int safe = -1;
01537 
01538     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01539     if (data->recv == Qundef) {
01540         rb_raise(rb_eTypeError, "can't call unbound method; bind first");
01541     }
01542     PUSH_TAG();
01543     if (OBJ_TAINTED(method)) {
01544         const int safe_level_to_run = 4 /*SAFE_LEVEL_MAX*/;
01545         safe = rb_safe_level();
01546         if (rb_safe_level() < safe_level_to_run) {
01547             rb_set_safe_level_force(safe_level_to_run);
01548         }
01549     }
01550     if ((state = EXEC_TAG()) == 0) {
01551         rb_thread_t *th = GET_THREAD();
01552         rb_block_t *block = 0;
01553 
01554         if (!NIL_P(pass_procval)) {
01555             rb_proc_t *pass_proc;
01556             GetProcPtr(pass_procval, pass_proc);
01557             block = &pass_proc->block;
01558         }
01559 
01560         th->passed_block = block;
01561         result = rb_vm_call(th, data->recv, data->id,  argc, argv, data->me, data->defined_class);
01562     }
01563     POP_TAG();
01564     if (safe >= 0)
01565         rb_set_safe_level_force(safe);
01566     if (state)
01567         JUMP_TAG(state);
01568     return result;
01569 }
01570 
01571 /**********************************************************************
01572  *
01573  * Document-class: UnboundMethod
01574  *
01575  *  Ruby supports two forms of objectified methods. Class
01576  *  <code>Method</code> is used to represent methods that are associated
01577  *  with a particular object: these method objects are bound to that
01578  *  object. Bound method objects for an object can be created using
01579  *  <code>Object#method</code>.
01580  *
01581  *  Ruby also supports unbound methods; methods objects that are not
01582  *  associated with a particular object. These can be created either by
01583  *  calling <code>Module#instance_method</code> or by calling
01584  *  <code>unbind</code> on a bound method object. The result of both of
01585  *  these is an <code>UnboundMethod</code> object.
01586  *
01587  *  Unbound methods can only be called after they are bound to an
01588  *  object. That object must be be a kind_of? the method's original
01589  *  class.
01590  *
01591  *     class Square
01592  *       def area
01593  *         @side * @side
01594  *       end
01595  *       def initialize(side)
01596  *         @side = side
01597  *       end
01598  *     end
01599  *
01600  *     area_un = Square.instance_method(:area)
01601  *
01602  *     s = Square.new(12)
01603  *     area = area_un.bind(s)
01604  *     area.call   #=> 144
01605  *
01606  *  Unbound methods are a reference to the method at the time it was
01607  *  objectified: subsequent changes to the underlying class will not
01608  *  affect the unbound method.
01609  *
01610  *     class Test
01611  *       def test
01612  *         :original
01613  *       end
01614  *     end
01615  *     um = Test.instance_method(:test)
01616  *     class Test
01617  *       def test
01618  *         :modified
01619  *       end
01620  *     end
01621  *     t = Test.new
01622  *     t.test            #=> :modified
01623  *     um.bind(t).call   #=> :original
01624  *
01625  */
01626 
01627 /*
01628  *  call-seq:
01629  *     umeth.bind(obj) -> method
01630  *
01631  *  Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
01632  *  from which <i>umeth</i> was obtained,
01633  *  <code>obj.kind_of?(Klass)</code> must be true.
01634  *
01635  *     class A
01636  *       def test
01637  *         puts "In test, class = #{self.class}"
01638  *       end
01639  *     end
01640  *     class B < A
01641  *     end
01642  *     class C < B
01643  *     end
01644  *
01645  *
01646  *     um = B.instance_method(:test)
01647  *     bm = um.bind(C.new)
01648  *     bm.call
01649  *     bm = um.bind(B.new)
01650  *     bm.call
01651  *     bm = um.bind(A.new)
01652  *     bm.call
01653  *
01654  *  <em>produces:</em>
01655  *
01656  *     In test, class = C
01657  *     In test, class = B
01658  *     prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
01659  *      from prog.rb:16
01660  */
01661 
01662 static VALUE
01663 umethod_bind(VALUE method, VALUE recv)
01664 {
01665     struct METHOD *data, *bound;
01666 
01667     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01668 
01669     if (!RB_TYPE_P(data->rclass, T_MODULE) &&
01670         data->rclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, data->rclass)) {
01671         if (FL_TEST(data->rclass, FL_SINGLETON)) {
01672             rb_raise(rb_eTypeError,
01673                      "singleton method called for a different object");
01674         }
01675         else {
01676             rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
01677                      rb_class2name(data->rclass));
01678         }
01679     }
01680 
01681     method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
01682     *bound = *data;
01683     bound->me = ALLOC(rb_method_entry_t);
01684     *bound->me = *data->me;
01685     if (bound->me->def) bound->me->def->alias_count++;
01686     bound->recv = recv;
01687     bound->rclass = CLASS_OF(recv);
01688     data->ume = ALLOC(struct unlinked_method_entry_list_entry);
01689 
01690     return method;
01691 }
01692 
01693 /*
01694  * Returns the number of required parameters and stores the maximum
01695  * number of parameters in max, or UNLIMITED_ARGUMENTS
01696  * if there is no maximum.
01697  */
01698 static int
01699 rb_method_entry_min_max_arity(const rb_method_entry_t *me, int *max)
01700 {
01701     const rb_method_definition_t *def = me->def;
01702     if (!def) return *max = 0;
01703     switch (def->type) {
01704       case VM_METHOD_TYPE_CFUNC:
01705         if (def->body.cfunc.argc < 0) {
01706             *max = UNLIMITED_ARGUMENTS;
01707             return 0;
01708         }
01709         return *max = check_argc(def->body.cfunc.argc);
01710       case VM_METHOD_TYPE_ZSUPER:
01711         *max = UNLIMITED_ARGUMENTS;
01712         return 0;
01713       case VM_METHOD_TYPE_ATTRSET:
01714         return *max = 1;
01715       case VM_METHOD_TYPE_IVAR:
01716         return *max = 0;
01717       case VM_METHOD_TYPE_BMETHOD:
01718         return rb_proc_min_max_arity(def->body.proc, max);
01719       case VM_METHOD_TYPE_ISEQ: {
01720         rb_iseq_t *iseq = def->body.iseq;
01721         return rb_iseq_min_max_arity(iseq, max);
01722       }
01723       case VM_METHOD_TYPE_UNDEF:
01724       case VM_METHOD_TYPE_NOTIMPLEMENTED:
01725         return *max = 0;
01726       case VM_METHOD_TYPE_MISSING:
01727         *max = UNLIMITED_ARGUMENTS;
01728         return 0;
01729       case VM_METHOD_TYPE_OPTIMIZED: {
01730         switch (def->body.optimize_type) {
01731           case OPTIMIZED_METHOD_TYPE_SEND:
01732             *max = UNLIMITED_ARGUMENTS;
01733             return 0;
01734           default:
01735             break;
01736         }
01737       }
01738       case VM_METHOD_TYPE_REFINED:
01739         *max = UNLIMITED_ARGUMENTS;
01740         return 0;
01741     }
01742     rb_bug("rb_method_entry_min_max_arity: invalid method entry type (%d)", def->type);
01743     UNREACHABLE;
01744 }
01745 
01746 int
01747 rb_method_entry_arity(const rb_method_entry_t *me)
01748 {
01749     int max, min = rb_method_entry_min_max_arity(me, &max);
01750     return min == max ? min : -min-1;
01751 }
01752 
01753 /*
01754  *  call-seq:
01755  *     meth.arity    -> fixnum
01756  *
01757  *  Returns an indication of the number of arguments accepted by a
01758  *  method. Returns a nonnegative integer for methods that take a fixed
01759  *  number of arguments. For Ruby methods that take a variable number of
01760  *  arguments, returns -n-1, where n is the number of required
01761  *  arguments. For methods written in C, returns -1 if the call takes a
01762  *  variable number of arguments.
01763  *
01764  *     class C
01765  *       def one;    end
01766  *       def two(a); end
01767  *       def three(*a);  end
01768  *       def four(a, b); end
01769  *       def five(a, b, *c);    end
01770  *       def six(a, b, *c, &d); end
01771  *     end
01772  *     c = C.new
01773  *     c.method(:one).arity     #=> 0
01774  *     c.method(:two).arity     #=> 1
01775  *     c.method(:three).arity   #=> -1
01776  *     c.method(:four).arity    #=> 2
01777  *     c.method(:five).arity    #=> -3
01778  *     c.method(:six).arity     #=> -3
01779  *
01780  *     "cat".method(:size).arity      #=> 0
01781  *     "cat".method(:replace).arity   #=> 1
01782  *     "cat".method(:squeeze).arity   #=> -1
01783  *     "cat".method(:count).arity     #=> -1
01784  */
01785 
01786 static VALUE
01787 method_arity_m(VALUE method)
01788 {
01789     int n = method_arity(method);
01790     return INT2FIX(n);
01791 }
01792 
01793 static int
01794 method_arity(VALUE method)
01795 {
01796     struct METHOD *data;
01797 
01798     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01799     return rb_method_entry_arity(data->me);
01800 }
01801 
01802 static rb_method_entry_t *
01803 original_method_entry(VALUE mod, ID id)
01804 {
01805     VALUE rclass;
01806     rb_method_entry_t *me;
01807     while ((me = rb_method_entry(mod, id, &rclass)) != 0) {
01808         rb_method_definition_t *def = me->def;
01809         if (!def) break;
01810         if (def->type != VM_METHOD_TYPE_ZSUPER) break;
01811         mod = RCLASS_SUPER(rclass);
01812         id = def->original_id;
01813     }
01814     return me;
01815 }
01816 
01817 static int
01818 method_min_max_arity(VALUE method, int *max)
01819 {
01820     struct METHOD *data;
01821 
01822     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01823     return rb_method_entry_min_max_arity(data->me, max);
01824 }
01825 
01826 int
01827 rb_mod_method_arity(VALUE mod, ID id)
01828 {
01829     rb_method_entry_t *me = original_method_entry(mod, id);
01830     if (!me) return 0;          /* should raise? */
01831     return rb_method_entry_arity(me);
01832 }
01833 
01834 int
01835 rb_obj_method_arity(VALUE obj, ID id)
01836 {
01837     return rb_mod_method_arity(CLASS_OF(obj), id);
01838 }
01839 
01840 static inline rb_method_definition_t *
01841 method_get_def(VALUE method)
01842 {
01843     struct METHOD *data;
01844 
01845     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01846     return data->me->def;
01847 }
01848 
01849 static rb_iseq_t *
01850 method_get_iseq(rb_method_definition_t *def)
01851 {
01852     switch (def->type) {
01853       case VM_METHOD_TYPE_BMETHOD:
01854         return get_proc_iseq(def->body.proc, 0);
01855       case VM_METHOD_TYPE_ISEQ:
01856         return def->body.iseq;
01857       default:
01858         return 0;
01859     }
01860 }
01861 
01862 rb_iseq_t *
01863 rb_method_get_iseq(VALUE method)
01864 {
01865     return method_get_iseq(method_get_def(method));
01866 }
01867 
01868 static VALUE
01869 method_def_location(rb_method_definition_t *def)
01870 {
01871     if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
01872         if (!def->body.attr.location)
01873             return Qnil;
01874         return rb_ary_dup(def->body.attr.location);
01875     }
01876     return iseq_location(method_get_iseq(def));
01877 }
01878 
01879 VALUE
01880 rb_method_entry_location(rb_method_entry_t *me)
01881 {
01882     if (!me || !me->def) return Qnil;
01883     return method_def_location(me->def);
01884 }
01885 
01886 VALUE
01887 rb_mod_method_location(VALUE mod, ID id)
01888 {
01889     rb_method_entry_t *me = original_method_entry(mod, id);
01890     return rb_method_entry_location(me);
01891 }
01892 
01893 VALUE
01894 rb_obj_method_location(VALUE obj, ID id)
01895 {
01896     return rb_mod_method_location(CLASS_OF(obj), id);
01897 }
01898 
01899 /*
01900  * call-seq:
01901  *    meth.source_location  -> [String, Fixnum]
01902  *
01903  * Returns the Ruby source filename and line number containing this method
01904  * or nil if this method was not defined in Ruby (i.e. native)
01905  */
01906 
01907 VALUE
01908 rb_method_location(VALUE method)
01909 {
01910     rb_method_definition_t *def = method_get_def(method);
01911     return method_def_location(def);
01912 }
01913 
01914 /*
01915  * call-seq:
01916  *    meth.parameters  -> array
01917  *
01918  * Returns the parameter information of this method.
01919  */
01920 
01921 static VALUE
01922 rb_method_parameters(VALUE method)
01923 {
01924     rb_iseq_t *iseq = rb_method_get_iseq(method);
01925     if (!iseq) {
01926         return unnamed_parameters(method_arity(method));
01927     }
01928     return rb_iseq_parameters(iseq, 0);
01929 }
01930 
01931 /*
01932  *  call-seq:
01933  *   meth.to_s      ->  string
01934  *   meth.inspect   ->  string
01935  *
01936  *  Returns the name of the underlying method.
01937  *
01938  *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
01939  */
01940 
01941 static VALUE
01942 method_inspect(VALUE method)
01943 {
01944     struct METHOD *data;
01945     VALUE str;
01946     const char *s;
01947     const char *sharp = "#";
01948 
01949     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
01950     str = rb_str_buf_new2("#<");
01951     s = rb_obj_classname(method);
01952     rb_str_buf_cat2(str, s);
01953     rb_str_buf_cat2(str, ": ");
01954 
01955     if (FL_TEST(data->me->klass, FL_SINGLETON)) {
01956         VALUE v = rb_ivar_get(data->me->klass, attached);
01957 
01958         if (data->recv == Qundef) {
01959             rb_str_buf_append(str, rb_inspect(data->me->klass));
01960         }
01961         else if (data->recv == v) {
01962             rb_str_buf_append(str, rb_inspect(v));
01963             sharp = ".";
01964         }
01965         else {
01966             rb_str_buf_append(str, rb_inspect(data->recv));
01967             rb_str_buf_cat2(str, "(");
01968             rb_str_buf_append(str, rb_inspect(v));
01969             rb_str_buf_cat2(str, ")");
01970             sharp = ".";
01971         }
01972     }
01973     else {
01974         rb_str_buf_cat2(str, rb_class2name(data->rclass));
01975         if (data->rclass != data->me->klass) {
01976             rb_str_buf_cat2(str, "(");
01977             rb_str_buf_cat2(str, rb_class2name(data->me->klass));
01978             rb_str_buf_cat2(str, ")");
01979         }
01980     }
01981     rb_str_buf_cat2(str, sharp);
01982     rb_str_append(str, rb_id2str(data->me->def->original_id));
01983     if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
01984         rb_str_buf_cat2(str, " (not-implemented)");
01985     }
01986     rb_str_buf_cat2(str, ">");
01987 
01988     return str;
01989 }
01990 
01991 static VALUE
01992 mproc(VALUE method)
01993 {
01994     return rb_funcall2(rb_mRubyVMFrozenCore, idProc, 0, 0);
01995 }
01996 
01997 static VALUE
01998 mlambda(VALUE method)
01999 {
02000     return rb_funcall(rb_mRubyVMFrozenCore, idLambda, 0, 0);
02001 }
02002 
02003 static VALUE
02004 bmcall(VALUE args, VALUE method, int argc, VALUE *argv, VALUE passed_proc)
02005 {
02006     volatile VALUE a;
02007     VALUE ret;
02008 
02009     if (CLASS_OF(args) != rb_cArray) {
02010         args = rb_ary_new3(1, args);
02011         argc = 1;
02012     }
02013     else {
02014         argc = check_argc(RARRAY_LEN(args));
02015     }
02016     ret = rb_method_call_with_block(argc, RARRAY_PTR(args), method, passed_proc);
02017     RB_GC_GUARD(a) = args;
02018     return ret;
02019 }
02020 
02021 VALUE
02022 rb_proc_new(
02023     VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */
02024     VALUE val)
02025 {
02026     VALUE procval = rb_iterate(mproc, 0, func, val);
02027     return procval;
02028 }
02029 
02030 /*
02031  *  call-seq:
02032  *     meth.to_proc    -> prc
02033  *
02034  *  Returns a <code>Proc</code> object corresponding to this method.
02035  */
02036 
02037 static VALUE
02038 method_proc(VALUE method)
02039 {
02040     VALUE procval;
02041     rb_proc_t *proc;
02042     /*
02043      * class Method
02044      *   def to_proc
02045      *     proc{|*args|
02046      *       self.call(*args)
02047      *     }
02048      *   end
02049      * end
02050      */
02051     procval = rb_iterate(mlambda, 0, bmcall, method);
02052     GetProcPtr(procval, proc);
02053     proc->is_from_method = 1;
02054     return procval;
02055 }
02056 
02057 /*
02058  * call_seq:
02059  *   local_jump_error.exit_value  -> obj
02060  *
02061  * Returns the exit value associated with this +LocalJumpError+.
02062  */
02063 static VALUE
02064 localjump_xvalue(VALUE exc)
02065 {
02066     return rb_iv_get(exc, "@exit_value");
02067 }
02068 
02069 /*
02070  * call-seq:
02071  *    local_jump_error.reason   -> symbol
02072  *
02073  * The reason this block was terminated:
02074  * :break, :redo, :retry, :next, :return, or :noreason.
02075  */
02076 
02077 static VALUE
02078 localjump_reason(VALUE exc)
02079 {
02080     return rb_iv_get(exc, "@reason");
02081 }
02082 
02083 /*
02084  *  call-seq:
02085  *     prc.binding    -> binding
02086  *
02087  *  Returns the binding associated with <i>prc</i>. Note that
02088  *  <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
02089  *  <code>Binding</code> object as its second parameter.
02090  *
02091  *     def fred(param)
02092  *       proc {}
02093  *     end
02094  *
02095  *     b = fred(99)
02096  *     eval("param", b.binding)   #=> 99
02097  */
02098 static VALUE
02099 proc_binding(VALUE self)
02100 {
02101     rb_proc_t *proc;
02102     VALUE bindval;
02103     rb_binding_t *bind;
02104 
02105     GetProcPtr(self, proc);
02106     if (RB_TYPE_P((VALUE)proc->block.iseq, T_NODE)) {
02107         if (!IS_METHOD_PROC_NODE((NODE *)proc->block.iseq)) {
02108             rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
02109         }
02110     }
02111 
02112     bindval = binding_alloc(rb_cBinding);
02113     GetBindingPtr(bindval, bind);
02114     bind->env = proc->envval;
02115     if (RUBY_VM_NORMAL_ISEQ_P(proc->block.iseq)) {
02116         bind->path = proc->block.iseq->location.path;
02117         bind->first_lineno = rb_iseq_first_lineno(proc->block.iseq);
02118     }
02119     else {
02120         bind->path = Qnil;
02121         bind->first_lineno = 0;
02122     }
02123     return bindval;
02124 }
02125 
02126 static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc);
02127 
02128 static VALUE
02129 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
02130 {
02131     VALUE args = rb_ary_new3(3, proc, passed, arity);
02132     rb_proc_t *procp;
02133     int is_lambda;
02134 
02135     GetProcPtr(proc, procp);
02136     is_lambda = procp->is_lambda;
02137     rb_ary_freeze(passed);
02138     rb_ary_freeze(args);
02139     proc = rb_proc_new(curry, args);
02140     GetProcPtr(proc, procp);
02141     procp->is_lambda = is_lambda;
02142     return proc;
02143 }
02144 
02145 static VALUE
02146 curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc)
02147 {
02148     VALUE proc, passed, arity;
02149     proc = RARRAY_PTR(args)[0];
02150     passed = RARRAY_PTR(args)[1];
02151     arity = RARRAY_PTR(args)[2];
02152 
02153     passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
02154     rb_ary_freeze(passed);
02155 
02156     if (RARRAY_LEN(passed) < FIX2INT(arity)) {
02157         if (!NIL_P(passed_proc)) {
02158             rb_warn("given block not used");
02159         }
02160         arity = make_curry_proc(proc, passed, arity);
02161         return arity;
02162     }
02163     else {
02164         return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)),
02165                                        RARRAY_PTR(passed), passed_proc);
02166     }
02167 }
02168 
02169  /*
02170   *  call-seq:
02171   *     prc.curry         -> a_proc
02172   *     prc.curry(arity)  -> a_proc
02173   *
02174   *  Returns a curried proc. If the optional <i>arity</i> argument is given,
02175   *  it determines the number of arguments.
02176   *  A curried proc receives some arguments. If a sufficient number of
02177   *  arguments are supplied, it passes the supplied arguments to the original
02178   *  proc and returns the result. Otherwise, returns another curried proc that
02179   *  takes the rest of arguments.
02180   *
02181   *     b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
02182   *     p b.curry[1][2][3]           #=> 6
02183   *     p b.curry[1, 2][3, 4]        #=> 6
02184   *     p b.curry(5)[1][2][3][4][5]  #=> 6
02185   *     p b.curry(5)[1, 2][3, 4][5]  #=> 6
02186   *     p b.curry(1)[1]              #=> 1
02187   *
02188   *     b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
02189   *     p b.curry[1][2][3]           #=> 6
02190   *     p b.curry[1, 2][3, 4]        #=> 10
02191   *     p b.curry(5)[1][2][3][4][5]  #=> 15
02192   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
02193   *     p b.curry(1)[1]              #=> 1
02194   *
02195   *     b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
02196   *     p b.curry[1][2][3]           #=> 6
02197   *     p b.curry[1, 2][3, 4]        #=> wrong number of arguments (4 for 3)
02198   *     p b.curry(5)                 #=> wrong number of arguments (5 for 3)
02199   *     p b.curry(1)                 #=> wrong number of arguments (1 for 3)
02200   *
02201   *     b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
02202   *     p b.curry[1][2][3]           #=> 6
02203   *     p b.curry[1, 2][3, 4]        #=> 10
02204   *     p b.curry(5)[1][2][3][4][5]  #=> 15
02205   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
02206   *     p b.curry(1)                 #=> wrong number of arguments (1 for 3)
02207   *
02208   *     b = proc { :foo }
02209   *     p b.curry[]                  #=> :foo
02210   */
02211 static VALUE
02212 proc_curry(int argc, VALUE *argv, VALUE self)
02213 {
02214     int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
02215     VALUE arity;
02216 
02217     rb_scan_args(argc, argv, "01", &arity);
02218     if (NIL_P(arity)) {
02219         arity = INT2FIX(min_arity);
02220     }
02221     else {
02222         sarity = FIX2INT(arity);
02223         if (rb_proc_lambda_p(self)) {
02224             rb_check_arity(sarity, min_arity, max_arity);
02225         }
02226     }
02227 
02228     return make_curry_proc(self, rb_ary_new(), arity);
02229 }
02230 
02231 /*
02232  *  Document-class: LocalJumpError
02233  *
02234  *  Raised when Ruby can't yield as requested.
02235  *
02236  *  A typical scenario is attempting to yield when no block is given:
02237  *
02238  *     def call_block
02239  *       yield 42
02240  *     end
02241  *     call_block
02242  *
02243  *  <em>raises the exception:</em>
02244  *
02245  *     LocalJumpError: no block given (yield)
02246  *
02247  *  A more subtle example:
02248  *
02249  *     def get_me_a_return
02250  *       Proc.new { return 42 }
02251  *     end
02252  *     get_me_a_return.call
02253  *
02254  *  <em>raises the exception:</em>
02255  *
02256  *     LocalJumpError: unexpected return
02257  */
02258 
02259 /*
02260  *  Document-class: SystemStackError
02261  *
02262  *  Raised in case of a stack overflow.
02263  *
02264  *     def me_myself_and_i
02265  *       me_myself_and_i
02266  *     end
02267  *     me_myself_and_i
02268  *
02269  *  <em>raises the exception:</em>
02270  *
02271  *    SystemStackError: stack level too deep
02272  */
02273 
02274 /*
02275  *  <code>Proc</code> objects are blocks of code that have been bound to
02276  *  a set of local variables. Once bound, the code may be called in
02277  *  different contexts and still access those variables.
02278  *
02279  *     def gen_times(factor)
02280  *       return Proc.new {|n| n*factor }
02281  *     end
02282  *
02283  *     times3 = gen_times(3)
02284  *     times5 = gen_times(5)
02285  *
02286  *     times3.call(12)               #=> 36
02287  *     times5.call(5)                #=> 25
02288  *     times3.call(times5.call(4))   #=> 60
02289  *
02290  */
02291 
02292 void
02293 Init_Proc(void)
02294 {
02295     /* Proc */
02296     rb_cProc = rb_define_class("Proc", rb_cObject);
02297     rb_undef_alloc_func(rb_cProc);
02298     rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
02299 
02300 #if 0 /* incomplete. */
02301     rb_add_method(rb_cProc, rb_intern("call"), VM_METHOD_TYPE_OPTIMIZED,
02302                   (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
02303     rb_add_method(rb_cProc, rb_intern("[]"), VM_METHOD_TYPE_OPTIMIZED,
02304                   (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
02305     rb_add_method(rb_cProc, rb_intern("==="), VM_METHOD_TYPE_OPTIMIZED,
02306                   (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
02307     rb_add_method(rb_cProc, rb_intern("yield"), VM_METHOD_TYPE_OPTIMIZED,
02308                   (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
02309 #else
02310     rb_define_method(rb_cProc, "call", proc_call, -1);
02311     rb_define_method(rb_cProc, "[]", proc_call, -1);
02312     rb_define_method(rb_cProc, "===", proc_call, -1);
02313     rb_define_method(rb_cProc, "yield", proc_call, -1);
02314 #endif
02315     rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
02316     rb_define_method(rb_cProc, "arity", proc_arity, 0);
02317     rb_define_method(rb_cProc, "clone", proc_clone, 0);
02318     rb_define_method(rb_cProc, "dup", proc_dup, 0);
02319     rb_define_method(rb_cProc, "hash", proc_hash, 0);
02320     rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
02321     rb_define_alias(rb_cProc, "inspect", "to_s");
02322     rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
02323     rb_define_method(rb_cProc, "binding", proc_binding, 0);
02324     rb_define_method(rb_cProc, "curry", proc_curry, -1);
02325     rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
02326     rb_define_method(rb_cProc, "parameters", rb_proc_parameters, 0);
02327 
02328     /* Exceptions */
02329     rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
02330     rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
02331     rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
02332 
02333     rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
02334     sysstack_error = rb_exc_new3(rb_eSysStackError,
02335                                  rb_obj_freeze(rb_str_new2("stack level too deep")));
02336     OBJ_TAINT(sysstack_error);
02337 
02338     /* utility functions */
02339     rb_define_global_function("proc", rb_block_proc, 0);
02340     rb_define_global_function("lambda", rb_block_lambda, 0);
02341 
02342     /* Method */
02343     rb_cMethod = rb_define_class("Method", rb_cObject);
02344     rb_undef_alloc_func(rb_cMethod);
02345     rb_undef_method(CLASS_OF(rb_cMethod), "new");
02346     rb_define_method(rb_cMethod, "==", method_eq, 1);
02347     rb_define_method(rb_cMethod, "eql?", method_eq, 1);
02348     rb_define_method(rb_cMethod, "hash", method_hash, 0);
02349     rb_define_method(rb_cMethod, "clone", method_clone, 0);
02350     rb_define_method(rb_cMethod, "call", rb_method_call, -1);
02351     rb_define_method(rb_cMethod, "[]", rb_method_call, -1);
02352     rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
02353     rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
02354     rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
02355     rb_define_method(rb_cMethod, "to_proc", method_proc, 0);
02356     rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
02357     rb_define_method(rb_cMethod, "name", method_name, 0);
02358     rb_define_method(rb_cMethod, "owner", method_owner, 0);
02359     rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
02360     rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
02361     rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
02362     rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
02363     rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
02364 
02365     /* UnboundMethod */
02366     rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
02367     rb_undef_alloc_func(rb_cUnboundMethod);
02368     rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
02369     rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
02370     rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
02371     rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
02372     rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
02373     rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
02374     rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
02375     rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
02376     rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
02377     rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
02378     rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
02379     rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
02380     rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
02381 
02382     /* Module#*_method */
02383     rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
02384     rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
02385     rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
02386 
02387     /* Kernel */
02388     rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
02389 
02390     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
02391                              "define_method", top_define_method, -1);
02392 }
02393 
02394 /*
02395  *  Objects of class <code>Binding</code> encapsulate the execution
02396  *  context at some particular place in the code and retain this context
02397  *  for future use. The variables, methods, value of <code>self</code>,
02398  *  and possibly an iterator block that can be accessed in this context
02399  *  are all retained. Binding objects can be created using
02400  *  <code>Kernel#binding</code>, and are made available to the callback
02401  *  of <code>Kernel#set_trace_func</code>.
02402  *
02403  *  These binding objects can be passed as the second argument of the
02404  *  <code>Kernel#eval</code> method, establishing an environment for the
02405  *  evaluation.
02406  *
02407  *     class Demo
02408  *       def initialize(n)
02409  *         @secret = n
02410  *       end
02411  *       def get_binding
02412  *         return binding()
02413  *       end
02414  *     end
02415  *
02416  *     k1 = Demo.new(99)
02417  *     b1 = k1.get_binding
02418  *     k2 = Demo.new(-3)
02419  *     b2 = k2.get_binding
02420  *
02421  *     eval("@secret", b1)   #=> 99
02422  *     eval("@secret", b2)   #=> -3
02423  *     eval("@secret")       #=> nil
02424  *
02425  *  Binding objects have no class-specific methods.
02426  *
02427  */
02428 
02429 void
02430 Init_Binding(void)
02431 {
02432     rb_cBinding = rb_define_class("Binding", rb_cObject);
02433     rb_undef_alloc_func(rb_cBinding);
02434     rb_undef_method(CLASS_OF(rb_cBinding), "new");
02435     rb_define_method(rb_cBinding, "clone", binding_clone, 0);
02436     rb_define_method(rb_cBinding, "dup", binding_dup, 0);
02437     rb_define_method(rb_cBinding, "eval", bind_eval, -1);
02438     rb_define_global_function("binding", rb_f_binding, 0);
02439     attached = rb_intern("__attached__");
02440 }
02441 
02442