Ruby: proc.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

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