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