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