Ruby: proc.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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