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