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