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