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