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