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