"Fossies" - the Fresh Open Source Software Archive

Member "ruby-2.7.4/proc.c" (7 Jul 2021, 114480 Bytes) of package /linux/misc/ruby-2.7.4.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "proc.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.7.3_vs_2.7.4.

    1 /**********************************************************************
    2 
    3   proc.c - Proc, Binding, Env
    4 
    5   $Author$
    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 "internal.h"
   14 #include "gc.h"
   15 #include "vm_core.h"
   16 #include "iseq.h"
   17 
   18 /* Proc.new with no block will raise an exception in the future
   19  * versions */
   20 #define PROC_NEW_REQUIRES_BLOCK 0
   21 
   22 #if !defined(__GNUC__) || __GNUC__ < 5 || defined(__MINGW32__)
   23 # define NO_CLOBBERED(v) (*(volatile VALUE *)&(v))
   24 #else
   25 # define NO_CLOBBERED(v) (v)
   26 #endif
   27 
   28 #define UPDATE_TYPED_REFERENCE(_type, _ref) *(_type*)&_ref = (_type)rb_gc_location((VALUE)_ref)
   29 #define UPDATE_REFERENCE(_ref) UPDATE_TYPED_REFERENCE(VALUE, _ref)
   30 
   31 const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
   32 
   33 struct METHOD {
   34     const VALUE recv;
   35     const VALUE klass;
   36     const VALUE iclass;
   37     const rb_method_entry_t * const me;
   38     /* for bound methods, `me' should be rb_callable_method_entry_t * */
   39 };
   40 
   41 VALUE rb_cUnboundMethod;
   42 VALUE rb_cMethod;
   43 VALUE rb_cBinding;
   44 VALUE rb_cProc;
   45 
   46 static rb_block_call_func bmcall;
   47 static int method_arity(VALUE);
   48 static int method_min_max_arity(VALUE, int *max);
   49 
   50 #define attached id__attached__
   51 
   52 /* Proc */
   53 
   54 #define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
   55 
   56 static void
   57 block_mark(const struct rb_block *block)
   58 {
   59     switch (vm_block_type(block)) {
   60       case block_type_iseq:
   61       case block_type_ifunc:
   62     {
   63         const struct rb_captured_block *captured = &block->as.captured;
   64         RUBY_MARK_NO_PIN_UNLESS_NULL(captured->self);
   65         RUBY_MARK_NO_PIN_UNLESS_NULL((VALUE)captured->code.val);
   66         if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) {
   67                 RUBY_MARK_NO_PIN_UNLESS_NULL(VM_ENV_ENVVAL(captured->ep));
   68         }
   69     }
   70     break;
   71       case block_type_symbol:
   72     RUBY_MARK_NO_PIN_UNLESS_NULL(block->as.symbol);
   73     break;
   74       case block_type_proc:
   75     RUBY_MARK_NO_PIN_UNLESS_NULL(block->as.proc);
   76     break;
   77     }
   78 }
   79 
   80 static void
   81 block_compact(struct rb_block *block)
   82 {
   83     switch (block->type) {
   84       case block_type_iseq:
   85       case block_type_ifunc:
   86     {
   87         struct rb_captured_block *captured = &block->as.captured;
   88             captured->self = rb_gc_location(captured->self);
   89             captured->code.val = rb_gc_location(captured->code.val);
   90             if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) {
   91                 UPDATE_REFERENCE(captured->ep[VM_ENV_DATA_INDEX_ENV]);
   92             }
   93     }
   94     break;
   95       case block_type_symbol:
   96         block->as.symbol = rb_gc_location(block->as.symbol);
   97     break;
   98       case block_type_proc:
   99         block->as.proc = rb_gc_location(block->as.proc);
  100     break;
  101     }
  102 }
  103 
  104 static void
  105 proc_compact(void *ptr)
  106 {
  107     rb_proc_t *proc = ptr;
  108     block_compact((struct rb_block *)&proc->block);
  109 }
  110 
  111 static void
  112 proc_mark(void *ptr)
  113 {
  114     rb_proc_t *proc = ptr;
  115     block_mark(&proc->block);
  116     RUBY_MARK_LEAVE("proc");
  117 }
  118 
  119 typedef struct {
  120     rb_proc_t basic;
  121     VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
  122 } cfunc_proc_t;
  123 
  124 static size_t
  125 proc_memsize(const void *ptr)
  126 {
  127     const rb_proc_t *proc = ptr;
  128     if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1)
  129     return sizeof(cfunc_proc_t);
  130     return sizeof(rb_proc_t);
  131 }
  132 
  133 static const rb_data_type_t proc_data_type = {
  134     "proc",
  135     {
  136     proc_mark,
  137     RUBY_TYPED_DEFAULT_FREE,
  138     proc_memsize,
  139     proc_compact,
  140     },
  141     0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
  142 };
  143 
  144 VALUE
  145 rb_proc_alloc(VALUE klass)
  146 {
  147     rb_proc_t *proc;
  148     return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
  149 }
  150 
  151 VALUE
  152 rb_obj_is_proc(VALUE proc)
  153 {
  154     if (rb_typeddata_is_kind_of(proc, &proc_data_type)) {
  155     return Qtrue;
  156     }
  157     else {
  158     return Qfalse;
  159     }
  160 }
  161 
  162 /* :nodoc: */
  163 static VALUE
  164 proc_clone(VALUE self)
  165 {
  166     VALUE procval = rb_proc_dup(self);
  167     CLONESETUP(procval, self);
  168     return procval;
  169 }
  170 
  171 /*
  172  * call-seq:
  173  *   prc.lambda? -> true or false
  174  *
  175  * Returns +true+ if a Proc object is lambda.
  176  * +false+ if non-lambda.
  177  *
  178  * The lambda-ness affects argument handling and the behavior of +return+ and +break+.
  179  *
  180  * A Proc object generated by +proc+ ignores extra arguments.
  181  *
  182  *   proc {|a,b| [a,b] }.call(1,2,3)    #=> [1,2]
  183  *
  184  * It provides +nil+ for missing arguments.
  185  *
  186  *   proc {|a,b| [a,b] }.call(1)        #=> [1,nil]
  187  *
  188  * It expands a single array argument.
  189  *
  190  *   proc {|a,b| [a,b] }.call([1,2])    #=> [1,2]
  191  *
  192  * A Proc object generated by +lambda+ doesn't have such tricks.
  193  *
  194  *   lambda {|a,b| [a,b] }.call(1,2,3)  #=> ArgumentError
  195  *   lambda {|a,b| [a,b] }.call(1)      #=> ArgumentError
  196  *   lambda {|a,b| [a,b] }.call([1,2])  #=> ArgumentError
  197  *
  198  * Proc#lambda? is a predicate for the tricks.
  199  * It returns +true+ if no tricks apply.
  200  *
  201  *   lambda {}.lambda?            #=> true
  202  *   proc {}.lambda?              #=> false
  203  *
  204  * Proc.new is the same as +proc+.
  205  *
  206  *   Proc.new {}.lambda?          #=> false
  207  *
  208  * +lambda+, +proc+ and Proc.new preserve the tricks of
  209  * a Proc object given by <code>&</code> argument.
  210  *
  211  *   lambda(&lambda {}).lambda?   #=> true
  212  *   proc(&lambda {}).lambda?     #=> true
  213  *   Proc.new(&lambda {}).lambda? #=> true
  214  *
  215  *   lambda(&proc {}).lambda?     #=> false
  216  *   proc(&proc {}).lambda?       #=> false
  217  *   Proc.new(&proc {}).lambda?   #=> false
  218  *
  219  * A Proc object generated by <code>&</code> argument has the tricks
  220  *
  221  *   def n(&b) b.lambda? end
  222  *   n {}                         #=> false
  223  *
  224  * The <code>&</code> argument preserves the tricks if a Proc object
  225  * is given by <code>&</code> argument.
  226  *
  227  *   n(&lambda {})                #=> true
  228  *   n(&proc {})                  #=> false
  229  *   n(&Proc.new {})              #=> false
  230  *
  231  * A Proc object converted from a method has no tricks.
  232  *
  233  *   def m() end
  234  *   method(:m).to_proc.lambda?   #=> true
  235  *
  236  *   n(&method(:m))               #=> true
  237  *   n(&method(:m).to_proc)       #=> true
  238  *
  239  * +define_method+ is treated the same as method definition.
  240  * The defined method has no tricks.
  241  *
  242  *   class C
  243  *     define_method(:d) {}
  244  *   end
  245  *   C.new.d(1,2)       #=> ArgumentError
  246  *   C.new.method(:d).to_proc.lambda?   #=> true
  247  *
  248  * +define_method+ always defines a method without the tricks,
  249  * even if a non-lambda Proc object is given.
  250  * This is the only exception for which the tricks are not preserved.
  251  *
  252  *   class C
  253  *     define_method(:e, &proc {})
  254  *   end
  255  *   C.new.e(1,2)       #=> ArgumentError
  256  *   C.new.method(:e).to_proc.lambda?   #=> true
  257  *
  258  * This exception ensures that methods never have tricks
  259  * and makes it easy to have wrappers to define methods that behave as usual.
  260  *
  261  *   class C
  262  *     def self.def2(name, &body)
  263  *       define_method(name, &body)
  264  *     end
  265  *
  266  *     def2(:f) {}
  267  *   end
  268  *   C.new.f(1,2)       #=> ArgumentError
  269  *
  270  * The wrapper <i>def2</i> defines a method which has no tricks.
  271  *
  272  */
  273 
  274 VALUE
  275 rb_proc_lambda_p(VALUE procval)
  276 {
  277     rb_proc_t *proc;
  278     GetProcPtr(procval, proc);
  279 
  280     return proc->is_lambda ? Qtrue : Qfalse;
  281 }
  282 
  283 /* Binding */
  284 
  285 static void
  286 binding_free(void *ptr)
  287 {
  288     RUBY_FREE_ENTER("binding");
  289     ruby_xfree(ptr);
  290     RUBY_FREE_LEAVE("binding");
  291 }
  292 
  293 static void
  294 binding_mark(void *ptr)
  295 {
  296     rb_binding_t *bind = ptr;
  297 
  298     RUBY_MARK_ENTER("binding");
  299     block_mark(&bind->block);
  300     rb_gc_mark_movable(bind->pathobj);
  301     RUBY_MARK_LEAVE("binding");
  302 }
  303 
  304 static void
  305 binding_compact(void *ptr)
  306 {
  307     rb_binding_t *bind = ptr;
  308 
  309     block_compact((struct rb_block *)&bind->block);
  310     UPDATE_REFERENCE(bind->pathobj);
  311 }
  312 
  313 static size_t
  314 binding_memsize(const void *ptr)
  315 {
  316     return sizeof(rb_binding_t);
  317 }
  318 
  319 const rb_data_type_t ruby_binding_data_type = {
  320     "binding",
  321     {
  322     binding_mark,
  323     binding_free,
  324     binding_memsize,
  325     binding_compact,
  326     },
  327     0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
  328 };
  329 
  330 VALUE
  331 rb_binding_alloc(VALUE klass)
  332 {
  333     VALUE obj;
  334     rb_binding_t *bind;
  335     obj = TypedData_Make_Struct(klass, rb_binding_t, &ruby_binding_data_type, bind);
  336     return obj;
  337 }
  338 
  339 
  340 /* :nodoc: */
  341 static VALUE
  342 binding_dup(VALUE self)
  343 {
  344     VALUE bindval = rb_binding_alloc(rb_cBinding);
  345     rb_binding_t *src, *dst;
  346     GetBindingPtr(self, src);
  347     GetBindingPtr(bindval, dst);
  348     rb_vm_block_copy(bindval, &dst->block, &src->block);
  349     RB_OBJ_WRITE(bindval, &dst->pathobj, src->pathobj);
  350     dst->first_lineno = src->first_lineno;
  351     return bindval;
  352 }
  353 
  354 /* :nodoc: */
  355 static VALUE
  356 binding_clone(VALUE self)
  357 {
  358     VALUE bindval = binding_dup(self);
  359     CLONESETUP(bindval, self);
  360     return bindval;
  361 }
  362 
  363 VALUE
  364 rb_binding_new(void)
  365 {
  366     rb_execution_context_t *ec = GET_EC();
  367     return rb_vm_make_binding(ec, ec->cfp);
  368 }
  369 
  370 /*
  371  *  call-seq:
  372  *     binding -> a_binding
  373  *
  374  *  Returns a +Binding+ object, describing the variable and
  375  *  method bindings at the point of call. This object can be used when
  376  *  calling +eval+ to execute the evaluated command in this
  377  *  environment. See also the description of class +Binding+.
  378  *
  379  *     def get_binding(param)
  380  *       binding
  381  *     end
  382  *     b = get_binding("hello")
  383  *     eval("param", b)   #=> "hello"
  384  */
  385 
  386 static VALUE
  387 rb_f_binding(VALUE self)
  388 {
  389     return rb_binding_new();
  390 }
  391 
  392 /*
  393  *  call-seq:
  394  *     binding.eval(string [, filename [,lineno]])  -> obj
  395  *
  396  *  Evaluates the Ruby expression(s) in <em>string</em>, in the
  397  *  <em>binding</em>'s context.  If the optional <em>filename</em> and
  398  *  <em>lineno</em> parameters are present, they will be used when
  399  *  reporting syntax errors.
  400  *
  401  *     def get_binding(param)
  402  *       binding
  403  *     end
  404  *     b = get_binding("hello")
  405  *     b.eval("param")   #=> "hello"
  406  */
  407 
  408 static VALUE
  409 bind_eval(int argc, VALUE *argv, VALUE bindval)
  410 {
  411     VALUE args[4];
  412 
  413     rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
  414     args[1] = bindval;
  415     return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
  416 }
  417 
  418 static const VALUE *
  419 get_local_variable_ptr(const rb_env_t **envp, ID lid)
  420 {
  421     const rb_env_t *env = *envp;
  422     do {
  423     if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) {
  424         const rb_iseq_t *iseq = env->iseq;
  425         unsigned int i;
  426 
  427         VM_ASSERT(rb_obj_is_iseq((VALUE)iseq));
  428 
  429         for (i=0; i<iseq->body->local_table_size; i++) {
  430         if (iseq->body->local_table[i] == lid) {
  431             if (iseq->body->local_iseq == iseq &&
  432             iseq->body->param.flags.has_block &&
  433             (unsigned int)iseq->body->param.block_start == i) {
  434             const VALUE *ep = env->ep;
  435             if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) {
  436                 RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep)));
  437                 VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM);
  438             }
  439             }
  440 
  441             *envp = env;
  442             return &env->env[i];
  443         }
  444         }
  445     }
  446     else {
  447         *envp = NULL;
  448         return NULL;
  449     }
  450     } while ((env = rb_vm_env_prev_env(env)) != NULL);
  451 
  452     *envp = NULL;
  453     return NULL;
  454 }
  455 
  456 /*
  457  * check local variable name.
  458  * returns ID if it's an already interned symbol, or 0 with setting
  459  * local name in String to *namep.
  460  */
  461 static ID
  462 check_local_id(VALUE bindval, volatile VALUE *pname)
  463 {
  464     ID lid = rb_check_id(pname);
  465     VALUE name = *pname;
  466 
  467     if (lid) {
  468     if (!rb_is_local_id(lid)) {
  469         rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
  470                   bindval, ID2SYM(lid));
  471     }
  472     }
  473     else {
  474     if (!rb_is_local_name(name)) {
  475         rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
  476                   bindval, name);
  477     }
  478     return 0;
  479     }
  480     return lid;
  481 }
  482 
  483 /*
  484  *  call-seq:
  485  *     binding.local_variables -> Array
  486  *
  487  *  Returns the names of the binding's local variables as symbols.
  488  *
  489  *  def foo
  490  *        a = 1
  491  *        2.times do |n|
  492  *          binding.local_variables #=> [:a, :n]
  493  *        end
  494  *      end
  495  *
  496  *  This method is the short version of the following code:
  497  *
  498  *  binding.eval("local_variables")
  499  *
  500  */
  501 static VALUE
  502 bind_local_variables(VALUE bindval)
  503 {
  504     const rb_binding_t *bind;
  505     const rb_env_t *env;
  506 
  507     GetBindingPtr(bindval, bind);
  508     env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
  509     return rb_vm_env_local_variables(env);
  510 }
  511 
  512 /*
  513  *  call-seq:
  514  *     binding.local_variable_get(symbol) -> obj
  515  *
  516  *  Returns the value of the local variable +symbol+.
  517  *
  518  *  def foo
  519  *        a = 1
  520  *        binding.local_variable_get(:a) #=> 1
  521  *        binding.local_variable_get(:b) #=> NameError
  522  *      end
  523  *
  524  *  This method is the short version of the following code:
  525  *
  526  *  binding.eval("#{symbol}")
  527  *
  528  */
  529 static VALUE
  530 bind_local_variable_get(VALUE bindval, VALUE sym)
  531 {
  532     ID lid = check_local_id(bindval, &sym);
  533     const rb_binding_t *bind;
  534     const VALUE *ptr;
  535     const rb_env_t *env;
  536 
  537     if (!lid) goto undefined;
  538 
  539     GetBindingPtr(bindval, bind);
  540 
  541     env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
  542     if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) {
  543     sym = ID2SYM(lid);
  544       undefined:
  545     rb_name_err_raise("local variable `%1$s' is not defined for %2$s",
  546               bindval, sym);
  547     }
  548 
  549     return *ptr;
  550 }
  551 
  552 /*
  553  *  call-seq:
  554  *     binding.local_variable_set(symbol, obj) -> obj
  555  *
  556  *  Set local variable named +symbol+ as +obj+.
  557  *
  558  *  def foo
  559  *        a = 1
  560  *        bind = binding
  561  *        bind.local_variable_set(:a, 2) # set existing local variable `a'
  562  *        bind.local_variable_set(:b, 3) # create new local variable `b'
  563  *                                       # `b' exists only in binding
  564  *
  565  *        p bind.local_variable_get(:a)  #=> 2
  566  *        p bind.local_variable_get(:b)  #=> 3
  567  *        p a                            #=> 2
  568  *        p b                            #=> NameError
  569  *      end
  570  *
  571  *  This method behaves similarly to the following code:
  572  *
  573  *    binding.eval("#{symbol} = #{obj}")
  574  *
  575  *  if +obj+ can be dumped in Ruby code.
  576  */
  577 static VALUE
  578 bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
  579 {
  580     ID lid = check_local_id(bindval, &sym);
  581     rb_binding_t *bind;
  582     const VALUE *ptr;
  583     const rb_env_t *env;
  584 
  585     if (!lid) lid = rb_intern_str(sym);
  586 
  587     GetBindingPtr(bindval, bind);
  588     env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
  589     if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) {
  590     /* not found. create new env */
  591     ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
  592     env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
  593     }
  594 
  595     RB_OBJ_WRITE(env, ptr, val);
  596 
  597     return val;
  598 }
  599 
  600 /*
  601  *  call-seq:
  602  *     binding.local_variable_defined?(symbol) -> obj
  603  *
  604  *  Returns +true+ if a local variable +symbol+ exists.
  605  *
  606  *  def foo
  607  *        a = 1
  608  *        binding.local_variable_defined?(:a) #=> true
  609  *        binding.local_variable_defined?(:b) #=> false
  610  *      end
  611  *
  612  *  This method is the short version of the following code:
  613  *
  614  *  binding.eval("defined?(#{symbol}) == 'local-variable'")
  615  *
  616  */
  617 static VALUE
  618 bind_local_variable_defined_p(VALUE bindval, VALUE sym)
  619 {
  620     ID lid = check_local_id(bindval, &sym);
  621     const rb_binding_t *bind;
  622     const rb_env_t *env;
  623 
  624     if (!lid) return Qfalse;
  625 
  626     GetBindingPtr(bindval, bind);
  627     env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
  628     return get_local_variable_ptr(&env, lid) ? Qtrue : Qfalse;
  629 }
  630 
  631 /*
  632  *  call-seq:
  633  *     binding.receiver    -> object
  634  *
  635  *  Returns the bound receiver of the binding object.
  636  */
  637 static VALUE
  638 bind_receiver(VALUE bindval)
  639 {
  640     const rb_binding_t *bind;
  641     GetBindingPtr(bindval, bind);
  642     return vm_block_self(&bind->block);
  643 }
  644 
  645 /*
  646  *  call-seq:
  647  *     binding.source_location  -> [String, Integer]
  648  *
  649  *  Returns the Ruby source filename and line number of the binding object.
  650  */
  651 static VALUE
  652 bind_location(VALUE bindval)
  653 {
  654     VALUE loc[2];
  655     const rb_binding_t *bind;
  656     GetBindingPtr(bindval, bind);
  657     loc[0] = pathobj_path(bind->pathobj);
  658     loc[1] = INT2FIX(bind->first_lineno);
  659 
  660     return rb_ary_new4(2, loc);
  661 }
  662 
  663 static VALUE
  664 cfunc_proc_new(VALUE klass, VALUE ifunc, int8_t is_lambda)
  665 {
  666     rb_proc_t *proc;
  667     cfunc_proc_t *sproc;
  668     VALUE procval = TypedData_Make_Struct(klass, cfunc_proc_t, &proc_data_type, sproc);
  669     VALUE *ep;
  670 
  671     proc = &sproc->basic;
  672     vm_block_type_set(&proc->block, block_type_ifunc);
  673 
  674     *(VALUE **)&proc->block.as.captured.ep = ep = sproc->env + VM_ENV_DATA_SIZE-1;
  675     ep[VM_ENV_DATA_INDEX_FLAGS]   = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL | VM_ENV_FLAG_ESCAPED;
  676     ep[VM_ENV_DATA_INDEX_ME_CREF] = Qfalse;
  677     ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
  678     ep[VM_ENV_DATA_INDEX_ENV]     = Qundef; /* envval */
  679 
  680     /* self? */
  681     RB_OBJ_WRITE(procval, &proc->block.as.captured.code.ifunc, ifunc);
  682     proc->is_lambda = is_lambda;
  683     return procval;
  684 }
  685 
  686 static VALUE
  687 sym_proc_new(VALUE klass, VALUE sym)
  688 {
  689     VALUE procval = rb_proc_alloc(klass);
  690     rb_proc_t *proc;
  691     GetProcPtr(procval, proc);
  692 
  693     vm_block_type_set(&proc->block, block_type_symbol);
  694     RB_OBJ_WRITE(procval, &proc->block.as.symbol, sym);
  695     return procval;
  696 }
  697 
  698 struct vm_ifunc *
  699 rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc)
  700 {
  701     union {
  702     struct vm_ifunc_argc argc;
  703     VALUE packed;
  704     } arity;
  705 
  706     if (min_argc < UNLIMITED_ARGUMENTS ||
  707 #if SIZEOF_INT * 2 > SIZEOF_VALUE
  708     min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
  709 #endif
  710     0) {
  711     rb_raise(rb_eRangeError, "minimum argument number out of range: %d",
  712          min_argc);
  713     }
  714     if (max_argc < UNLIMITED_ARGUMENTS ||
  715 #if SIZEOF_INT * 2 > SIZEOF_VALUE
  716     max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
  717 #endif
  718     0) {
  719     rb_raise(rb_eRangeError, "maximum argument number out of range: %d",
  720          max_argc);
  721     }
  722     arity.argc.min = min_argc;
  723     arity.argc.max = max_argc;
  724     return IFUNC_NEW(func, data, arity.packed);
  725 }
  726 
  727 MJIT_FUNC_EXPORTED VALUE
  728 rb_func_proc_new(rb_block_call_func_t func, VALUE val)
  729 {
  730     struct vm_ifunc *ifunc = rb_vm_ifunc_proc_new(func, (void *)val);
  731     return cfunc_proc_new(rb_cProc, (VALUE)ifunc, 0);
  732 }
  733 
  734 VALUE
  735 rb_func_lambda_new(rb_block_call_func_t func, VALUE val, int min_argc, int max_argc)
  736 {
  737     struct vm_ifunc *ifunc = rb_vm_ifunc_new(func, (void *)val, min_argc, max_argc);
  738     return cfunc_proc_new(rb_cProc, (VALUE)ifunc, 1);
  739 }
  740 
  741 static const char proc_without_block[] = "tried to create Proc object without a block";
  742 
  743 static VALUE
  744 proc_new(VALUE klass, int8_t is_lambda, int8_t kernel)
  745 {
  746     VALUE procval;
  747     const rb_execution_context_t *ec = GET_EC();
  748     rb_control_frame_t *cfp = ec->cfp;
  749     VALUE block_handler;
  750 
  751     if ((block_handler = rb_vm_frame_block_handler(cfp)) == VM_BLOCK_HANDLER_NONE) {
  752 #if !PROC_NEW_REQUIRES_BLOCK
  753     cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
  754 
  755     if ((block_handler = rb_vm_frame_block_handler(cfp)) != VM_BLOCK_HANDLER_NONE) {
  756         if (is_lambda) {
  757                 rb_raise(rb_eArgError, proc_without_block);
  758             }
  759             else {
  760                 const char *name = kernel ? "Kernel#proc" : "Proc.new";
  761                 rb_warn_deprecated("Capturing the given block using %s",
  762                                    "`&block`", name);
  763         }
  764     }
  765 #else
  766     if (0);
  767 #endif
  768     else {
  769         rb_raise(rb_eArgError, proc_without_block);
  770     }
  771     }
  772 
  773     /* block is in cf */
  774     switch (vm_block_handler_type(block_handler)) {
  775       case block_handler_type_proc:
  776     procval = VM_BH_TO_PROC(block_handler);
  777 
  778     if (RBASIC_CLASS(procval) == klass) {
  779         return procval;
  780     }
  781     else {
  782         VALUE newprocval = rb_proc_dup(procval);
  783             RBASIC_SET_CLASS(newprocval, klass);
  784         return newprocval;
  785     }
  786     break;
  787 
  788       case block_handler_type_symbol:
  789     return (klass != rb_cProc) ?
  790       sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) :
  791       rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
  792     break;
  793 
  794       case block_handler_type_ifunc:
  795     return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda);
  796       case block_handler_type_iseq:
  797         {
  798             const struct rb_captured_block *captured = VM_BH_TO_CAPT_BLOCK(block_handler);
  799             rb_control_frame_t *last_ruby_cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
  800             if (is_lambda && last_ruby_cfp && vm_cfp_forwarded_bh_p(last_ruby_cfp, block_handler)) {
  801                 is_lambda = false;
  802             }
  803             return rb_vm_make_proc_lambda(ec, captured, klass, is_lambda);
  804         }
  805     }
  806     VM_UNREACHABLE(proc_new);
  807     return Qnil;
  808 }
  809 
  810 /*
  811  *  call-seq:
  812  *     Proc.new {|...| block } -> a_proc
  813  *     Proc.new                -> a_proc
  814  *
  815  *  Creates a new Proc object, bound to the current context. Proc::new
  816  *  may be called without a block only within a method with an
  817  *  attached block, in which case that block is converted to the Proc
  818  *  object.
  819  *
  820  *     def proc_from
  821  *       Proc.new
  822  *     end
  823  *     proc = proc_from { "hello" }
  824  *     proc.call   #=> "hello"
  825  */
  826 
  827 static VALUE
  828 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
  829 {
  830     VALUE block = proc_new(klass, FALSE, FALSE);
  831 
  832     rb_obj_call_init_kw(block, argc, argv, RB_PASS_CALLED_KEYWORDS);
  833     return block;
  834 }
  835 
  836 VALUE
  837 rb_block_proc(void)
  838 {
  839     return proc_new(rb_cProc, FALSE, FALSE);
  840 }
  841 
  842 /*
  843  * call-seq:
  844  *   proc   { |...| block }  -> a_proc
  845  *
  846  * Equivalent to Proc.new.
  847  */
  848 
  849 static VALUE
  850 f_proc(VALUE _)
  851 {
  852     return proc_new(rb_cProc, FALSE, TRUE);
  853 }
  854 
  855 VALUE
  856 rb_block_lambda(void)
  857 {
  858     return proc_new(rb_cProc, TRUE, FALSE);
  859 }
  860 
  861 /*
  862  * call-seq:
  863  *   lambda { |...| block }  -> a_proc
  864  *
  865  * Equivalent to Proc.new, except the resulting Proc objects check the
  866  * number of parameters passed when called.
  867  */
  868 
  869 static VALUE
  870 f_lambda(VALUE _)
  871 {
  872     return rb_block_lambda();
  873 }
  874 
  875 /*  Document-method: Proc#===
  876  *
  877  *  call-seq:
  878  *     proc === obj   -> result_of_proc
  879  *
  880  *  Invokes the block with +obj+ as the proc's parameter like Proc#call.
  881  *  This allows a proc object to be the target of a +when+ clause
  882  *  in a case statement.
  883  */
  884 
  885 /* CHECKME: are the argument checking semantics correct? */
  886 
  887 /*
  888  *  Document-method: Proc#[]
  889  *  Document-method: Proc#call
  890  *  Document-method: Proc#yield
  891  *
  892  *  call-seq:
  893  *     prc.call(params,...)   -> obj
  894  *     prc[params,...]        -> obj
  895  *     prc.(params,...)       -> obj
  896  *     prc.yield(params,...)  -> obj
  897  *
  898  *  Invokes the block, setting the block's parameters to the values in
  899  *  <i>params</i> using something close to method calling semantics.
  900  *  Returns the value of the last expression evaluated in the block.
  901  *
  902  *     a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
  903  *     a_proc.call(9, 1, 2, 3)    #=> [9, 18, 27]
  904  *     a_proc[9, 1, 2, 3]         #=> [9, 18, 27]
  905  *     a_proc.(9, 1, 2, 3)        #=> [9, 18, 27]
  906  *     a_proc.yield(9, 1, 2, 3)   #=> [9, 18, 27]
  907  *
  908  *  Note that <code>prc.()</code> invokes <code>prc.call()</code> with
  909  *  the parameters given.  It's syntactic sugar to hide "call".
  910  *
  911  *  For procs created using #lambda or <code>->()</code> an error is
  912  *  generated if the wrong number of parameters are passed to the
  913  *  proc.  For procs created using Proc.new or Kernel.proc, extra
  914  *  parameters are silently discarded and missing parameters are set
  915  *  to +nil+.
  916  *
  917  *     a_proc = proc {|a,b| [a,b] }
  918  *     a_proc.call(1)   #=> [1, nil]
  919  *
  920  *     a_proc = lambda {|a,b| [a,b] }
  921  *     a_proc.call(1)   # ArgumentError: wrong number of arguments (given 1, expected 2)
  922  *
  923  *  See also Proc#lambda?.
  924  */
  925 #if 0
  926 static VALUE
  927 proc_call(int argc, VALUE *argv, VALUE procval)
  928 {
  929     /* removed */
  930 }
  931 #endif
  932 
  933 #if SIZEOF_LONG > SIZEOF_INT
  934 static inline int
  935 check_argc(long argc)
  936 {
  937     if (argc > INT_MAX || argc < 0) {
  938     rb_raise(rb_eArgError, "too many arguments (%lu)",
  939          (unsigned long)argc);
  940     }
  941     return (int)argc;
  942 }
  943 #else
  944 #define check_argc(argc) (argc)
  945 #endif
  946 
  947 VALUE
  948 rb_proc_call_kw(VALUE self, VALUE args, int kw_splat)
  949 {
  950     VALUE vret;
  951     rb_proc_t *proc;
  952     VALUE v;
  953     int argc = check_argc(RARRAY_LEN(args));
  954     const VALUE *argv = RARRAY_CONST_PTR(args);
  955     GetProcPtr(self, proc);
  956     v = rb_adjust_argv_kw_splat(&argc, &argv, &kw_splat);
  957     vret = rb_vm_invoke_proc(GET_EC(), proc, argc, argv,
  958                              kw_splat, VM_BLOCK_HANDLER_NONE);
  959     rb_free_tmp_buffer(&v);
  960     RB_GC_GUARD(self);
  961     RB_GC_GUARD(args);
  962     return vret;
  963 }
  964 
  965 VALUE
  966 rb_proc_call(VALUE self, VALUE args)
  967 {
  968     VALUE vret;
  969     rb_proc_t *proc;
  970     GetProcPtr(self, proc);
  971     vret = rb_vm_invoke_proc(GET_EC(), proc,
  972                  check_argc(RARRAY_LEN(args)), RARRAY_CONST_PTR(args),
  973                              RB_NO_KEYWORDS, VM_BLOCK_HANDLER_NONE);
  974     RB_GC_GUARD(self);
  975     RB_GC_GUARD(args);
  976     return vret;
  977 }
  978 
  979 static VALUE
  980 proc_to_block_handler(VALUE procval)
  981 {
  982     return NIL_P(procval) ? VM_BLOCK_HANDLER_NONE : procval;
  983 }
  984 
  985 VALUE
  986 rb_proc_call_with_block_kw(VALUE self, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
  987 {
  988     rb_execution_context_t *ec = GET_EC();
  989     VALUE vret;
  990     rb_proc_t *proc;
  991     VALUE v = rb_adjust_argv_kw_splat(&argc, &argv, &kw_splat);
  992     GetProcPtr(self, proc);
  993     vret = rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, proc_to_block_handler(passed_procval));
  994     rb_free_tmp_buffer(&v);
  995     RB_GC_GUARD(self);
  996     return vret;
  997 }
  998 
  999 VALUE
 1000 rb_proc_call_with_block(VALUE self, int argc, const VALUE *argv, VALUE passed_procval)
 1001 {
 1002     rb_execution_context_t *ec = GET_EC();
 1003     VALUE vret;
 1004     rb_proc_t *proc;
 1005     GetProcPtr(self, proc);
 1006     vret = rb_vm_invoke_proc(ec, proc, argc, argv, RB_NO_KEYWORDS, proc_to_block_handler(passed_procval));
 1007     RB_GC_GUARD(self);
 1008     return vret;
 1009 }
 1010 
 1011 
 1012 /*
 1013  *  call-seq:
 1014  *     prc.arity -> integer
 1015  *
 1016  *  Returns the number of mandatory arguments. If the block
 1017  *  is declared to take no arguments, returns 0. If the block is known
 1018  *  to take exactly n arguments, returns n.
 1019  *  If the block has optional arguments, returns -n-1, where n is the
 1020  *  number of mandatory arguments, with the exception for blocks that
 1021  *  are not lambdas and have only a finite number of optional arguments;
 1022  *  in this latter case, returns n.
 1023  *  Keyword arguments will be considered as a single additional argument,
 1024  *  that argument being mandatory if any keyword argument is mandatory.
 1025  *  A #proc with no argument declarations is the same as a block
 1026  *  declaring <code>||</code> as its arguments.
 1027  *
 1028  *     proc {}.arity                  #=>  0
 1029  *     proc { || }.arity              #=>  0
 1030  *     proc { |a| }.arity             #=>  1
 1031  *     proc { |a, b| }.arity          #=>  2
 1032  *     proc { |a, b, c| }.arity       #=>  3
 1033  *     proc { |*a| }.arity            #=> -1
 1034  *     proc { |a, *b| }.arity         #=> -2
 1035  *     proc { |a, *b, c| }.arity      #=> -3
 1036  *     proc { |x:, y:, z:0| }.arity   #=>  1
 1037  *     proc { |*a, x:, y:0| }.arity   #=> -2
 1038  *
 1039  *     proc   { |a=0| }.arity         #=>  0
 1040  *     lambda { |a=0| }.arity         #=> -1
 1041  *     proc   { |a=0, b| }.arity      #=>  1
 1042  *     lambda { |a=0, b| }.arity      #=> -2
 1043  *     proc   { |a=0, b=0| }.arity    #=>  0
 1044  *     lambda { |a=0, b=0| }.arity    #=> -1
 1045  *     proc   { |a, b=0| }.arity      #=>  1
 1046  *     lambda { |a, b=0| }.arity      #=> -2
 1047  *     proc   { |(a, b), c=0| }.arity #=>  1
 1048  *     lambda { |(a, b), c=0| }.arity #=> -2
 1049  *     proc   { |a, x:0, y:0| }.arity #=>  1
 1050  *     lambda { |a, x:0, y:0| }.arity #=> -2
 1051  */
 1052 
 1053 static VALUE
 1054 proc_arity(VALUE self)
 1055 {
 1056     int arity = rb_proc_arity(self);
 1057     return INT2FIX(arity);
 1058 }
 1059 
 1060 static inline int
 1061 rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
 1062 {
 1063     *max = iseq->body->param.flags.has_rest == FALSE ?
 1064       iseq->body->param.lead_num + iseq->body->param.opt_num + iseq->body->param.post_num +
 1065       (iseq->body->param.flags.has_kw == TRUE || iseq->body->param.flags.has_kwrest == TRUE)
 1066       : UNLIMITED_ARGUMENTS;
 1067     return iseq->body->param.lead_num + iseq->body->param.post_num + (iseq->body->param.flags.has_kw && iseq->body->param.keyword->required_num > 0);
 1068 }
 1069 
 1070 static int
 1071 rb_vm_block_min_max_arity(const struct rb_block *block, int *max)
 1072 {
 1073   again:
 1074     switch (vm_block_type(block)) {
 1075       case block_type_iseq:
 1076     return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max);
 1077       case block_type_proc:
 1078     block = vm_proc_block(block->as.proc);
 1079     goto again;
 1080       case block_type_ifunc:
 1081     {
 1082         const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
 1083         if (IS_METHOD_PROC_IFUNC(ifunc)) {
 1084         /* e.g. method(:foo).to_proc.arity */
 1085         return method_min_max_arity((VALUE)ifunc->data, max);
 1086         }
 1087         *max = ifunc->argc.max;
 1088         return ifunc->argc.min;
 1089     }
 1090       case block_type_symbol:
 1091     break;
 1092     }
 1093     *max = UNLIMITED_ARGUMENTS;
 1094     return 0;
 1095 }
 1096 
 1097 /*
 1098  * Returns the number of required parameters and stores the maximum
 1099  * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
 1100  * For non-lambda procs, the maximum is the number of non-ignored
 1101  * parameters even though there is no actual limit to the number of parameters
 1102  */
 1103 static int
 1104 rb_proc_min_max_arity(VALUE self, int *max)
 1105 {
 1106     rb_proc_t *proc;
 1107     GetProcPtr(self, proc);
 1108     return rb_vm_block_min_max_arity(&proc->block, max);
 1109 }
 1110 
 1111 int
 1112 rb_proc_arity(VALUE self)
 1113 {
 1114     rb_proc_t *proc;
 1115     int max, min;
 1116     GetProcPtr(self, proc);
 1117     min = rb_vm_block_min_max_arity(&proc->block, &max);
 1118     return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
 1119 }
 1120 
 1121 static void
 1122 block_setup(struct rb_block *block, VALUE block_handler)
 1123 {
 1124     switch (vm_block_handler_type(block_handler)) {
 1125       case block_handler_type_iseq:
 1126     block->type = block_type_iseq;
 1127     block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler);
 1128     break;
 1129       case block_handler_type_ifunc:
 1130     block->type = block_type_ifunc;
 1131     block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler);
 1132     break;
 1133       case block_handler_type_symbol:
 1134     block->type = block_type_symbol;
 1135     block->as.symbol = VM_BH_TO_SYMBOL(block_handler);
 1136     break;
 1137       case block_handler_type_proc:
 1138     block->type = block_type_proc;
 1139     block->as.proc = VM_BH_TO_PROC(block_handler);
 1140     }
 1141 }
 1142 
 1143 int
 1144 rb_block_arity(void)
 1145 {
 1146     int min, max;
 1147     const rb_execution_context_t *ec = GET_EC();
 1148     rb_control_frame_t *cfp = ec->cfp;
 1149     VALUE block_handler = rb_vm_frame_block_handler(cfp);
 1150     struct rb_block block;
 1151 
 1152     if (block_handler == VM_BLOCK_HANDLER_NONE) {
 1153     rb_raise(rb_eArgError, "no block given");
 1154     }
 1155 
 1156     block_setup(&block, block_handler);
 1157     min = rb_vm_block_min_max_arity(&block, &max);
 1158 
 1159     switch (vm_block_type(&block)) {
 1160       case block_handler_type_symbol:
 1161     return -1;
 1162 
 1163       case block_handler_type_proc:
 1164     {
 1165         VALUE procval = block_handler;
 1166         rb_proc_t *proc;
 1167         GetProcPtr(procval, proc);
 1168         return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
 1169         /* fall through */
 1170     }
 1171 
 1172       default:
 1173     return max != UNLIMITED_ARGUMENTS ? min : -min-1;
 1174     }
 1175 }
 1176 
 1177 int
 1178 rb_block_min_max_arity(int *max)
 1179 {
 1180     const rb_execution_context_t *ec = GET_EC();
 1181     rb_control_frame_t *cfp = ec->cfp;
 1182     VALUE block_handler = rb_vm_frame_block_handler(cfp);
 1183     struct rb_block block;
 1184 
 1185     if (block_handler == VM_BLOCK_HANDLER_NONE) {
 1186     rb_raise(rb_eArgError, "no block given");
 1187     }
 1188 
 1189     block_setup(&block, block_handler);
 1190     return rb_vm_block_min_max_arity(&block, max);
 1191 }
 1192 
 1193 const rb_iseq_t *
 1194 rb_proc_get_iseq(VALUE self, int *is_proc)
 1195 {
 1196     const rb_proc_t *proc;
 1197     const struct rb_block *block;
 1198 
 1199     GetProcPtr(self, proc);
 1200     block = &proc->block;
 1201     if (is_proc) *is_proc = !proc->is_lambda;
 1202 
 1203     switch (vm_block_type(block)) {
 1204       case block_type_iseq:
 1205     return rb_iseq_check(block->as.captured.code.iseq);
 1206       case block_type_proc:
 1207     return rb_proc_get_iseq(block->as.proc, is_proc);
 1208       case block_type_ifunc:
 1209     {
 1210         const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
 1211         if (IS_METHOD_PROC_IFUNC(ifunc)) {
 1212         /* method(:foo).to_proc */
 1213         if (is_proc) *is_proc = 0;
 1214         return rb_method_iseq((VALUE)ifunc->data);
 1215         }
 1216         else {
 1217         return NULL;
 1218         }
 1219     }
 1220       case block_type_symbol:
 1221     return NULL;
 1222     }
 1223 
 1224     VM_UNREACHABLE(rb_proc_get_iseq);
 1225     return NULL;
 1226 }
 1227 
 1228 static VALUE
 1229 iseq_location(const rb_iseq_t *iseq)
 1230 {
 1231     VALUE loc[2];
 1232 
 1233     if (!iseq) return Qnil;
 1234     rb_iseq_check(iseq);
 1235     loc[0] = rb_iseq_path(iseq);
 1236     loc[1] = iseq->body->location.first_lineno;
 1237 
 1238     return rb_ary_new4(2, loc);
 1239 }
 1240 
 1241 MJIT_FUNC_EXPORTED VALUE
 1242 rb_iseq_location(const rb_iseq_t *iseq)
 1243 {
 1244     return iseq_location(iseq);
 1245 }
 1246 
 1247 /*
 1248  * call-seq:
 1249  *    prc.source_location  -> [String, Integer]
 1250  *
 1251  * Returns the Ruby source filename and line number containing this proc
 1252  * or +nil+ if this proc was not defined in Ruby (i.e. native).
 1253  */
 1254 
 1255 VALUE
 1256 rb_proc_location(VALUE self)
 1257 {
 1258     return iseq_location(rb_proc_get_iseq(self, 0));
 1259 }
 1260 
 1261 VALUE
 1262 rb_unnamed_parameters(int arity)
 1263 {
 1264     VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
 1265     int n = (arity < 0) ? ~arity : arity;
 1266     ID req, rest;
 1267     CONST_ID(req, "req");
 1268     a = rb_ary_new3(1, ID2SYM(req));
 1269     OBJ_FREEZE(a);
 1270     for (; n; --n) {
 1271     rb_ary_push(param, a);
 1272     }
 1273     if (arity < 0) {
 1274     CONST_ID(rest, "rest");
 1275     rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
 1276     }
 1277     return param;
 1278 }
 1279 
 1280 /*
 1281  * call-seq:
 1282  *    prc.parameters  -> array
 1283  *
 1284  * Returns the parameter information of this proc.
 1285  *
 1286  *    prc = lambda{|x, y=42, *other|}
 1287  *    prc.parameters  #=> [[:req, :x], [:opt, :y], [:rest, :other]]
 1288  */
 1289 
 1290 static VALUE
 1291 rb_proc_parameters(VALUE self)
 1292 {
 1293     int is_proc;
 1294     const rb_iseq_t *iseq = rb_proc_get_iseq(self, &is_proc);
 1295     if (!iseq) {
 1296     return rb_unnamed_parameters(rb_proc_arity(self));
 1297     }
 1298     return rb_iseq_parameters(iseq, is_proc);
 1299 }
 1300 
 1301 st_index_t
 1302 rb_hash_proc(st_index_t hash, VALUE prc)
 1303 {
 1304     rb_proc_t *proc;
 1305     GetProcPtr(prc, proc);
 1306     hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.code.val);
 1307     hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.self);
 1308     return rb_hash_uint(hash, (st_index_t)proc->block.as.captured.ep >> 16);
 1309 }
 1310 
 1311 MJIT_FUNC_EXPORTED VALUE
 1312 rb_sym_to_proc(VALUE sym)
 1313 {
 1314     static VALUE sym_proc_cache = Qfalse;
 1315     enum {SYM_PROC_CACHE_SIZE = 67};
 1316     VALUE proc;
 1317     long index;
 1318     ID id;
 1319 
 1320     if (!sym_proc_cache) {
 1321     sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2);
 1322     rb_gc_register_mark_object(sym_proc_cache);
 1323     rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil);
 1324     }
 1325 
 1326     id = SYM2ID(sym);
 1327     index = (id % SYM_PROC_CACHE_SIZE) << 1;
 1328 
 1329     if (RARRAY_AREF(sym_proc_cache, index) == sym) {
 1330         return RARRAY_AREF(sym_proc_cache, index + 1);
 1331     }
 1332     else {
 1333         proc = sym_proc_new(rb_cProc, ID2SYM(id));
 1334         RARRAY_ASET(sym_proc_cache, index, sym);
 1335         RARRAY_ASET(sym_proc_cache, index + 1, proc);
 1336     return proc;
 1337     }
 1338 }
 1339 
 1340 /*
 1341  * call-seq:
 1342  *   prc.hash   ->  integer
 1343  *
 1344  * Returns a hash value corresponding to proc body.
 1345  *
 1346  * See also Object#hash.
 1347  */
 1348 
 1349 static VALUE
 1350 proc_hash(VALUE self)
 1351 {
 1352     st_index_t hash;
 1353     hash = rb_hash_start(0);
 1354     hash = rb_hash_proc(hash, self);
 1355     hash = rb_hash_end(hash);
 1356     return ST2FIX(hash);
 1357 }
 1358 
 1359 VALUE
 1360 rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
 1361 {
 1362     VALUE cname = rb_obj_class(self);
 1363     VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
 1364 
 1365   again:
 1366     switch (vm_block_type(block)) {
 1367       case block_type_proc:
 1368     block = vm_proc_block(block->as.proc);
 1369     goto again;
 1370       case block_type_iseq:
 1371     {
 1372         const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
 1373             rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
 1374             rb_iseq_path(iseq),
 1375             FIX2INT(iseq->body->location.first_lineno));
 1376     }
 1377     break;
 1378       case block_type_symbol:
 1379     rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
 1380     break;
 1381       case block_type_ifunc:
 1382     rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
 1383     break;
 1384     }
 1385 
 1386     if (additional_info) rb_str_cat_cstr(str, additional_info);
 1387     rb_str_cat_cstr(str, ">");
 1388     return str;
 1389 }
 1390 
 1391 /*
 1392  * call-seq:
 1393  *   prc.to_s   -> string
 1394  *
 1395  * Returns the unique identifier for this proc, along with
 1396  * an indication of where the proc was defined.
 1397  */
 1398 
 1399 static VALUE
 1400 proc_to_s(VALUE self)
 1401 {
 1402     const rb_proc_t *proc;
 1403     GetProcPtr(self, proc);
 1404     return rb_block_to_s(self, &proc->block, proc->is_lambda ? " (lambda)" : NULL);
 1405 }
 1406 
 1407 /*
 1408  *  call-seq:
 1409  *     prc.to_proc -> proc
 1410  *
 1411  *  Part of the protocol for converting objects to Proc objects.
 1412  *  Instances of class Proc simply return themselves.
 1413  */
 1414 
 1415 static VALUE
 1416 proc_to_proc(VALUE self)
 1417 {
 1418     return self;
 1419 }
 1420 
 1421 static void
 1422 bm_mark(void *ptr)
 1423 {
 1424     struct METHOD *data = ptr;
 1425     rb_gc_mark_movable(data->recv);
 1426     rb_gc_mark_movable(data->klass);
 1427     rb_gc_mark_movable(data->iclass);
 1428     rb_gc_mark_movable((VALUE)data->me);
 1429 }
 1430 
 1431 static void
 1432 bm_compact(void *ptr)
 1433 {
 1434     struct METHOD *data = ptr;
 1435     UPDATE_REFERENCE(data->recv);
 1436     UPDATE_REFERENCE(data->klass);
 1437     UPDATE_REFERENCE(data->iclass);
 1438     UPDATE_TYPED_REFERENCE(rb_method_entry_t *, data->me);
 1439 }
 1440 
 1441 static size_t
 1442 bm_memsize(const void *ptr)
 1443 {
 1444     return sizeof(struct METHOD);
 1445 }
 1446 
 1447 static const rb_data_type_t method_data_type = {
 1448     "method",
 1449     {
 1450     bm_mark,
 1451     RUBY_TYPED_DEFAULT_FREE,
 1452     bm_memsize,
 1453     bm_compact,
 1454     },
 1455     0, 0, RUBY_TYPED_FREE_IMMEDIATELY
 1456 };
 1457 
 1458 VALUE
 1459 rb_obj_is_method(VALUE m)
 1460 {
 1461     if (rb_typeddata_is_kind_of(m, &method_data_type)) {
 1462     return Qtrue;
 1463     }
 1464     else {
 1465     return Qfalse;
 1466     }
 1467 }
 1468 
 1469 static int
 1470 respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
 1471 {
 1472     /* TODO: merge with obj_respond_to() */
 1473     ID rmiss = idRespond_to_missing;
 1474 
 1475     if (obj == Qundef) return 0;
 1476     if (rb_method_basic_definition_p(klass, rmiss)) return 0;
 1477     return RTEST(rb_funcall(obj, rmiss, 2, sym, scope ? Qfalse : Qtrue));
 1478 }
 1479 
 1480 
 1481 static VALUE
 1482 mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
 1483 {
 1484     struct METHOD *data;
 1485     VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
 1486     rb_method_entry_t *me;
 1487     rb_method_definition_t *def;
 1488 
 1489     RB_OBJ_WRITE(method, &data->recv, obj);
 1490     RB_OBJ_WRITE(method, &data->klass, klass);
 1491 
 1492     def = ZALLOC(rb_method_definition_t);
 1493     def->type = VM_METHOD_TYPE_MISSING;
 1494     def->original_id = id;
 1495 
 1496     me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
 1497 
 1498     RB_OBJ_WRITE(method, &data->me, me);
 1499 
 1500     return method;
 1501 }
 1502 
 1503 static VALUE
 1504 mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
 1505 {
 1506     VALUE vid = rb_str_intern(*name);
 1507     *name = vid;
 1508     if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
 1509     return mnew_missing(klass, obj, SYM2ID(vid), mclass);
 1510 }
 1511 
 1512 static VALUE
 1513 mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
 1514           VALUE obj, ID id, VALUE mclass, int scope, int error)
 1515 {
 1516     struct METHOD *data;
 1517     VALUE method;
 1518     rb_method_visibility_t visi = METHOD_VISI_UNDEF;
 1519 
 1520   again:
 1521     if (UNDEFINED_METHOD_ENTRY_P(me)) {
 1522     if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
 1523         return mnew_missing(klass, obj, id, mclass);
 1524     }
 1525     if (!error) return Qnil;
 1526     rb_print_undef(klass, id, METHOD_VISI_UNDEF);
 1527     }
 1528     if (visi == METHOD_VISI_UNDEF) {
 1529     visi = METHOD_ENTRY_VISI(me);
 1530     if (scope && (visi != METHOD_VISI_PUBLIC)) {
 1531         if (!error) return Qnil;
 1532         rb_print_inaccessible(klass, id, visi);
 1533     }
 1534     }
 1535     if (me->def->type == VM_METHOD_TYPE_ZSUPER) {
 1536     if (me->defined_class) {
 1537         VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
 1538         id = me->def->original_id;
 1539             me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
 1540     }
 1541     else {
 1542         VALUE klass = RCLASS_SUPER(me->owner);
 1543         id = me->def->original_id;
 1544         me = rb_method_entry_without_refinements(klass, id, &iclass);
 1545     }
 1546     goto again;
 1547     }
 1548 
 1549     method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
 1550 
 1551     RB_OBJ_WRITE(method, &data->recv, obj);
 1552     RB_OBJ_WRITE(method, &data->klass, klass);
 1553     RB_OBJ_WRITE(method, &data->iclass, iclass);
 1554     RB_OBJ_WRITE(method, &data->me, me);
 1555 
 1556     return method;
 1557 }
 1558 
 1559 static VALUE
 1560 mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
 1561          VALUE obj, ID id, VALUE mclass, int scope)
 1562 {
 1563     return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
 1564 }
 1565 
 1566 static VALUE
 1567 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
 1568 {
 1569     const rb_method_entry_t *me;
 1570     VALUE iclass = Qnil;
 1571 
 1572     if (obj == Qundef) { /* UnboundMethod */
 1573         me = rb_method_entry_with_refinements(klass, id, &iclass);
 1574     }
 1575     else {
 1576         me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
 1577     }
 1578     return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
 1579 }
 1580 
 1581 static inline VALUE
 1582 method_entry_defined_class(const rb_method_entry_t *me)
 1583 {
 1584     VALUE defined_class = me->defined_class;
 1585     return defined_class ? defined_class : me->owner;
 1586 }
 1587 
 1588 /**********************************************************************
 1589  *
 1590  * Document-class: Method
 1591  *
 1592  *  Method objects are created by Object#method, and are associated
 1593  *  with a particular object (not just with a class).  They may be
 1594  *  used to invoke the method within the object, and as a block
 1595  *  associated with an iterator.  They may also be unbound from one
 1596  *  object (creating an UnboundMethod) and bound to another.
 1597  *
 1598  *     class Thing
 1599  *       def square(n)
 1600  *         n*n
 1601  *       end
 1602  *     end
 1603  *     thing = Thing.new
 1604  *     meth  = thing.method(:square)
 1605  *
 1606  *     meth.call(9)                 #=> 81
 1607  *     [ 1, 2, 3 ].collect(&meth)   #=> [1, 4, 9]
 1608  *
 1609  *     [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
 1610  *
 1611  *     require 'date'
 1612  *     %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
 1613  *     #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
 1614  */
 1615 
 1616 /*
 1617  * call-seq:
 1618  *   meth.eql?(other_meth)  -> true or false
 1619  *   meth == other_meth  -> true or false
 1620  *
 1621  * Two method objects are equal if they are bound to the same
 1622  * object and refer to the same method definition and their owners are the
 1623  * same class or module.
 1624  */
 1625 
 1626 static VALUE
 1627 method_eq(VALUE method, VALUE other)
 1628 {
 1629     struct METHOD *m1, *m2;
 1630     VALUE klass1, klass2;
 1631 
 1632     if (!rb_obj_is_method(other))
 1633     return Qfalse;
 1634     if (CLASS_OF(method) != CLASS_OF(other))
 1635     return Qfalse;
 1636 
 1637     Check_TypedStruct(method, &method_data_type);
 1638     m1 = (struct METHOD *)DATA_PTR(method);
 1639     m2 = (struct METHOD *)DATA_PTR(other);
 1640 
 1641     klass1 = method_entry_defined_class(m1->me);
 1642     klass2 = method_entry_defined_class(m2->me);
 1643 
 1644     if (!rb_method_entry_eq(m1->me, m2->me) ||
 1645     klass1 != klass2 ||
 1646     m1->klass != m2->klass ||
 1647     m1->recv != m2->recv) {
 1648     return Qfalse;
 1649     }
 1650 
 1651     return Qtrue;
 1652 }
 1653 
 1654 /*
 1655  * call-seq:
 1656  *    meth.hash   -> integer
 1657  *
 1658  * Returns a hash value corresponding to the method object.
 1659  *
 1660  * See also Object#hash.
 1661  */
 1662 
 1663 static VALUE
 1664 method_hash(VALUE method)
 1665 {
 1666     struct METHOD *m;
 1667     st_index_t hash;
 1668 
 1669     TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
 1670     hash = rb_hash_start((st_index_t)m->recv);
 1671     hash = rb_hash_method_entry(hash, m->me);
 1672     hash = rb_hash_end(hash);
 1673 
 1674     return ST2FIX(hash);
 1675 }
 1676 
 1677 /*
 1678  *  call-seq:
 1679  *     meth.unbind    -> unbound_method
 1680  *
 1681  *  Dissociates <i>meth</i> from its current receiver. The resulting
 1682  *  UnboundMethod can subsequently be bound to a new object of the
 1683  *  same class (see UnboundMethod).
 1684  */
 1685 
 1686 static VALUE
 1687 method_unbind(VALUE obj)
 1688 {
 1689     VALUE method;
 1690     struct METHOD *orig, *data;
 1691 
 1692     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
 1693     method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
 1694                    &method_data_type, data);
 1695     RB_OBJ_WRITE(method, &data->recv, Qundef);
 1696     RB_OBJ_WRITE(method, &data->klass, orig->klass);
 1697     RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
 1698     RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
 1699 
 1700     return method;
 1701 }
 1702 
 1703 /*
 1704  *  call-seq:
 1705  *     meth.receiver    -> object
 1706  *
 1707  *  Returns the bound receiver of the method object.
 1708  *
 1709  *    (1..3).method(:map).receiver # => 1..3
 1710  */
 1711 
 1712 static VALUE
 1713 method_receiver(VALUE obj)
 1714 {
 1715     struct METHOD *data;
 1716 
 1717     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
 1718     return data->recv;
 1719 }
 1720 
 1721 /*
 1722  *  call-seq:
 1723  *     meth.name    -> symbol
 1724  *
 1725  *  Returns the name of the method.
 1726  */
 1727 
 1728 static VALUE
 1729 method_name(VALUE obj)
 1730 {
 1731     struct METHOD *data;
 1732 
 1733     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
 1734     return ID2SYM(data->me->called_id);
 1735 }
 1736 
 1737 /*
 1738  *  call-seq:
 1739  *     meth.original_name    -> symbol
 1740  *
 1741  *  Returns the original name of the method.
 1742  *
 1743  *    class C
 1744  *      def foo; end
 1745  *      alias bar foo
 1746  *    end
 1747  *    C.instance_method(:bar).original_name # => :foo
 1748  */
 1749 
 1750 static VALUE
 1751 method_original_name(VALUE obj)
 1752 {
 1753     struct METHOD *data;
 1754 
 1755     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
 1756     return ID2SYM(data->me->def->original_id);
 1757 }
 1758 
 1759 /*
 1760  *  call-seq:
 1761  *     meth.owner    -> class_or_module
 1762  *
 1763  *  Returns the class or module that defines the method.
 1764  *  See also Method#receiver.
 1765  *
 1766  *    (1..3).method(:map).owner #=> Enumerable
 1767  */
 1768 
 1769 static VALUE
 1770 method_owner(VALUE obj)
 1771 {
 1772     struct METHOD *data;
 1773     TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
 1774     return data->me->owner;
 1775 }
 1776 
 1777 void
 1778 rb_method_name_error(VALUE klass, VALUE str)
 1779 {
 1780 #define MSG(s) rb_fstring_lit("undefined method `%1$s' for"s" `%2$s'")
 1781     VALUE c = klass;
 1782     VALUE s;
 1783 
 1784     if (FL_TEST(c, FL_SINGLETON)) {
 1785     VALUE obj = rb_ivar_get(klass, attached);
 1786 
 1787     switch (BUILTIN_TYPE(obj)) {
 1788       case T_MODULE:
 1789       case T_CLASS:
 1790         c = obj;
 1791         s = MSG("");
 1792     }
 1793     goto normal_class;
 1794     }
 1795     else if (RB_TYPE_P(c, T_MODULE)) {
 1796     s = MSG(" module");
 1797     }
 1798     else {
 1799       normal_class:
 1800     s = MSG(" class");
 1801     }
 1802     rb_name_err_raise_str(s, c, str);
 1803 #undef MSG
 1804 }
 1805 
 1806 static VALUE
 1807 obj_method(VALUE obj, VALUE vid, int scope)
 1808 {
 1809     ID id = rb_check_id(&vid);
 1810     const VALUE klass = CLASS_OF(obj);
 1811     const VALUE mclass = rb_cMethod;
 1812 
 1813     if (!id) {
 1814         VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
 1815         if (m) return m;
 1816     rb_method_name_error(klass, vid);
 1817     }
 1818     return mnew(klass, obj, id, mclass, scope);
 1819 }
 1820 
 1821 /*
 1822  *  call-seq:
 1823  *     obj.method(sym)    -> method
 1824  *
 1825  *  Looks up the named method as a receiver in <i>obj</i>, returning a
 1826  *  Method object (or raising NameError). The Method object acts as a
 1827  *  closure in <i>obj</i>'s object instance, so instance variables and
 1828  *  the value of <code>self</code> remain available.
 1829  *
 1830  *     class Demo
 1831  *       def initialize(n)
 1832  *         @iv = n
 1833  *       end
 1834  *       def hello()
 1835  *         "Hello, @iv = #{@iv}"
 1836  *       end
 1837  *     end
 1838  *
 1839  *     k = Demo.new(99)
 1840  *     m = k.method(:hello)
 1841  *     m.call   #=> "Hello, @iv = 99"
 1842  *
 1843  *     l = Demo.new('Fred')
 1844  *     m = l.method("hello")
 1845  *     m.call   #=> "Hello, @iv = Fred"
 1846  *
 1847  *  Note that Method implements <code>to_proc</code> method, which
 1848  *  means it can be used with iterators.
 1849  *
 1850  *     [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
 1851  *
 1852  *     out = File.open('test.txt', 'w')
 1853  *     [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
 1854  *
 1855  *     require 'date'
 1856  *     %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
 1857  *     #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
 1858  */
 1859 
 1860 VALUE
 1861 rb_obj_method(VALUE obj, VALUE vid)
 1862 {
 1863     return obj_method(obj, vid, FALSE);
 1864 }
 1865 
 1866 /*
 1867  *  call-seq:
 1868  *     obj.public_method(sym)    -> method
 1869  *
 1870  *  Similar to _method_, searches public method only.
 1871  */
 1872 
 1873 VALUE
 1874 rb_obj_public_method(VALUE obj, VALUE vid)
 1875 {
 1876     return obj_method(obj, vid, TRUE);
 1877 }
 1878 
 1879 /*
 1880  *  call-seq:
 1881  *     obj.singleton_method(sym)    -> method
 1882  *
 1883  *  Similar to _method_, searches singleton method only.
 1884  *
 1885  *     class Demo
 1886  *       def initialize(n)
 1887  *         @iv = n
 1888  *       end
 1889  *       def hello()
 1890  *         "Hello, @iv = #{@iv}"
 1891  *       end
 1892  *     end
 1893  *
 1894  *     k = Demo.new(99)
 1895  *     def k.hi
 1896  *       "Hi, @iv = #{@iv}"
 1897  *     end
 1898  *     m = k.singleton_method(:hi)
 1899  *     m.call   #=> "Hi, @iv = 99"
 1900  *     m = k.singleton_method(:hello) #=> NameError
 1901  */
 1902 
 1903 VALUE
 1904 rb_obj_singleton_method(VALUE obj, VALUE vid)
 1905 {
 1906     const rb_method_entry_t *me;
 1907     VALUE klass = rb_singleton_class_get(obj);
 1908     ID id = rb_check_id(&vid);
 1909 
 1910     if (NIL_P(klass) || NIL_P(klass = RCLASS_ORIGIN(klass))) {
 1911       undef:
 1912     rb_name_err_raise("undefined singleton method `%1$s' for `%2$s'",
 1913               obj, vid);
 1914     }
 1915     if (!id) {
 1916         VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
 1917         if (m) return m;
 1918     goto undef;
 1919     }
 1920     me = rb_method_entry_at(klass, id);
 1921     if (UNDEFINED_METHOD_ENTRY_P(me) ||
 1922     UNDEFINED_REFINED_METHOD_P(me->def)) {
 1923     vid = ID2SYM(id);
 1924     goto undef;
 1925     }
 1926     return mnew_from_me(me, klass, klass, obj, id, rb_cMethod, FALSE);
 1927 }
 1928 
 1929 /*
 1930  *  call-seq:
 1931  *     mod.instance_method(symbol)   -> unbound_method
 1932  *
 1933  *  Returns an +UnboundMethod+ representing the given
 1934  *  instance method in _mod_.
 1935  *
 1936  *     class Interpreter
 1937  *       def do_a() print "there, "; end
 1938  *       def do_d() print "Hello ";  end
 1939  *       def do_e() print "!\n";     end
 1940  *       def do_v() print "Dave";    end
 1941  *       Dispatcher = {
 1942  *         "a" => instance_method(:do_a),
 1943  *         "d" => instance_method(:do_d),
 1944  *         "e" => instance_method(:do_e),
 1945  *         "v" => instance_method(:do_v)
 1946  *       }
 1947  *       def interpret(string)
 1948  *         string.each_char {|b| Dispatcher[b].bind(self).call }
 1949  *       end
 1950  *     end
 1951  *
 1952  *     interpreter = Interpreter.new
 1953  *     interpreter.interpret('dave')
 1954  *
 1955  *  <em>produces:</em>
 1956  *
 1957  *     Hello there, Dave!
 1958  */
 1959 
 1960 static VALUE
 1961 rb_mod_instance_method(VALUE mod, VALUE vid)
 1962 {
 1963     ID id = rb_check_id(&vid);
 1964     if (!id) {
 1965     rb_method_name_error(mod, vid);
 1966     }
 1967     return mnew(mod, Qundef, id, rb_cUnboundMethod, FALSE);
 1968 }
 1969 
 1970 /*
 1971  *  call-seq:
 1972  *     mod.public_instance_method(symbol)   -> unbound_method
 1973  *
 1974  *  Similar to _instance_method_, searches public method only.
 1975  */
 1976 
 1977 static VALUE
 1978 rb_mod_public_instance_method(VALUE mod, VALUE vid)
 1979 {
 1980     ID id = rb_check_id(&vid);
 1981     if (!id) {
 1982     rb_method_name_error(mod, vid);
 1983     }
 1984     return mnew(mod, Qundef, id, rb_cUnboundMethod, TRUE);
 1985 }
 1986 
 1987 /*
 1988  *  call-seq:
 1989  *     define_method(symbol, method)     -> symbol
 1990  *     define_method(symbol) { block }   -> symbol
 1991  *
 1992  *  Defines an instance method in the receiver. The _method_
 1993  *  parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
 1994  *  If a block is specified, it is used as the method body.
 1995  *  If a block or the _method_ parameter has parameters,
 1996  *  they're used as method parameters.
 1997  *  This block is evaluated using #instance_eval.
 1998  *
 1999  *     class A
 2000  *       def fred
 2001  *         puts "In Fred"
 2002  *       end
 2003  *       def create_method(name, &block)
 2004  *         self.class.define_method(name, &block)
 2005  *       end
 2006  *       define_method(:wilma) { puts "Charge it!" }
 2007  *       define_method(:flint) {|name| puts "I'm #{name}!"}
 2008  *     end
 2009  *     class B < A
 2010  *       define_method(:barney, instance_method(:fred))
 2011  *     end
 2012  *     a = B.new
 2013  *     a.barney
 2014  *     a.wilma
 2015  *     a.flint('Dino')
 2016  *     a.create_method(:betty) { p self }
 2017  *     a.betty
 2018  *
 2019  *  <em>produces:</em>
 2020  *
 2021  *     In Fred
 2022  *     Charge it!
 2023  *     I'm Dino!
 2024  *     #<B:0x401b39e8>
 2025  */
 2026 
 2027 static VALUE
 2028 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
 2029 {
 2030     ID id;
 2031     VALUE body;
 2032     VALUE name;
 2033     const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
 2034     const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
 2035     const rb_scope_visibility_t *scope_visi = &default_scope_visi;
 2036     int is_method = FALSE;
 2037 
 2038     if (cref) {
 2039     scope_visi = CREF_SCOPE_VISI(cref);
 2040     }
 2041 
 2042     rb_check_arity(argc, 1, 2);
 2043     name = argv[0];
 2044     id = rb_check_id(&name);
 2045     if (argc == 1) {
 2046 #if PROC_NEW_REQUIRES_BLOCK
 2047     body = rb_block_lambda();
 2048 #else
 2049     const rb_execution_context_t *ec = GET_EC();
 2050     VALUE block_handler = rb_vm_frame_block_handler(ec->cfp);
 2051     if (block_handler == VM_BLOCK_HANDLER_NONE) rb_raise(rb_eArgError, proc_without_block);
 2052 
 2053     switch (vm_block_handler_type(block_handler)) {
 2054       case block_handler_type_proc:
 2055         body = VM_BH_TO_PROC(block_handler);
 2056         break;
 2057       case block_handler_type_symbol:
 2058         body = rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
 2059         break;
 2060       case block_handler_type_iseq:
 2061       case block_handler_type_ifunc:
 2062         body = rb_vm_make_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc);
 2063     }
 2064 #endif
 2065     }
 2066     else {
 2067     body = argv[1];
 2068 
 2069     if (rb_obj_is_method(body)) {
 2070         is_method = TRUE;
 2071     }
 2072     else if (rb_obj_is_proc(body)) {
 2073         is_method = FALSE;
 2074     }
 2075     else {
 2076         rb_raise(rb_eTypeError,
 2077              "wrong argument type %s (expected Proc/Method/UnboundMethod)",
 2078              rb_obj_classname(body));
 2079     }
 2080     }
 2081     if (!id) id = rb_to_id(name);
 2082 
 2083     if (is_method) {
 2084     struct METHOD *method = (struct METHOD *)DATA_PTR(body);
 2085     if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
 2086         !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
 2087         if (FL_TEST(method->me->owner, FL_SINGLETON)) {
 2088         rb_raise(rb_eTypeError,
 2089              "can't bind singleton method to a different class");
 2090         }
 2091         else {
 2092         rb_raise(rb_eTypeError,
 2093              "bind argument must be a subclass of % "PRIsVALUE,
 2094              method->me->owner);
 2095         }
 2096     }
 2097     rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
 2098     if (scope_visi->module_func) {
 2099         rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
 2100     }
 2101     RB_GC_GUARD(body);
 2102     }
 2103     else {
 2104     VALUE procval = rb_proc_dup(body);
 2105     if (vm_proc_iseq(procval) != NULL) {
 2106         rb_proc_t *proc;
 2107         GetProcPtr(procval, proc);
 2108         proc->is_lambda = TRUE;
 2109         proc->is_from_method = TRUE;
 2110     }
 2111     rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
 2112     if (scope_visi->module_func) {
 2113         rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
 2114     }
 2115     }
 2116 
 2117     return ID2SYM(id);
 2118 }
 2119 
 2120 /*
 2121  *  call-seq:
 2122  *     define_singleton_method(symbol, method) -> symbol
 2123  *     define_singleton_method(symbol) { block } -> symbol
 2124  *
 2125  *  Defines a singleton method in the receiver. The _method_
 2126  *  parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
 2127  *  If a block is specified, it is used as the method body.
 2128  *  If a block or a method has parameters, they're used as method parameters.
 2129  *
 2130  *     class A
 2131  *       class << self
 2132  *         def class_name
 2133  *           to_s
 2134  *         end
 2135  *       end
 2136  *     end
 2137  *     A.define_singleton_method(:who_am_i) do
 2138  *       "I am: #{class_name}"
 2139  *     end
 2140  *     A.who_am_i   # ==> "I am: A"
 2141  *
 2142  *     guy = "Bob"
 2143  *     guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
 2144  *     guy.hello    #=>  "Bob: Hello there!"
 2145  *
 2146  *     chris = "Chris"
 2147  *     chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
 2148  *     chris.greet("Hi") #=> "Hi, I'm Chris!"
 2149  */
 2150 
 2151 static VALUE
 2152 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
 2153 {
 2154     VALUE klass = rb_singleton_class(obj);
 2155 
 2156     return rb_mod_define_method(argc, argv, klass);
 2157 }
 2158 
 2159 /*
 2160  *     define_method(symbol, method)     -> symbol
 2161  *     define_method(symbol) { block }   -> symbol
 2162  *
 2163  *  Defines a global function by _method_ or the block.
 2164  */
 2165 
 2166 static VALUE
 2167 top_define_method(int argc, VALUE *argv, VALUE obj)
 2168 {
 2169     rb_thread_t *th = GET_THREAD();
 2170     VALUE klass;
 2171 
 2172     klass = th->top_wrapper;
 2173     if (klass) {
 2174     rb_warning("main.define_method in the wrapped load is effective only in wrapper module");
 2175     }
 2176     else {
 2177     klass = rb_cObject;
 2178     }
 2179     return rb_mod_define_method(argc, argv, klass);
 2180 }
 2181 
 2182 /*
 2183  *  call-seq:
 2184  *    method.clone -> new_method
 2185  *
 2186  *  Returns a clone of this method.
 2187  *
 2188  *    class A
 2189  *      def foo
 2190  *        return "bar"
 2191  *      end
 2192  *    end
 2193  *
 2194  *    m = A.new.method(:foo)
 2195  *    m.call # => "bar"
 2196  *    n = m.clone.call # => "bar"
 2197  */
 2198 
 2199 static VALUE
 2200 method_clone(VALUE self)
 2201 {
 2202     VALUE clone;
 2203     struct METHOD *orig, *data;
 2204 
 2205     TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
 2206     clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
 2207     CLONESETUP(clone, self);
 2208     RB_OBJ_WRITE(clone, &data->recv, orig->recv);
 2209     RB_OBJ_WRITE(clone, &data->klass, orig->klass);
 2210     RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
 2211     RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
 2212     return clone;
 2213 }
 2214 
 2215 /*  Document-method: Method#===
 2216  *
 2217  *  call-seq:
 2218  *     method === obj   -> result_of_method
 2219  *
 2220  *  Invokes the method with +obj+ as the parameter like #call.
 2221  *  This allows a method object to be the target of a +when+ clause
 2222  *  in a case statement.
 2223  *
 2224  *      require 'prime'
 2225  *
 2226  *      case 1373
 2227  *      when Prime.method(:prime?)
 2228  *        # ...
 2229  *      end
 2230  */
 2231 
 2232 
 2233 /*  Document-method: Method#[]
 2234  *
 2235  *  call-seq:
 2236  *     meth[args, ...]         -> obj
 2237  *
 2238  *  Invokes the <i>meth</i> with the specified arguments, returning the
 2239  *  method's return value, like #call.
 2240  *
 2241  *     m = 12.method("+")
 2242  *     m[3]         #=> 15
 2243  *     m[20]        #=> 32
 2244  */
 2245 
 2246 /*
 2247  *  call-seq:
 2248  *     meth.call(args, ...)    -> obj
 2249  *
 2250  *  Invokes the <i>meth</i> with the specified arguments, returning the
 2251  *  method's return value.
 2252  *
 2253  *     m = 12.method("+")
 2254  *     m.call(3)    #=> 15
 2255  *     m.call(20)   #=> 32
 2256  */
 2257 
 2258 static VALUE
 2259 rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
 2260 {
 2261     VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
 2262     return rb_method_call_with_block_kw(argc, argv, method, procval, RB_PASS_CALLED_KEYWORDS);
 2263 }
 2264 
 2265 VALUE
 2266 rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
 2267 {
 2268     VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
 2269     return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
 2270 }
 2271 
 2272 VALUE
 2273 rb_method_call(int argc, const VALUE *argv, VALUE method)
 2274 {
 2275     VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
 2276     return rb_method_call_with_block(argc, argv, method, procval);
 2277 }
 2278 
 2279 static const rb_callable_method_entry_t *
 2280 method_callable_method_entry(const struct METHOD *data)
 2281 {
 2282     if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
 2283     return (const rb_callable_method_entry_t *)data->me;
 2284 }
 2285 
 2286 static inline VALUE
 2287 call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
 2288                  int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
 2289 {
 2290     vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
 2291     return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
 2292                          method_callable_method_entry(data), kw_splat);
 2293 }
 2294 
 2295 VALUE
 2296 rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
 2297 {
 2298     const struct METHOD *data;
 2299     rb_execution_context_t *ec = GET_EC();
 2300 
 2301     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2302     if (data->recv == Qundef) {
 2303     rb_raise(rb_eTypeError, "can't call unbound method; bind first");
 2304     }
 2305     return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
 2306 }
 2307 
 2308 VALUE
 2309 rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
 2310 {
 2311     return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
 2312 }
 2313 
 2314 /**********************************************************************
 2315  *
 2316  * Document-class: UnboundMethod
 2317  *
 2318  *  Ruby supports two forms of objectified methods. Class Method is
 2319  *  used to represent methods that are associated with a particular
 2320  *  object: these method objects are bound to that object. Bound
 2321  *  method objects for an object can be created using Object#method.
 2322  *
 2323  *  Ruby also supports unbound methods; methods objects that are not
 2324  *  associated with a particular object. These can be created either
 2325  *  by calling Module#instance_method or by calling #unbind on a bound
 2326  *  method object. The result of both of these is an UnboundMethod
 2327  *  object.
 2328  *
 2329  *  Unbound methods can only be called after they are bound to an
 2330  *  object. That object must be a kind_of? the method's original
 2331  *  class.
 2332  *
 2333  *     class Square
 2334  *       def area
 2335  *         @side * @side
 2336  *       end
 2337  *       def initialize(side)
 2338  *         @side = side
 2339  *       end
 2340  *     end
 2341  *
 2342  *     area_un = Square.instance_method(:area)
 2343  *
 2344  *     s = Square.new(12)
 2345  *     area = area_un.bind(s)
 2346  *     area.call   #=> 144
 2347  *
 2348  *  Unbound methods are a reference to the method at the time it was
 2349  *  objectified: subsequent changes to the underlying class will not
 2350  *  affect the unbound method.
 2351  *
 2352  *     class Test
 2353  *       def test
 2354  *         :original
 2355  *       end
 2356  *     end
 2357  *     um = Test.instance_method(:test)
 2358  *     class Test
 2359  *       def test
 2360  *         :modified
 2361  *       end
 2362  *     end
 2363  *     t = Test.new
 2364  *     t.test            #=> :modified
 2365  *     um.bind(t).call   #=> :original
 2366  *
 2367  */
 2368 
 2369 static void
 2370 convert_umethod_to_method_components(VALUE method, VALUE recv, VALUE *methclass_out, VALUE *klass_out, VALUE *iclass_out, const rb_method_entry_t **me_out)
 2371 {
 2372     struct METHOD *data;
 2373 
 2374     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2375 
 2376     VALUE methclass = data->me->owner;
 2377     VALUE iclass = data->me->defined_class;
 2378     VALUE klass = CLASS_OF(recv);
 2379 
 2380     if (!RB_TYPE_P(methclass, T_MODULE) &&
 2381     methclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, methclass)) {
 2382     if (FL_TEST(methclass, FL_SINGLETON)) {
 2383         rb_raise(rb_eTypeError,
 2384              "singleton method called for a different object");
 2385     }
 2386     else {
 2387         rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
 2388              methclass);
 2389     }
 2390     }
 2391 
 2392     const rb_method_entry_t *me = rb_method_entry_clone(data->me);
 2393 
 2394     if (RB_TYPE_P(me->owner, T_MODULE)) {
 2395     VALUE ic = rb_class_search_ancestor(klass, me->owner);
 2396     if (ic) {
 2397         klass = ic;
 2398             iclass = ic;
 2399     }
 2400     else {
 2401         klass = rb_include_class_new(methclass, klass);
 2402     }
 2403         me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
 2404     }
 2405 
 2406     *methclass_out = methclass;
 2407     *klass_out = klass;
 2408     *iclass_out = iclass;
 2409     *me_out = me;
 2410 }
 2411 
 2412 /*
 2413  *  call-seq:
 2414  *     umeth.bind(obj) -> method
 2415  *
 2416  *  Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
 2417  *  <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
 2418  *  be true.
 2419  *
 2420  *     class A
 2421  *       def test
 2422  *         puts "In test, class = #{self.class}"
 2423  *       end
 2424  *     end
 2425  *     class B < A
 2426  *     end
 2427  *     class C < B
 2428  *     end
 2429  *
 2430  *
 2431  *     um = B.instance_method(:test)
 2432  *     bm = um.bind(C.new)
 2433  *     bm.call
 2434  *     bm = um.bind(B.new)
 2435  *     bm.call
 2436  *     bm = um.bind(A.new)
 2437  *     bm.call
 2438  *
 2439  *  <em>produces:</em>
 2440  *
 2441  *     In test, class = C
 2442  *     In test, class = B
 2443  *     prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
 2444  *      from prog.rb:16
 2445  */
 2446 
 2447 static VALUE
 2448 umethod_bind(VALUE method, VALUE recv)
 2449 {
 2450     VALUE methclass, klass, iclass;
 2451     const rb_method_entry_t *me;
 2452     convert_umethod_to_method_components(method, recv, &methclass, &klass, &iclass, &me);
 2453 
 2454     struct METHOD *bound;
 2455     method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
 2456     RB_OBJ_WRITE(method, &bound->recv, recv);
 2457     RB_OBJ_WRITE(method, &bound->klass, klass);
 2458     RB_OBJ_WRITE(method, &bound->iclass, iclass);
 2459     RB_OBJ_WRITE(method, &bound->me, me);
 2460 
 2461     return method;
 2462 }
 2463 
 2464 /*
 2465  *  call-seq:
 2466  *     umeth.bind_call(recv, args, ...) -> obj
 2467  *
 2468  *  Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
 2469  *  specified arguments.
 2470  *  This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
 2471  */
 2472 static VALUE
 2473 umethod_bind_call(int argc, VALUE *argv, VALUE method)
 2474 {
 2475     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
 2476     VALUE recv = argv[0];
 2477     argc--;
 2478     argv++;
 2479 
 2480     VALUE methclass, klass, iclass;
 2481     const rb_method_entry_t *me;
 2482     convert_umethod_to_method_components(method, recv, &methclass, &klass, &iclass, &me);
 2483     struct METHOD bound = { recv, klass, 0, me };
 2484 
 2485     VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
 2486 
 2487     rb_execution_context_t *ec = GET_EC();
 2488     return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
 2489 }
 2490 
 2491 /*
 2492  * Returns the number of required parameters and stores the maximum
 2493  * number of parameters in max, or UNLIMITED_ARGUMENTS
 2494  * if there is no maximum.
 2495  */
 2496 static int
 2497 rb_method_entry_min_max_arity(const rb_method_entry_t *me, int *max)
 2498 {
 2499     const rb_method_definition_t *def = me->def;
 2500 
 2501   again:
 2502     if (!def) return *max = 0;
 2503     switch (def->type) {
 2504       case VM_METHOD_TYPE_CFUNC:
 2505     if (def->body.cfunc.argc < 0) {
 2506         *max = UNLIMITED_ARGUMENTS;
 2507         return 0;
 2508     }
 2509     return *max = check_argc(def->body.cfunc.argc);
 2510       case VM_METHOD_TYPE_ZSUPER:
 2511     *max = UNLIMITED_ARGUMENTS;
 2512     return 0;
 2513       case VM_METHOD_TYPE_ATTRSET:
 2514     return *max = 1;
 2515       case VM_METHOD_TYPE_IVAR:
 2516     return *max = 0;
 2517       case VM_METHOD_TYPE_ALIAS:
 2518     def = def->body.alias.original_me->def;
 2519     goto again;
 2520       case VM_METHOD_TYPE_BMETHOD:
 2521         return rb_proc_min_max_arity(def->body.bmethod.proc, max);
 2522       case VM_METHOD_TYPE_ISEQ:
 2523     return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
 2524       case VM_METHOD_TYPE_UNDEF:
 2525       case VM_METHOD_TYPE_NOTIMPLEMENTED:
 2526     return *max = 0;
 2527       case VM_METHOD_TYPE_MISSING:
 2528     *max = UNLIMITED_ARGUMENTS;
 2529     return 0;
 2530       case VM_METHOD_TYPE_OPTIMIZED: {
 2531     switch (def->body.optimize_type) {
 2532       case OPTIMIZED_METHOD_TYPE_SEND:
 2533         *max = UNLIMITED_ARGUMENTS;
 2534         return 0;
 2535       case OPTIMIZED_METHOD_TYPE_CALL:
 2536         *max = UNLIMITED_ARGUMENTS;
 2537         return 0;
 2538       case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
 2539         *max = UNLIMITED_ARGUMENTS;
 2540         return 0;
 2541       default:
 2542         break;
 2543     }
 2544     break;
 2545       }
 2546       case VM_METHOD_TYPE_REFINED:
 2547     *max = UNLIMITED_ARGUMENTS;
 2548     return 0;
 2549     }
 2550     rb_bug("rb_method_entry_min_max_arity: invalid method entry type (%d)", def->type);
 2551     UNREACHABLE_RETURN(Qnil);
 2552 }
 2553 
 2554 int
 2555 rb_method_entry_arity(const rb_method_entry_t *me)
 2556 {
 2557     int max, min = rb_method_entry_min_max_arity(me, &max);
 2558     return min == max ? min : -min-1;
 2559 }
 2560 
 2561 /*
 2562  *  call-seq:
 2563  *     meth.arity    -> integer
 2564  *
 2565  *  Returns an indication of the number of arguments accepted by a
 2566  *  method. Returns a nonnegative integer for methods that take a fixed
 2567  *  number of arguments. For Ruby methods that take a variable number of
 2568  *  arguments, returns -n-1, where n is the number of required arguments.
 2569  *  Keyword arguments will be considered as a single additional argument,
 2570  *  that argument being mandatory if any keyword argument is mandatory.
 2571  *  For methods written in C, returns -1 if the call takes a
 2572  *  variable number of arguments.
 2573  *
 2574  *     class C
 2575  *       def one;    end
 2576  *       def two(a); end
 2577  *       def three(*a);  end
 2578  *       def four(a, b); end
 2579  *       def five(a, b, *c);    end
 2580  *       def six(a, b, *c, &d); end
 2581  *       def seven(a, b, x:0); end
 2582  *       def eight(x:, y:); end
 2583  *       def nine(x:, y:, **z); end
 2584  *       def ten(*a, x:, y:); end
 2585  *     end
 2586  *     c = C.new
 2587  *     c.method(:one).arity     #=> 0
 2588  *     c.method(:two).arity     #=> 1
 2589  *     c.method(:three).arity   #=> -1
 2590  *     c.method(:four).arity    #=> 2
 2591  *     c.method(:five).arity    #=> -3
 2592  *     c.method(:six).arity     #=> -3
 2593  *     c.method(:seven).arity   #=> -3
 2594  *     c.method(:eight).arity   #=> 1
 2595  *     c.method(:nine).arity    #=> 1
 2596  *     c.method(:ten).arity     #=> -2
 2597  *
 2598  *     "cat".method(:size).arity      #=> 0
 2599  *     "cat".method(:replace).arity   #=> 1
 2600  *     "cat".method(:squeeze).arity   #=> -1
 2601  *     "cat".method(:count).arity     #=> -1
 2602  */
 2603 
 2604 static VALUE
 2605 method_arity_m(VALUE method)
 2606 {
 2607     int n = method_arity(method);
 2608     return INT2FIX(n);
 2609 }
 2610 
 2611 static int
 2612 method_arity(VALUE method)
 2613 {
 2614     struct METHOD *data;
 2615 
 2616     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2617     return rb_method_entry_arity(data->me);
 2618 }
 2619 
 2620 static const rb_method_entry_t *
 2621 original_method_entry(VALUE mod, ID id)
 2622 {
 2623     const rb_method_entry_t *me;
 2624 
 2625     while ((me = rb_method_entry(mod, id)) != 0) {
 2626     const rb_method_definition_t *def = me->def;
 2627     if (def->type != VM_METHOD_TYPE_ZSUPER) break;
 2628     mod = RCLASS_SUPER(me->owner);
 2629     id = def->original_id;
 2630     }
 2631     return me;
 2632 }
 2633 
 2634 static int
 2635 method_min_max_arity(VALUE method, int *max)
 2636 {
 2637     const struct METHOD *data;
 2638 
 2639     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2640     return rb_method_entry_min_max_arity(data->me, max);
 2641 }
 2642 
 2643 int
 2644 rb_mod_method_arity(VALUE mod, ID id)
 2645 {
 2646     const rb_method_entry_t *me = original_method_entry(mod, id);
 2647     if (!me) return 0;      /* should raise? */
 2648     return rb_method_entry_arity(me);
 2649 }
 2650 
 2651 int
 2652 rb_obj_method_arity(VALUE obj, ID id)
 2653 {
 2654     return rb_mod_method_arity(CLASS_OF(obj), id);
 2655 }
 2656 
 2657 const rb_method_definition_t *
 2658 rb_method_def(VALUE method)
 2659 {
 2660     const struct METHOD *data;
 2661 
 2662     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2663     return data->me->def;
 2664 }
 2665 
 2666 static const rb_iseq_t *
 2667 method_def_iseq(const rb_method_definition_t *def)
 2668 {
 2669     switch (def->type) {
 2670       case VM_METHOD_TYPE_ISEQ:
 2671     return rb_iseq_check(def->body.iseq.iseqptr);
 2672       case VM_METHOD_TYPE_BMETHOD:
 2673         return rb_proc_get_iseq(def->body.bmethod.proc, 0);
 2674       case VM_METHOD_TYPE_ALIAS:
 2675     return method_def_iseq(def->body.alias.original_me->def);
 2676       case VM_METHOD_TYPE_CFUNC:
 2677       case VM_METHOD_TYPE_ATTRSET:
 2678       case VM_METHOD_TYPE_IVAR:
 2679       case VM_METHOD_TYPE_ZSUPER:
 2680       case VM_METHOD_TYPE_UNDEF:
 2681       case VM_METHOD_TYPE_NOTIMPLEMENTED:
 2682       case VM_METHOD_TYPE_OPTIMIZED:
 2683       case VM_METHOD_TYPE_MISSING:
 2684       case VM_METHOD_TYPE_REFINED:
 2685     break;
 2686     }
 2687     return NULL;
 2688 }
 2689 
 2690 const rb_iseq_t *
 2691 rb_method_iseq(VALUE method)
 2692 {
 2693     return method_def_iseq(rb_method_def(method));
 2694 }
 2695 
 2696 static const rb_cref_t *
 2697 method_cref(VALUE method)
 2698 {
 2699     const rb_method_definition_t *def = rb_method_def(method);
 2700 
 2701   again:
 2702     switch (def->type) {
 2703       case VM_METHOD_TYPE_ISEQ:
 2704     return def->body.iseq.cref;
 2705       case VM_METHOD_TYPE_ALIAS:
 2706     def = def->body.alias.original_me->def;
 2707     goto again;
 2708       default:
 2709     return NULL;
 2710     }
 2711 }
 2712 
 2713 static VALUE
 2714 method_def_location(const rb_method_definition_t *def)
 2715 {
 2716     if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
 2717     if (!def->body.attr.location)
 2718         return Qnil;
 2719     return rb_ary_dup(def->body.attr.location);
 2720     }
 2721     return iseq_location(method_def_iseq(def));
 2722 }
 2723 
 2724 VALUE
 2725 rb_method_entry_location(const rb_method_entry_t *me)
 2726 {
 2727     if (!me) return Qnil;
 2728     return method_def_location(me->def);
 2729 }
 2730 
 2731 /*
 2732  * call-seq:
 2733  *    meth.source_location  -> [String, Integer]
 2734  *
 2735  * Returns the Ruby source filename and line number containing this method
 2736  * or nil if this method was not defined in Ruby (i.e. native).
 2737  */
 2738 
 2739 VALUE
 2740 rb_method_location(VALUE method)
 2741 {
 2742     return method_def_location(rb_method_def(method));
 2743 }
 2744 
 2745 /*
 2746  * call-seq:
 2747  *    meth.parameters  -> array
 2748  *
 2749  * Returns the parameter information of this method.
 2750  *
 2751  *    def foo(bar); end
 2752  *    method(:foo).parameters #=> [[:req, :bar]]
 2753  *
 2754  *    def foo(bar, baz, bat, &blk); end
 2755  *    method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
 2756  *
 2757  *    def foo(bar, *args); end
 2758  *    method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
 2759  *
 2760  *    def foo(bar, baz, *args, &blk); end
 2761  *    method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
 2762  */
 2763 
 2764 static VALUE
 2765 rb_method_parameters(VALUE method)
 2766 {
 2767     const rb_iseq_t *iseq = rb_method_iseq(method);
 2768     if (!iseq) {
 2769     return rb_unnamed_parameters(method_arity(method));
 2770     }
 2771     return rb_iseq_parameters(iseq, 0);
 2772 }
 2773 
 2774 /*
 2775  *  call-seq:
 2776  *   meth.to_s      ->  string
 2777  *   meth.inspect   ->  string
 2778  *
 2779  *  Returns a human-readable description of the underlying method.
 2780  *
 2781  *    "cat".method(:count).inspect   #=> "#<Method: String#count(*)>"
 2782  *    (1..3).method(:map).inspect    #=> "#<Method: Range(Enumerable)#map()>"
 2783  *
 2784  *  In the latter case, the method description includes the "owner" of the
 2785  *  original method (+Enumerable+ module, which is included into +Range+).
 2786  *
 2787  *  +inspect+ also provides, when possible, method argument names (call
 2788  *  sequence) and source location.
 2789  *
 2790  *    require 'net/http'
 2791  *    Net::HTTP.method(:get).inspect
 2792  *    #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
 2793  *
 2794  *  <code>...</code> in argument definition means argument is optional (has
 2795  *  some default value).
 2796  *
 2797  *  For methods defined in C (language core and extensions), location and
 2798  *  argument names can't be extracted, and only generic information is provided
 2799  *  in form of <code>*</code> (any number of arguments) or <code>_</code> (some
 2800  *  positional argument).
 2801  *
 2802  *    "cat".method(:count).inspect   #=> "#<Method: String#count(*)>"
 2803  *    "cat".method(:+).inspect       #=> "#<Method: String#+(_)>""
 2804 
 2805  */
 2806 
 2807 static VALUE
 2808 method_inspect(VALUE method)
 2809 {
 2810     struct METHOD *data;
 2811     VALUE str;
 2812     const char *sharp = "#";
 2813     VALUE mklass;
 2814     VALUE defined_class;
 2815 
 2816     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 2817     str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
 2818 
 2819     mklass = data->klass;
 2820 
 2821     if (RB_TYPE_P(mklass, T_ICLASS)) {
 2822         /* TODO: I'm not sure why mklass is T_ICLASS.
 2823          * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
 2824          * but not sure it is needed.
 2825          */
 2826         mklass = RBASIC_CLASS(mklass);
 2827     }
 2828 
 2829     if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
 2830     defined_class = data->me->def->body.alias.original_me->owner;
 2831     }
 2832     else {
 2833     defined_class = method_entry_defined_class(data->me);
 2834     }
 2835 
 2836     if (RB_TYPE_P(defined_class, T_ICLASS)) {
 2837     defined_class = RBASIC_CLASS(defined_class);
 2838     }
 2839 
 2840     if (FL_TEST(mklass, FL_SINGLETON)) {
 2841     VALUE v = rb_ivar_get(mklass, attached);
 2842 
 2843     if (data->recv == Qundef) {
 2844         rb_str_buf_append(str, rb_inspect(mklass));
 2845     }
 2846     else if (data->recv == v) {
 2847         rb_str_buf_append(str, rb_inspect(v));
 2848         sharp = ".";
 2849     }
 2850     else {
 2851         rb_str_buf_append(str, rb_inspect(data->recv));
 2852         rb_str_buf_cat2(str, "(");
 2853         rb_str_buf_append(str, rb_inspect(v));
 2854         rb_str_buf_cat2(str, ")");
 2855         sharp = ".";
 2856     }
 2857     }
 2858     else {
 2859     rb_str_buf_append(str, rb_inspect(mklass));
 2860     if (defined_class != mklass) {
 2861         rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
 2862     }
 2863     }
 2864     rb_str_buf_cat2(str, sharp);
 2865     rb_str_append(str, rb_id2str(data->me->called_id));
 2866     if (data->me->called_id != data->me->def->original_id) {
 2867     rb_str_catf(str, "(%"PRIsVALUE")",
 2868             rb_id2str(data->me->def->original_id));
 2869     }
 2870     if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
 2871         rb_str_buf_cat2(str, " (not-implemented)");
 2872     }
 2873 
 2874     // parameter information
 2875     {
 2876         VALUE params = rb_method_parameters(method);
 2877         VALUE pair, name, kind;
 2878         const VALUE req = ID2SYM(rb_intern("req"));
 2879         const VALUE opt = ID2SYM(rb_intern("opt"));
 2880         const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
 2881         const VALUE key = ID2SYM(rb_intern("key"));
 2882         const VALUE rest = ID2SYM(rb_intern("rest"));
 2883         const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
 2884         const VALUE block = ID2SYM(rb_intern("block"));
 2885         const VALUE nokey = ID2SYM(rb_intern("nokey"));
 2886         int forwarding = 0;
 2887 
 2888         rb_str_buf_cat2(str, "(");
 2889 
 2890         for (int i = 0; i < RARRAY_LEN(params); i++) {
 2891             pair = RARRAY_AREF(params, i);
 2892             kind = RARRAY_AREF(pair, 0);
 2893             name = RARRAY_AREF(pair, 1);
 2894             // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
 2895             if (NIL_P(name) || name == Qfalse) {
 2896                 // FIXME: can it be reduced to switch/case?
 2897                 if (kind == req || kind == opt) {
 2898                     name = rb_str_new2("_");
 2899                 }
 2900                 else if (kind == rest || kind == keyrest) {
 2901                     name = rb_str_new2("");
 2902                 }
 2903                 else if (kind == block) {
 2904                     name = rb_str_new2("block");
 2905                 }
 2906                 else if (kind == nokey) {
 2907                     name = rb_str_new2("nil");
 2908                 }
 2909             }
 2910 
 2911             if (kind == req) {
 2912                 rb_str_catf(str, "%"PRIsVALUE, name);
 2913             }
 2914             else if (kind == opt) {
 2915                 rb_str_catf(str, "%"PRIsVALUE"=...", name);
 2916             }
 2917             else if (kind == keyreq) {
 2918                 rb_str_catf(str, "%"PRIsVALUE":", name);
 2919             }
 2920             else if (kind == key) {
 2921                 rb_str_catf(str, "%"PRIsVALUE": ...", name);
 2922             }
 2923             else if (kind == rest) {
 2924                 if (name == ID2SYM('*')) {
 2925                     forwarding = 1;
 2926                     rb_str_cat_cstr(str, "...");
 2927                 }
 2928                 else {
 2929                     rb_str_catf(str, "*%"PRIsVALUE, name);
 2930                 }
 2931             }
 2932             else if (kind == keyrest) {
 2933                 rb_str_catf(str, "**%"PRIsVALUE, name);
 2934             }
 2935             else if (kind == block) {
 2936                 if (name == ID2SYM('&')) {
 2937                     if (forwarding) {
 2938                         rb_str_set_len(str, RSTRING_LEN(str) - 2);
 2939                     }
 2940                     else {
 2941                         rb_str_cat_cstr(str, "...");
 2942                     }
 2943                 }
 2944                 else {
 2945                     rb_str_catf(str, "&%"PRIsVALUE, name);
 2946                 }
 2947             }
 2948             else if (kind == nokey) {
 2949                 rb_str_buf_cat2(str, "**nil");
 2950             }
 2951 
 2952             if (i < RARRAY_LEN(params) - 1) {
 2953                 rb_str_buf_cat2(str, ", ");
 2954             }
 2955         }
 2956         rb_str_buf_cat2(str, ")");
 2957     }
 2958 
 2959     { // source location
 2960         VALUE loc = rb_method_location(method);
 2961         if (!NIL_P(loc)) {
 2962             rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
 2963                         RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
 2964         }
 2965     }
 2966 
 2967     rb_str_buf_cat2(str, ">");
 2968 
 2969     return str;
 2970 }
 2971 
 2972 static VALUE
 2973 mproc(VALUE method)
 2974 {
 2975     return rb_funcallv(rb_mRubyVMFrozenCore, idProc, 0, 0);
 2976 }
 2977 
 2978 static VALUE
 2979 mlambda(VALUE method)
 2980 {
 2981     return rb_funcallv(rb_mRubyVMFrozenCore, idLambda, 0, 0);
 2982 }
 2983 
 2984 static VALUE
 2985 bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
 2986 {
 2987     return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
 2988 }
 2989 
 2990 VALUE
 2991 rb_proc_new(
 2992     rb_block_call_func_t func,
 2993     VALUE val)
 2994 {
 2995     VALUE procval = rb_iterate(mproc, 0, func, val);
 2996     return procval;
 2997 }
 2998 
 2999 /*
 3000  *  call-seq:
 3001  *     meth.to_proc    -> proc
 3002  *
 3003  *  Returns a Proc object corresponding to this method.
 3004  */
 3005 
 3006 static VALUE
 3007 method_to_proc(VALUE method)
 3008 {
 3009     VALUE procval;
 3010     rb_proc_t *proc;
 3011 
 3012     /*
 3013      * class Method
 3014      *   def to_proc
 3015      *     lambda{|*args|
 3016      *       self.call(*args)
 3017      *     }
 3018      *   end
 3019      * end
 3020      */
 3021     procval = rb_iterate(mlambda, 0, bmcall, method);
 3022     GetProcPtr(procval, proc);
 3023     proc->is_from_method = 1;
 3024     return procval;
 3025 }
 3026 
 3027 extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
 3028 
 3029 /*
 3030  * call-seq:
 3031  *   meth.super_method  -> method
 3032  *
 3033  * Returns a Method of superclass which would be called when super is used
 3034  * or nil if there is no method on superclass.
 3035  */
 3036 
 3037 static VALUE
 3038 method_super_method(VALUE method)
 3039 {
 3040     const struct METHOD *data;
 3041     VALUE super_class, iclass;
 3042     ID mid;
 3043     const rb_method_entry_t *me;
 3044 
 3045     TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
 3046     iclass = data->iclass;
 3047     if (!iclass) return Qnil;
 3048     if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
 3049         super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
 3050             data->me->def->body.alias.original_me->owner));
 3051         mid = data->me->def->body.alias.original_me->def->original_id;
 3052     }
 3053     else {
 3054         super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
 3055         mid = data->me->def->original_id;
 3056     }
 3057     if (!super_class) return Qnil;
 3058     me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
 3059     if (!me) return Qnil;
 3060     return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
 3061 }
 3062 
 3063 /*
 3064  * call-seq:
 3065  *   local_jump_error.exit_value  -> obj
 3066  *
 3067  * Returns the exit value associated with this +LocalJumpError+.
 3068  */
 3069 static VALUE
 3070 localjump_xvalue(VALUE exc)
 3071 {
 3072     return rb_iv_get(exc, "@exit_value");
 3073 }
 3074 
 3075 /*
 3076  * call-seq:
 3077  *    local_jump_error.reason   -> symbol
 3078  *
 3079  * The reason this block was terminated:
 3080  * :break, :redo, :retry, :next, :return, or :noreason.
 3081  */
 3082 
 3083 static VALUE
 3084 localjump_reason(VALUE exc)
 3085 {
 3086     return rb_iv_get(exc, "@reason");
 3087 }
 3088 
 3089 rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
 3090 
 3091 static const rb_env_t *
 3092 env_clone(const rb_env_t *env, const rb_cref_t *cref)
 3093 {
 3094     VALUE *new_ep;
 3095     VALUE *new_body;
 3096     const rb_env_t *new_env;
 3097 
 3098     VM_ASSERT(env->ep > env->env);
 3099     VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
 3100 
 3101     if (cref == NULL) {
 3102     cref = rb_vm_cref_new_toplevel();
 3103     }
 3104 
 3105     new_body = ALLOC_N(VALUE, env->env_size);
 3106     MEMCPY(new_body, env->env, VALUE, env->env_size);
 3107     new_ep = &new_body[env->ep - env->env];
 3108     new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
 3109     RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
 3110     VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
 3111     return new_env;
 3112 }
 3113 
 3114 /*
 3115  *  call-seq:
 3116  *     prc.binding    -> binding
 3117  *
 3118  *  Returns the binding associated with <i>prc</i>.
 3119  *
 3120  *     def fred(param)
 3121  *       proc {}
 3122  *     end
 3123  *
 3124  *     b = fred(99)
 3125  *     eval("param", b.binding)   #=> 99
 3126  */
 3127 static VALUE
 3128 proc_binding(VALUE self)
 3129 {
 3130     VALUE bindval, binding_self = Qundef;
 3131     rb_binding_t *bind;
 3132     const rb_proc_t *proc;
 3133     const rb_iseq_t *iseq = NULL;
 3134     const struct rb_block *block;
 3135     const rb_env_t *env = NULL;
 3136 
 3137     GetProcPtr(self, proc);
 3138     block = &proc->block;
 3139 
 3140   again:
 3141     switch (vm_block_type(block)) {
 3142       case block_type_iseq:
 3143     iseq = block->as.captured.code.iseq;
 3144     binding_self = block->as.captured.self;
 3145     env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
 3146     break;
 3147       case block_type_proc:
 3148     GetProcPtr(block->as.proc, proc);
 3149     block = &proc->block;
 3150     goto again;
 3151       case block_type_symbol:
 3152     goto error;
 3153       case block_type_ifunc:
 3154     {
 3155         const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
 3156         if (IS_METHOD_PROC_IFUNC(ifunc)) {
 3157         VALUE method = (VALUE)ifunc->data;
 3158         VALUE name = rb_fstring_lit("<empty_iseq>");
 3159         rb_iseq_t *empty;
 3160         binding_self = method_receiver(method);
 3161         iseq = rb_method_iseq(method);
 3162         env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
 3163         env = env_clone(env, method_cref(method));
 3164         /* set empty iseq */
 3165         empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP);
 3166         RB_OBJ_WRITE(env, &env->iseq, empty);
 3167         break;
 3168         }
 3169         else {
 3170           error:
 3171         rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
 3172         return Qnil;
 3173         }
 3174     }
 3175     }
 3176 
 3177     bindval = rb_binding_alloc(rb_cBinding);
 3178     GetBindingPtr(bindval, bind);
 3179     RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
 3180     RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
 3181     rb_vm_block_ep_update(bindval, &bind->block, env->ep);
 3182     RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
 3183 
 3184     if (iseq) {
 3185     rb_iseq_check(iseq);
 3186     RB_OBJ_WRITE(bindval, &bind->pathobj, iseq->body->location.pathobj);
 3187     bind->first_lineno = FIX2INT(rb_iseq_first_lineno(iseq));
 3188     }
 3189     else {
 3190     RB_OBJ_WRITE(bindval, &bind->pathobj,
 3191              rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
 3192     bind->first_lineno = 1;
 3193     }
 3194 
 3195     return bindval;
 3196 }
 3197 
 3198 static rb_block_call_func curry;
 3199 
 3200 static VALUE
 3201 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
 3202 {
 3203     VALUE args = rb_ary_new3(3, proc, passed, arity);
 3204     rb_proc_t *procp;
 3205     int is_lambda;
 3206 
 3207     GetProcPtr(proc, procp);
 3208     is_lambda = procp->is_lambda;
 3209     rb_ary_freeze(passed);
 3210     rb_ary_freeze(args);
 3211     proc = rb_proc_new(curry, args);
 3212     GetProcPtr(proc, procp);
 3213     procp->is_lambda = is_lambda;
 3214     return proc;
 3215 }
 3216 
 3217 static VALUE
 3218 curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
 3219 {
 3220     VALUE proc, passed, arity;
 3221     proc = RARRAY_AREF(args, 0);
 3222     passed = RARRAY_AREF(args, 1);
 3223     arity = RARRAY_AREF(args, 2);
 3224 
 3225     passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
 3226     rb_ary_freeze(passed);
 3227 
 3228     if (RARRAY_LEN(passed) < FIX2INT(arity)) {
 3229         if (!NIL_P(blockarg)) {
 3230         rb_warn("given block not used");
 3231     }
 3232     arity = make_curry_proc(proc, passed, arity);
 3233     return arity;
 3234     }
 3235     else {
 3236         return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
 3237     }
 3238 }
 3239 
 3240  /*
 3241   *  call-seq:
 3242   *     prc.curry         -> a_proc
 3243   *     prc.curry(arity)  -> a_proc
 3244   *
 3245   *  Returns a curried proc. If the optional <i>arity</i> argument is given,
 3246   *  it determines the number of arguments.
 3247   *  A curried proc receives some arguments. If a sufficient number of
 3248   *  arguments are supplied, it passes the supplied arguments to the original
 3249   *  proc and returns the result. Otherwise, returns another curried proc that
 3250   *  takes the rest of arguments.
 3251   *
 3252   *     b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
 3253   *     p b.curry[1][2][3]           #=> 6
 3254   *     p b.curry[1, 2][3, 4]        #=> 6
 3255   *     p b.curry(5)[1][2][3][4][5]  #=> 6
 3256   *     p b.curry(5)[1, 2][3, 4][5]  #=> 6
 3257   *     p b.curry(1)[1]              #=> 1
 3258   *
 3259   *     b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
 3260   *     p b.curry[1][2][3]           #=> 6
 3261   *     p b.curry[1, 2][3, 4]        #=> 10
 3262   *     p b.curry(5)[1][2][3][4][5]  #=> 15
 3263   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
 3264   *     p b.curry(1)[1]              #=> 1
 3265   *
 3266   *     b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
 3267   *     p b.curry[1][2][3]           #=> 6
 3268   *     p b.curry[1, 2][3, 4]        #=> wrong number of arguments (given 4, expected 3)
 3269   *     p b.curry(5)                 #=> wrong number of arguments (given 5, expected 3)
 3270   *     p b.curry(1)                 #=> wrong number of arguments (given 1, expected 3)
 3271   *
 3272   *     b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
 3273   *     p b.curry[1][2][3]           #=> 6
 3274   *     p b.curry[1, 2][3, 4]        #=> 10
 3275   *     p b.curry(5)[1][2][3][4][5]  #=> 15
 3276   *     p b.curry(5)[1, 2][3, 4][5]  #=> 15
 3277   *     p b.curry(1)                 #=> wrong number of arguments (given 1, expected 3)
 3278   *
 3279   *     b = proc { :foo }
 3280   *     p b.curry[]                  #=> :foo
 3281   */
 3282 static VALUE
 3283 proc_curry(int argc, const VALUE *argv, VALUE self)
 3284 {
 3285     int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
 3286     VALUE arity;
 3287 
 3288     if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
 3289     arity = INT2FIX(min_arity);
 3290     }
 3291     else {
 3292     sarity = FIX2INT(arity);
 3293     if (rb_proc_lambda_p(self)) {
 3294         rb_check_arity(sarity, min_arity, max_arity);
 3295     }
 3296     }
 3297 
 3298     return make_curry_proc(self, rb_ary_new(), arity);
 3299 }
 3300 
 3301 /*
 3302  *  call-seq:
 3303  *     meth.curry        -> proc
 3304  *     meth.curry(arity) -> proc
 3305  *
 3306  *  Returns a curried proc based on the method. When the proc is called with a number of
 3307  *  arguments that is lower than the method's arity, then another curried proc is returned.
 3308  *  Only when enough arguments have been supplied to satisfy the method signature, will the
 3309  *  method actually be called.
 3310  *
 3311  *  The optional <i>arity</i> argument should be supplied when currying methods with
 3312  *  variable arguments to determine how many arguments are needed before the method is
 3313  *  called.
 3314  *
 3315  *     def foo(a,b,c)
 3316  *       [a, b, c]
 3317  *     end
 3318  *
 3319  *     proc  = self.method(:foo).curry
 3320  *     proc2 = proc.call(1, 2)          #=> #<Proc>
 3321  *     proc2.call(3)                    #=> [1,2,3]
 3322  *
 3323  *     def vararg(*args)
 3324  *       args
 3325  *     end
 3326  *
 3327  *     proc = self.method(:vararg).curry(4)
 3328  *     proc2 = proc.call(:x)      #=> #<Proc>
 3329  *     proc3 = proc2.call(:y, :z) #=> #<Proc>
 3330  *     proc3.call(:a)             #=> [:x, :y, :z, :a]
 3331  */
 3332 
 3333 static VALUE
 3334 rb_method_curry(int argc, const VALUE *argv, VALUE self)
 3335 {
 3336     VALUE proc = method_to_proc(self);
 3337     return proc_curry(argc, argv, proc);
 3338 }
 3339 
 3340 static VALUE
 3341 compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
 3342 {
 3343     VALUE f, g, fargs;
 3344     f = RARRAY_AREF(args, 0);
 3345     g = RARRAY_AREF(args, 1);
 3346 
 3347     if (rb_obj_is_proc(g))
 3348         fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
 3349     else
 3350         fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
 3351 
 3352     if (rb_obj_is_proc(f))
 3353         return rb_proc_call(f, rb_ary_new3(1, fargs));
 3354     else
 3355         return rb_funcallv(f, idCall, 1, &fargs);
 3356 }
 3357 
 3358 static VALUE
 3359 to_callable(VALUE f)
 3360 {
 3361     VALUE mesg;
 3362 
 3363     if (rb_obj_is_proc(f)) return f;
 3364     if (rb_obj_is_method(f)) return f;
 3365     if (rb_obj_respond_to(f, idCall, TRUE)) return f;
 3366     mesg = rb_fstring_lit("callable object is expected");
 3367     rb_exc_raise(rb_exc_new_str(rb_eTypeError, mesg));
 3368 }
 3369 
 3370 static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
 3371 static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
 3372 
 3373 /*
 3374  *  call-seq:
 3375  *     prc << g -> a_proc
 3376  *
 3377  *  Returns a proc that is the composition of this proc and the given <i>g</i>.
 3378  *  The returned proc takes a variable number of arguments, calls <i>g</i> with them
 3379  *  then calls this proc with the result.
 3380  *
 3381  *     f = proc {|x| x * x }
 3382  *     g = proc {|x| x + x }
 3383  *     p (f << g).call(2) #=> 16
 3384  *
 3385  *  See Proc#>> for detailed explanations.
 3386  */
 3387 static VALUE
 3388 proc_compose_to_left(VALUE self, VALUE g)
 3389 {
 3390     return rb_proc_compose_to_left(self, to_callable(g));
 3391 }
 3392 
 3393 static VALUE
 3394 rb_proc_compose_to_left(VALUE self, VALUE g)
 3395 {
 3396     VALUE proc, args, procs[2];
 3397     rb_proc_t *procp;
 3398     int is_lambda;
 3399 
 3400     procs[0] = self;
 3401     procs[1] = g;
 3402     args = rb_ary_tmp_new_from_values(0, 2, procs);
 3403 
 3404     GetProcPtr(self, procp);
 3405     is_lambda = procp->is_lambda;
 3406 
 3407     proc = rb_proc_new(compose, args);
 3408     GetProcPtr(proc, procp);
 3409     procp->is_lambda = is_lambda;
 3410 
 3411     return proc;
 3412 }
 3413 
 3414 /*
 3415  *  call-seq:
 3416  *     prc >> g -> a_proc
 3417  *
 3418  *  Returns a proc that is the composition of this proc and the given <i>g</i>.
 3419  *  The returned proc takes a variable number of arguments, calls this proc with them
 3420  *  then calls <i>g</i> with the result.
 3421  *
 3422  *     f = proc {|x| x * x }
 3423  *     g = proc {|x| x + x }
 3424  *     p (f >> g).call(2) #=> 8
 3425  *
 3426  *  <i>g</i> could be other Proc, or Method, or any other object responding to
 3427  *  +call+ method:
 3428  *
 3429  *     class Parser
 3430  *       def self.call(text)
 3431  *          # ...some complicated parsing logic...
 3432  *       end
 3433  *     end
 3434  *
 3435  *     pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
 3436  *     pipeline.call('data.json')
 3437  *
 3438  *  See also Method#>> and Method#<<.
 3439  */
 3440 static VALUE
 3441 proc_compose_to_right(VALUE self, VALUE g)
 3442 {
 3443     return rb_proc_compose_to_right(self, to_callable(g));
 3444 }
 3445 
 3446 static VALUE
 3447 rb_proc_compose_to_right(VALUE self, VALUE g)
 3448 {
 3449     VALUE proc, args, procs[2];
 3450     rb_proc_t *procp;
 3451     int is_lambda;
 3452 
 3453     procs[0] = g;
 3454     procs[1] = self;
 3455     args = rb_ary_tmp_new_from_values(0, 2, procs);
 3456 
 3457     GetProcPtr(self, procp);
 3458     is_lambda = procp->is_lambda;
 3459 
 3460     proc = rb_proc_new(compose, args);
 3461     GetProcPtr(proc, procp);
 3462     procp->is_lambda = is_lambda;
 3463 
 3464     return proc;
 3465 }
 3466 
 3467 /*
 3468  *  call-seq:
 3469  *     meth << g -> a_proc
 3470  *
 3471  *  Returns a proc that is the composition of this method and the given <i>g</i>.
 3472  *  The returned proc takes a variable number of arguments, calls <i>g</i> with them
 3473  *  then calls this method with the result.
 3474  *
 3475  *     def f(x)
 3476  *       x * x
 3477  *     end
 3478  *
 3479  *     f = self.method(:f)
 3480  *     g = proc {|x| x + x }
 3481  *     p (f << g).call(2) #=> 16
 3482  */
 3483 static VALUE
 3484 rb_method_compose_to_left(VALUE self, VALUE g)
 3485 {
 3486     g = to_callable(g);
 3487     self = method_to_proc(self);
 3488     return proc_compose_to_left(self, g);
 3489 }
 3490 
 3491 /*
 3492  *  call-seq:
 3493  *     meth >> g -> a_proc
 3494  *
 3495  *  Returns a proc that is the composition of this method and the given <i>g</i>.
 3496  *  The returned proc takes a variable number of arguments, calls this method
 3497  *  with them then calls <i>g</i> with the result.
 3498  *
 3499  *     def f(x)
 3500  *       x * x
 3501  *     end
 3502  *
 3503  *     f = self.method(:f)
 3504  *     g = proc {|x| x + x }
 3505  *     p (f >> g).call(2) #=> 8
 3506  */
 3507 static VALUE
 3508 rb_method_compose_to_right(VALUE self, VALUE g)
 3509 {
 3510     g = to_callable(g);
 3511     self = method_to_proc(self);
 3512     return proc_compose_to_right(self, g);
 3513 }
 3514 
 3515 /*
 3516  *  call-seq:
 3517  *     proc.ruby2_keywords -> proc
 3518  *
 3519  *  Marks the proc as passing keywords through a normal argument splat.
 3520  *  This should only be called on procs that accept an argument splat
 3521  *  (<tt>*args</tt>) but not explicit keywords or a keyword splat.  It
 3522  *  marks the proc such that if the proc is called with keyword arguments,
 3523  *  the final hash argument is marked with a special flag such that if it
 3524  *  is the final element of a normal argument splat to another method call,
 3525  *  and that method call does not include explicit keywords or a keyword
 3526  *  splat, the final element is interpreted as keywords.  In other words,
 3527  *  keywords will be passed through the proc to other methods.
 3528  *
 3529  *  This should only be used for procs that delegate keywords to another
 3530  *  method, and only for backwards compatibility with Ruby versions before
 3531  *  2.7.
 3532  *
 3533  *  This method will probably be removed at some point, as it exists only
 3534  *  for backwards compatibility. As it does not exist in Ruby versions
 3535  *  before 2.7, check that the proc responds to this method before calling
 3536  *  it. Also, be aware that if this method is removed, the behavior of the
 3537  *  proc will change so that it does not pass through keywords.
 3538  *
 3539  *    module Mod
 3540  *      foo = ->(meth, *args, &block) do
 3541  *        send(:"do_#{meth}", *args, &block)
 3542  *      end
 3543  *      foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
 3544  *    end
 3545  */
 3546 
 3547 static VALUE
 3548 proc_ruby2_keywords(VALUE procval)
 3549 {
 3550     rb_proc_t *proc;
 3551     GetProcPtr(procval, proc);
 3552 
 3553     rb_check_frozen(procval);
 3554 
 3555     if (proc->is_from_method) {
 3556             rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
 3557             return procval;
 3558     }
 3559 
 3560     switch (proc->block.type) {
 3561       case block_type_iseq:
 3562         if (proc->block.as.captured.code.iseq->body->param.flags.has_rest &&
 3563                 !proc->block.as.captured.code.iseq->body->param.flags.has_kw &&
 3564                 !proc->block.as.captured.code.iseq->body->param.flags.has_kwrest) {
 3565             proc->block.as.captured.code.iseq->body->param.flags.ruby2_keywords = 1;
 3566         }
 3567         else {
 3568             rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
 3569         }
 3570         break;
 3571       default:
 3572         rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
 3573         break;
 3574     }
 3575 
 3576     return procval;
 3577 }
 3578 
 3579 /*
 3580  *  Document-class: LocalJumpError
 3581  *
 3582  *  Raised when Ruby can't yield as requested.
 3583  *
 3584  *  A typical scenario is attempting to yield when no block is given:
 3585  *
 3586  *     def call_block
 3587  *       yield 42
 3588  *     end
 3589  *     call_block
 3590  *
 3591  *  <em>raises the exception:</em>
 3592  *
 3593  *     LocalJumpError: no block given (yield)
 3594  *
 3595  *  A more subtle example:
 3596  *
 3597  *     def get_me_a_return
 3598  *       Proc.new { return 42 }
 3599  *     end
 3600  *     get_me_a_return.call
 3601  *
 3602  *  <em>raises the exception:</em>
 3603  *
 3604  *     LocalJumpError: unexpected return
 3605  */
 3606 
 3607 /*
 3608  *  Document-class: SystemStackError
 3609  *
 3610  *  Raised in case of a stack overflow.
 3611  *
 3612  *     def me_myself_and_i
 3613  *       me_myself_and_i
 3614  *     end
 3615  *     me_myself_and_i
 3616  *
 3617  *  <em>raises the exception:</em>
 3618  *
 3619  *    SystemStackError: stack level too deep
 3620  */
 3621 
 3622 /*
 3623  *  Document-class: Proc
 3624  *
 3625  * A +Proc+ object is an encapsulation of a block of code, which can be stored
 3626  * in a local variable, passed to a method or another Proc, and can be called.
 3627  * Proc is an essential concept in Ruby and a core of its functional
 3628  * programming features.
 3629  *
 3630  *      square = Proc.new {|x| x**2 }
 3631  *
 3632  *      square.call(3)  #=> 9
 3633  *      # shorthands:
 3634  *      square.(3)      #=> 9
 3635  *      square[3]       #=> 9
 3636  *
 3637  * Proc objects are _closures_, meaning they remember and can use the entire
 3638  * context in which they were created.
 3639  *
 3640  *     def gen_times(factor)
 3641  *       Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
 3642  *     end
 3643  *
 3644  *     times3 = gen_times(3)
 3645  *     times5 = gen_times(5)
 3646  *
 3647  *     times3.call(12)               #=> 36
 3648  *     times5.call(5)                #=> 25
 3649  *     times3.call(times5.call(4))   #=> 60
 3650  *
 3651  * == Creation
 3652  *
 3653  * There are several methods to create a Proc
 3654  *
 3655  * * Use the Proc class constructor:
 3656  *
 3657  *      proc1 = Proc.new {|x| x**2 }
 3658  *
 3659  * * Use the Kernel#proc method as a shorthand of Proc.new:
 3660  *
 3661  *      proc2 = proc {|x| x**2 }
 3662  *
 3663  * * Receiving a block of code into proc argument (note the <code>&</code>):
 3664  *
 3665  *      def make_proc(&block)
 3666  *        block
 3667  *      end
 3668  *
 3669  *      proc3 = make_proc {|x| x**2 }
 3670  *
 3671  * * Construct a proc with lambda semantics using the Kernel#lambda method
 3672  *   (see below for explanations about lambdas):
 3673  *
 3674  *      lambda1 = lambda {|x| x**2 }
 3675  *
 3676  * * Use the Lambda literal syntax (also constructs a proc with lambda semantics):
 3677  *
 3678  *      lambda2 = ->(x) { x**2 }
 3679  *
 3680  * == Lambda and non-lambda semantics
 3681  *
 3682  * Procs are coming in two flavors: lambda and non-lambda (regular procs).
 3683  * Differences are:
 3684  *
 3685  * * In lambdas, +return+ and +break+ means exit from this lambda;
 3686  * * In non-lambda procs, +return+ means exit from embracing method
 3687  *   (and will throw +LocalJumpError+ if invoked outside the method);
 3688  * * In non-lambda procs, +break+ means exit from the method which the block given for.
 3689  *   (and will throw +LocalJumpError+ if invoked after the method returns);
 3690  * * In lambdas, arguments are treated in the same way as in methods: strict,
 3691  *   with +ArgumentError+ for mismatching argument number,
 3692  *   and no additional argument processing;
 3693  * * Regular procs accept arguments more generously: missing arguments
 3694  *   are filled with +nil+, single Array arguments are deconstructed if the
 3695  *   proc has multiple arguments, and there is no error raised on extra
 3696  *   arguments.
 3697  *
 3698  * Examples:
 3699  *
 3700  *      # +return+ in non-lambda proc, +b+, exits +m2+.
 3701  *      # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
 3702  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
 3703  *      #=> []
 3704  *
 3705  *      # +break+ in non-lambda proc, +b+, exits +m1+.
 3706  *      # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
 3707  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
 3708  *      #=> [:m2]
 3709  *
 3710  *      # +next+ in non-lambda proc, +b+, exits the block.
 3711  *      # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
 3712  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
 3713  *      #=> [:m1, :m2]
 3714  *
 3715  *      # Using +proc+ method changes the behavior as follows because
 3716  *      # The block is given for +proc+ method and embraced by +m2+.
 3717  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
 3718  *      #=> []
 3719  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
 3720  *      # break from proc-closure (LocalJumpError)
 3721  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
 3722  *      #=> [:m1, :m2]
 3723  *
 3724  *      # +return+, +break+ and +next+ in the stubby lambda exits the block.
 3725  *      # (+lambda+ method behaves same.)
 3726  *      # (The block is given for stubby lambda syntax and embraced by +m2+.)
 3727  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
 3728  *      #=> [:m1, :m2]
 3729  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
 3730  *      #=> [:m1, :m2]
 3731  *      $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
 3732  *      #=> [:m1, :m2]
 3733  *
 3734  *      p = proc {|x, y| "x=#{x}, y=#{y}" }
 3735  *      p.call(1, 2)      #=> "x=1, y=2"
 3736  *      p.call([1, 2])    #=> "x=1, y=2", array deconstructed
 3737  *      p.call(1, 2, 8)   #=> "x=1, y=2", extra argument discarded
 3738  *      p.call(1)         #=> "x=1, y=", nil substituted instead of error
 3739  *
 3740  *      l = lambda {|x, y| "x=#{x}, y=#{y}" }
 3741  *      l.call(1, 2)      #=> "x=1, y=2"
 3742  *      l.call([1, 2])    # ArgumentError: wrong number of arguments (given 1, expected 2)
 3743  *      l.call(1, 2, 8)   # ArgumentError: wrong number of arguments (given 3, expected 2)
 3744  *      l.call(1)         # ArgumentError: wrong number of arguments (given 1, expected 2)
 3745  *
 3746  *      def test_return
 3747  *        -> { return 3 }.call      # just returns from lambda into method body
 3748  *        proc { return 4 }.call    # returns from method
 3749  *        return 5
 3750  *      end
 3751  *
 3752  *      test_return # => 4, return from proc
 3753  *
 3754  * Lambdas are useful as self-sufficient functions, in particular useful as
 3755  * arguments to higher-order functions, behaving exactly like Ruby methods.
 3756  *
 3757  * Procs are useful for implementing iterators:
 3758  *
 3759  *      def test
 3760  *        [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
 3761  *                                  #  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 3762  *      end
 3763  *
 3764  * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
 3765  * which means that the internal arrays will be deconstructed to pairs of
 3766  * arguments, and +return+ will exit from the method +test+. That would
 3767  * not be possible with a stricter lambda.
 3768  *
 3769  * You can tell a lambda from a regular proc by using the #lambda? instance method.
 3770  *
 3771  * Lambda semantics is typically preserved during the proc lifetime, including
 3772  * <code>&</code>-deconstruction to a block of code:
 3773  *
 3774  *      p = proc {|x, y| x }
 3775  *      l = lambda {|x, y| x }
 3776  *      [[1, 2], [3, 4]].map(&p) #=> [1, 2]
 3777  *      [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
 3778  *
 3779  * The only exception is dynamic method definition: even if defined by
 3780  * passing a non-lambda proc, methods still have normal semantics of argument
 3781  * checking.
 3782  *
 3783  *   class C
 3784  *     define_method(:e, &proc {})
 3785  *   end
 3786  *   C.new.e(1,2)       #=> ArgumentError
 3787  *   C.new.method(:e).to_proc.lambda?   #=> true
 3788  *
 3789  * This exception ensures that methods never have unusual argument passing
 3790  * conventions, and makes it easy to have wrappers defining methods that
 3791  * behave as usual.
 3792  *
 3793  *   class C
 3794  *     def self.def2(name, &body)
 3795  *       define_method(name, &body)
 3796  *     end
 3797  *
 3798  *     def2(:f) {}
 3799  *   end
 3800  *   C.new.f(1,2)       #=> ArgumentError
 3801  *
 3802  * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
 3803  * yet defines a method which has normal semantics.
 3804  *
 3805  * == Conversion of other objects to procs
 3806  *
 3807  * Any object that implements the +to_proc+ method can be converted into
 3808  * a proc by the <code>&</code> operator, and therefore con be
 3809  * consumed by iterators.
 3810  *
 3811 
 3812  *      class Greeter
 3813  *        def initialize(greeting)
 3814  *          @greeting = greeting
 3815  *        end
 3816  *
 3817  *        def to_proc
 3818  *          proc {|name| "#{@greeting}, #{name}!" }
 3819  *        end
 3820  *      end
 3821  *
 3822  *      hi = Greeter.new("Hi")
 3823  *      hey = Greeter.new("Hey")
 3824  *      ["Bob", "Jane"].map(&hi)    #=> ["Hi, Bob!", "Hi, Jane!"]
 3825  *      ["Bob", "Jane"].map(&hey)   #=> ["Hey, Bob!", "Hey, Jane!"]
 3826  *
 3827  * Of the Ruby core classes, this method is implemented by Symbol,
 3828  * Method, and Hash.
 3829  *
 3830  *      :to_s.to_proc.call(1)           #=> "1"
 3831  *      [1, 2].map(&:to_s)              #=> ["1", "2"]
 3832  *
 3833  *      method(:puts).to_proc.call(1)   # prints 1
 3834  *      [1, 2].each(&method(:puts))     # prints 1, 2
 3835  *
 3836  *      {test: 1}.to_proc.call(:test)       #=> 1
 3837  *      %i[test many keys].map(&{test: 1})  #=> [1, nil, nil]
 3838  *
 3839  * == Orphaned Proc
 3840  *
 3841  * +return+ and +break+ in a block exit a method.
 3842  * If a Proc object is generated from the block and the Proc object
 3843  * survives until the method is returned, +return+ and +break+ cannot work.
 3844  * In such case, +return+ and +break+ raises LocalJumpError.
 3845  * A Proc object in such situation is called as orphaned Proc object.
 3846  *
 3847  * Note that the method to exit is different for +return+ and +break+.
 3848  * There is a situation that orphaned for +break+ but not orphaned for +return+.
 3849  *
 3850  *     def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
 3851  *     def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
 3852  *
 3853  *     def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
 3854  *     def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
 3855  *
 3856  *     def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
 3857  *     def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
 3858  *
 3859  * Since +return+ and +break+ exits the block itself in lambdas,
 3860  * lambdas cannot be orphaned.
 3861  *
 3862  * == Numbered parameters
 3863  *
 3864  * Numbered parameters are implicitly defined block parameters intended to
 3865  * simplify writing short blocks:
 3866  *
 3867  *     # Explicit parameter:
 3868  *     %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
 3869  *     (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
 3870  *
 3871  *     # Implicit parameter:
 3872  *     %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
 3873  *     (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
 3874  *
 3875  * Parameter names from +_1+ to +_9+ are supported:
 3876  *
 3877  *     [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
 3878  *     # => [120, 150, 180]
 3879  *
 3880  * Though, it is advised to resort to them wisely, probably limiting
 3881  * yourself to +_1+ and +_2+, and to one-line blocks.
 3882  *
 3883  * Numbered parameters can't be used together with explicitly named
 3884  * ones:
 3885  *
 3886  *     [10, 20, 30].map { |x| _1**2 }
 3887  *     # SyntaxError (ordinary parameter is defined)
 3888  *
 3889  * To avoid conflicts, naming local variables or method
 3890  * arguments +_1+, +_2+ and so on, causes a warning.
 3891  *
 3892  *     _1 = 'test'
 3893  *     # warning: `_1' is reserved as numbered parameter
 3894  *
 3895  * Using implicit numbered parameters affects block's arity:
 3896  *
 3897  *     p = proc { _1 + _2 }
 3898  *     l = lambda { _1 + _2 }
 3899  *     p.parameters     # => [[:opt, :_1], [:opt, :_2]]
 3900  *     p.arity          # => 2
 3901  *     l.parameters     # => [[:req, :_1], [:req, :_2]]
 3902  *     l.arity          # => 2
 3903  *
 3904  * Blocks with numbered parameters can't be nested:
 3905  *
 3906  *     %w[test me].each { _1.each_char { p _1 } }
 3907  *     # SyntaxError (numbered parameter is already used in outer block here)
 3908  *     # %w[test me].each { _1.each_char { p _1 } }
 3909  *     #                    ^~
 3910  *
 3911  * Numbered parameters were introduced in Ruby 2.7.
 3912  */
 3913 
 3914 
 3915 void
 3916 Init_Proc(void)
 3917 {
 3918 #undef rb_intern
 3919     /* Proc */
 3920     rb_cProc = rb_define_class("Proc", rb_cObject);
 3921     rb_undef_alloc_func(rb_cProc);
 3922     rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
 3923 
 3924     rb_add_method(rb_cProc, idCall, VM_METHOD_TYPE_OPTIMIZED,
 3925           (void *)OPTIMIZED_METHOD_TYPE_CALL, METHOD_VISI_PUBLIC);
 3926     rb_add_method(rb_cProc, rb_intern("[]"), VM_METHOD_TYPE_OPTIMIZED,
 3927           (void *)OPTIMIZED_METHOD_TYPE_CALL, METHOD_VISI_PUBLIC);
 3928     rb_add_method(rb_cProc, rb_intern("==="), VM_METHOD_TYPE_OPTIMIZED,
 3929           (void *)OPTIMIZED_METHOD_TYPE_CALL, METHOD_VISI_PUBLIC);
 3930     rb_add_method(rb_cProc, rb_intern("yield"), VM_METHOD_TYPE_OPTIMIZED,
 3931           (void *)OPTIMIZED_METHOD_TYPE_CALL, METHOD_VISI_PUBLIC);
 3932 
 3933 #if 0 /* for RDoc */
 3934     rb_define_method(rb_cProc, "call", proc_call, -1);
 3935     rb_define_method(rb_cProc, "[]", proc_call, -1);
 3936     rb_define_method(rb_cProc, "===", proc_call, -1);
 3937     rb_define_method(rb_cProc, "yield", proc_call, -1);
 3938 #endif
 3939 
 3940     rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
 3941     rb_define_method(rb_cProc, "arity", proc_arity, 0);
 3942     rb_define_method(rb_cProc, "clone", proc_clone, 0);
 3943     rb_define_method(rb_cProc, "dup", rb_proc_dup, 0);
 3944     rb_define_method(rb_cProc, "hash", proc_hash, 0);
 3945     rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
 3946     rb_define_alias(rb_cProc, "inspect", "to_s");
 3947     rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
 3948     rb_define_method(rb_cProc, "binding", proc_binding, 0);
 3949     rb_define_method(rb_cProc, "curry", proc_curry, -1);
 3950     rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
 3951     rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
 3952     rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
 3953     rb_define_method(rb_cProc, "parameters", rb_proc_parameters, 0);
 3954     rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
 3955 
 3956     /* Exceptions */
 3957     rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
 3958     rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
 3959     rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
 3960 
 3961     rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
 3962     rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
 3963 
 3964     /* utility functions */
 3965     rb_define_global_function("proc", f_proc, 0);
 3966     rb_define_global_function("lambda", f_lambda, 0);
 3967 
 3968     /* Method */
 3969     rb_cMethod = rb_define_class("Method", rb_cObject);
 3970     rb_undef_alloc_func(rb_cMethod);
 3971     rb_undef_method(CLASS_OF(rb_cMethod), "new");
 3972     rb_define_method(rb_cMethod, "==", method_eq, 1);
 3973     rb_define_method(rb_cMethod, "eql?", method_eq, 1);
 3974     rb_define_method(rb_cMethod, "hash", method_hash, 0);
 3975     rb_define_method(rb_cMethod, "clone", method_clone, 0);
 3976     rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
 3977     rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
 3978     rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
 3979     rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
 3980     rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
 3981     rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
 3982     rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
 3983     rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
 3984     rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
 3985     rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
 3986     rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
 3987     rb_define_method(rb_cMethod, "name", method_name, 0);
 3988     rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
 3989     rb_define_method(rb_cMethod, "owner", method_owner, 0);
 3990     rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
 3991     rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
 3992     rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
 3993     rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
 3994     rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
 3995     rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
 3996     rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
 3997 
 3998     /* UnboundMethod */
 3999     rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
 4000     rb_undef_alloc_func(rb_cUnboundMethod);
 4001     rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
 4002     rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
 4003     rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
 4004     rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
 4005     rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
 4006     rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
 4007     rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
 4008     rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
 4009     rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
 4010     rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
 4011     rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
 4012     rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
 4013     rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
 4014     rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
 4015     rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
 4016     rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
 4017 
 4018     /* Module#*_method */
 4019     rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
 4020     rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
 4021     rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
 4022 
 4023     /* Kernel */
 4024     rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
 4025 
 4026     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
 4027                  "define_method", top_define_method, -1);
 4028 }
 4029 
 4030 /*
 4031  *  Objects of class Binding encapsulate the execution context at some
 4032  *  particular place in the code and retain this context for future
 4033  *  use. The variables, methods, value of <code>self</code>, and
 4034  *  possibly an iterator block that can be accessed in this context
 4035  *  are all retained. Binding objects can be created using
 4036  *  Kernel#binding, and are made available to the callback of
 4037  *  Kernel#set_trace_func and instances of TracePoint.
 4038  *
 4039  *  These binding objects can be passed as the second argument of the
 4040  *  Kernel#eval method, establishing an environment for the
 4041  *  evaluation.
 4042  *
 4043  *     class Demo
 4044  *       def initialize(n)
 4045  *         @secret = n
 4046  *       end
 4047  *       def get_binding
 4048  *         binding
 4049  *       end
 4050  *     end
 4051  *
 4052  *     k1 = Demo.new(99)
 4053  *     b1 = k1.get_binding
 4054  *     k2 = Demo.new(-3)
 4055  *     b2 = k2.get_binding
 4056  *
 4057  *     eval("@secret", b1)   #=> 99
 4058  *     eval("@secret", b2)   #=> -3
 4059  *     eval("@secret")       #=> nil
 4060  *
 4061  *  Binding objects have no class-specific methods.
 4062  *
 4063  */
 4064 
 4065 void
 4066 Init_Binding(void)
 4067 {
 4068     rb_cBinding = rb_define_class("Binding", rb_cObject);
 4069     rb_undef_alloc_func(rb_cBinding);
 4070     rb_undef_method(CLASS_OF(rb_cBinding), "new");
 4071     rb_define_method(rb_cBinding, "clone", binding_clone, 0);
 4072     rb_define_method(rb_cBinding, "dup", binding_dup, 0);
 4073     rb_define_method(rb_cBinding, "eval", bind_eval, -1);
 4074     rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
 4075     rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
 4076     rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
 4077     rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
 4078     rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
 4079     rb_define_method(rb_cBinding, "source_location", bind_location, 0);
 4080     rb_define_global_function("binding", rb_f_binding, 0);
 4081 }