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