* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / proc.c
blob6a04a6a958ec6e53dbdd1b7d36a0b2acb224d30b
1 /**********************************************************************
3 proc.c - Proc, Binding, Env
5 $Author$
6 created at: Wed Jan 17 12:13:14 2007
8 Copyright (C) 2004-2007 Koichi Sasada
10 **********************************************************************/
12 #include "eval_intern.h"
13 #include "gc.h"
14 #include "internal.h"
15 #include "internal/class.h"
16 #include "internal/error.h"
17 #include "internal/eval.h"
18 #include "internal/object.h"
19 #include "internal/proc.h"
20 #include "internal/symbol.h"
21 #include "method.h"
22 #include "iseq.h"
23 #include "vm_core.h"
24 #include "yjit.h"
26 #if !defined(__GNUC__) || __GNUC__ < 5 || defined(__MINGW32__)
27 # define NO_CLOBBERED(v) (*(volatile VALUE *)&(v))
28 #else
29 # define NO_CLOBBERED(v) (v)
30 #endif
32 #define UPDATE_TYPED_REFERENCE(_type, _ref) *(_type*)&_ref = (_type)rb_gc_location((VALUE)_ref)
33 #define UPDATE_REFERENCE(_ref) UPDATE_TYPED_REFERENCE(VALUE, _ref)
35 const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
37 struct METHOD {
38 const VALUE recv;
39 const VALUE klass;
40 const VALUE iclass;
41 const rb_method_entry_t * const me;
42 /* for bound methods, `me' should be rb_callable_method_entry_t * */
43 rb_method_visibility_t visibility;
46 VALUE rb_cUnboundMethod;
47 VALUE rb_cMethod;
48 VALUE rb_cBinding;
49 VALUE rb_cProc;
51 static rb_block_call_func bmcall;
52 static int method_arity(VALUE);
53 static int method_min_max_arity(VALUE, int *max);
54 static VALUE proc_binding(VALUE self);
56 #define attached id__attached__
58 /* Proc */
60 #define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
62 /* :FIXME: The way procs are cloned has been historically different from the
63 * way everything else are. @shyouhei is not sure for the intention though.
65 #undef CLONESETUP
66 static inline void
67 CLONESETUP(VALUE clone, VALUE obj)
69 RBIMPL_ASSERT_OR_ASSUME(! RB_SPECIAL_CONST_P(obj));
70 RBIMPL_ASSERT_OR_ASSUME(! RB_SPECIAL_CONST_P(clone));
72 const VALUE flags = RUBY_FL_PROMOTED0 | RUBY_FL_PROMOTED1 | RUBY_FL_FINALIZE;
73 rb_obj_setup(clone, rb_singleton_class_clone(obj),
74 RB_FL_TEST_RAW(obj, ~flags));
75 rb_singleton_class_attached(RBASIC_CLASS(clone), clone);
76 if (RB_FL_TEST(obj, RUBY_FL_EXIVAR)) rb_copy_generic_ivar(clone, obj);
79 static void
80 block_mark(const struct rb_block *block)
82 switch (vm_block_type(block)) {
83 case block_type_iseq:
84 case block_type_ifunc:
86 const struct rb_captured_block *captured = &block->as.captured;
87 RUBY_MARK_MOVABLE_UNLESS_NULL(captured->self);
88 RUBY_MARK_MOVABLE_UNLESS_NULL((VALUE)captured->code.val);
89 if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) {
90 rb_gc_mark(VM_ENV_ENVVAL(captured->ep));
93 break;
94 case block_type_symbol:
95 RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.symbol);
96 break;
97 case block_type_proc:
98 RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.proc);
99 break;
103 static void
104 block_compact(struct rb_block *block)
106 switch (block->type) {
107 case block_type_iseq:
108 case block_type_ifunc:
110 struct rb_captured_block *captured = &block->as.captured;
111 captured->self = rb_gc_location(captured->self);
112 captured->code.val = rb_gc_location(captured->code.val);
114 break;
115 case block_type_symbol:
116 block->as.symbol = rb_gc_location(block->as.symbol);
117 break;
118 case block_type_proc:
119 block->as.proc = rb_gc_location(block->as.proc);
120 break;
124 static void
125 proc_compact(void *ptr)
127 rb_proc_t *proc = ptr;
128 block_compact((struct rb_block *)&proc->block);
131 static void
132 proc_mark(void *ptr)
134 rb_proc_t *proc = ptr;
135 block_mark(&proc->block);
136 RUBY_MARK_LEAVE("proc");
139 typedef struct {
140 rb_proc_t basic;
141 VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
142 } cfunc_proc_t;
144 static size_t
145 proc_memsize(const void *ptr)
147 const rb_proc_t *proc = ptr;
148 if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1)
149 return sizeof(cfunc_proc_t);
150 return sizeof(rb_proc_t);
153 static const rb_data_type_t proc_data_type = {
154 "proc",
156 proc_mark,
157 RUBY_TYPED_DEFAULT_FREE,
158 proc_memsize,
159 proc_compact,
161 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
164 VALUE
165 rb_proc_alloc(VALUE klass)
167 rb_proc_t *proc;
168 return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
171 VALUE
172 rb_obj_is_proc(VALUE proc)
174 return RBOOL(rb_typeddata_is_kind_of(proc, &proc_data_type));
177 /* :nodoc: */
178 static VALUE
179 proc_clone(VALUE self)
181 VALUE procval = rb_proc_dup(self);
182 CLONESETUP(procval, self);
183 return procval;
187 * call-seq:
188 * prc.lambda? -> true or false
190 * Returns +true+ if a Proc object is lambda.
191 * +false+ if non-lambda.
193 * The lambda-ness affects argument handling and the behavior of +return+ and +break+.
195 * A Proc object generated by +proc+ ignores extra arguments.
197 * proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
199 * It provides +nil+ for missing arguments.
201 * proc {|a,b| [a,b] }.call(1) #=> [1,nil]
203 * It expands a single array argument.
205 * proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
207 * A Proc object generated by +lambda+ doesn't have such tricks.
209 * lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError
210 * lambda {|a,b| [a,b] }.call(1) #=> ArgumentError
211 * lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
213 * Proc#lambda? is a predicate for the tricks.
214 * It returns +true+ if no tricks apply.
216 * lambda {}.lambda? #=> true
217 * proc {}.lambda? #=> false
219 * Proc.new is the same as +proc+.
221 * Proc.new {}.lambda? #=> false
223 * +lambda+, +proc+ and Proc.new preserve the tricks of
224 * a Proc object given by <code>&</code> argument.
226 * lambda(&lambda {}).lambda? #=> true
227 * proc(&lambda {}).lambda? #=> true
228 * Proc.new(&lambda {}).lambda? #=> true
230 * lambda(&proc {}).lambda? #=> false
231 * proc(&proc {}).lambda? #=> false
232 * Proc.new(&proc {}).lambda? #=> false
234 * A Proc object generated by <code>&</code> argument has the tricks
236 * def n(&b) b.lambda? end
237 * n {} #=> false
239 * The <code>&</code> argument preserves the tricks if a Proc object
240 * is given by <code>&</code> argument.
242 * n(&lambda {}) #=> true
243 * n(&proc {}) #=> false
244 * n(&Proc.new {}) #=> false
246 * A Proc object converted from a method has no tricks.
248 * def m() end
249 * method(:m).to_proc.lambda? #=> true
251 * n(&method(:m)) #=> true
252 * n(&method(:m).to_proc) #=> true
254 * +define_method+ is treated the same as method definition.
255 * The defined method has no tricks.
257 * class C
258 * define_method(:d) {}
259 * end
260 * C.new.d(1,2) #=> ArgumentError
261 * C.new.method(:d).to_proc.lambda? #=> true
263 * +define_method+ always defines a method without the tricks,
264 * even if a non-lambda Proc object is given.
265 * This is the only exception for which the tricks are not preserved.
267 * class C
268 * define_method(:e, &proc {})
269 * end
270 * C.new.e(1,2) #=> ArgumentError
271 * C.new.method(:e).to_proc.lambda? #=> true
273 * This exception ensures that methods never have tricks
274 * and makes it easy to have wrappers to define methods that behave as usual.
276 * class C
277 * def self.def2(name, &body)
278 * define_method(name, &body)
279 * end
281 * def2(:f) {}
282 * end
283 * C.new.f(1,2) #=> ArgumentError
285 * The wrapper <i>def2</i> defines a method which has no tricks.
289 VALUE
290 rb_proc_lambda_p(VALUE procval)
292 rb_proc_t *proc;
293 GetProcPtr(procval, proc);
295 return RBOOL(proc->is_lambda);
298 /* Binding */
300 static void
301 binding_free(void *ptr)
303 RUBY_FREE_ENTER("binding");
304 ruby_xfree(ptr);
305 RUBY_FREE_LEAVE("binding");
308 static void
309 binding_mark(void *ptr)
311 rb_binding_t *bind = ptr;
313 RUBY_MARK_ENTER("binding");
314 block_mark(&bind->block);
315 rb_gc_mark_movable(bind->pathobj);
316 RUBY_MARK_LEAVE("binding");
319 static void
320 binding_compact(void *ptr)
322 rb_binding_t *bind = ptr;
324 block_compact((struct rb_block *)&bind->block);
325 UPDATE_REFERENCE(bind->pathobj);
328 static size_t
329 binding_memsize(const void *ptr)
331 return sizeof(rb_binding_t);
334 const rb_data_type_t ruby_binding_data_type = {
335 "binding",
337 binding_mark,
338 binding_free,
339 binding_memsize,
340 binding_compact,
342 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
345 VALUE
346 rb_binding_alloc(VALUE klass)
348 VALUE obj;
349 rb_binding_t *bind;
350 obj = TypedData_Make_Struct(klass, rb_binding_t, &ruby_binding_data_type, bind);
351 #if YJIT_STATS
352 rb_yjit_collect_binding_alloc();
353 #endif
354 return obj;
358 /* :nodoc: */
359 static VALUE
360 binding_dup(VALUE self)
362 VALUE bindval = rb_binding_alloc(rb_cBinding);
363 rb_binding_t *src, *dst;
364 GetBindingPtr(self, src);
365 GetBindingPtr(bindval, dst);
366 rb_vm_block_copy(bindval, &dst->block, &src->block);
367 RB_OBJ_WRITE(bindval, &dst->pathobj, src->pathobj);
368 dst->first_lineno = src->first_lineno;
369 return bindval;
372 /* :nodoc: */
373 static VALUE
374 binding_clone(VALUE self)
376 VALUE bindval = binding_dup(self);
377 CLONESETUP(bindval, self);
378 return bindval;
381 VALUE
382 rb_binding_new(void)
384 rb_execution_context_t *ec = GET_EC();
385 return rb_vm_make_binding(ec, ec->cfp);
389 * call-seq:
390 * binding -> a_binding
392 * Returns a +Binding+ object, describing the variable and
393 * method bindings at the point of call. This object can be used when
394 * calling +eval+ to execute the evaluated command in this
395 * environment. See also the description of class +Binding+.
397 * def get_binding(param)
398 * binding
399 * end
400 * b = get_binding("hello")
401 * eval("param", b) #=> "hello"
404 static VALUE
405 rb_f_binding(VALUE self)
407 return rb_binding_new();
411 * call-seq:
412 * binding.eval(string [, filename [,lineno]]) -> obj
414 * Evaluates the Ruby expression(s) in <em>string</em>, in the
415 * <em>binding</em>'s context. If the optional <em>filename</em> and
416 * <em>lineno</em> parameters are present, they will be used when
417 * reporting syntax errors.
419 * def get_binding(param)
420 * binding
421 * end
422 * b = get_binding("hello")
423 * b.eval("param") #=> "hello"
426 static VALUE
427 bind_eval(int argc, VALUE *argv, VALUE bindval)
429 VALUE args[4];
431 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
432 args[1] = bindval;
433 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
436 static const VALUE *
437 get_local_variable_ptr(const rb_env_t **envp, ID lid)
439 const rb_env_t *env = *envp;
440 do {
441 if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) {
442 if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) {
443 return NULL;
446 const rb_iseq_t *iseq = env->iseq;
447 unsigned int i;
449 VM_ASSERT(rb_obj_is_iseq((VALUE)iseq));
451 for (i=0; i<iseq->body->local_table_size; i++) {
452 if (iseq->body->local_table[i] == lid) {
453 if (iseq->body->local_iseq == iseq &&
454 iseq->body->param.flags.has_block &&
455 (unsigned int)iseq->body->param.block_start == i) {
456 const VALUE *ep = env->ep;
457 if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) {
458 RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep)));
459 VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM);
463 *envp = env;
464 return &env->env[i];
468 else {
469 *envp = NULL;
470 return NULL;
472 } while ((env = rb_vm_env_prev_env(env)) != NULL);
474 *envp = NULL;
475 return NULL;
479 * check local variable name.
480 * returns ID if it's an already interned symbol, or 0 with setting
481 * local name in String to *namep.
483 static ID
484 check_local_id(VALUE bindval, volatile VALUE *pname)
486 ID lid = rb_check_id(pname);
487 VALUE name = *pname;
489 if (lid) {
490 if (!rb_is_local_id(lid)) {
491 rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
492 bindval, ID2SYM(lid));
495 else {
496 if (!rb_is_local_name(name)) {
497 rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
498 bindval, name);
500 return 0;
502 return lid;
506 * call-seq:
507 * binding.local_variables -> Array
509 * Returns the names of the binding's local variables as symbols.
511 * def foo
512 * a = 1
513 * 2.times do |n|
514 * binding.local_variables #=> [:a, :n]
515 * end
516 * end
518 * This method is the short version of the following code:
520 * binding.eval("local_variables")
523 static VALUE
524 bind_local_variables(VALUE bindval)
526 const rb_binding_t *bind;
527 const rb_env_t *env;
529 GetBindingPtr(bindval, bind);
530 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
531 return rb_vm_env_local_variables(env);
535 * call-seq:
536 * binding.local_variable_get(symbol) -> obj
538 * Returns the value of the local variable +symbol+.
540 * def foo
541 * a = 1
542 * binding.local_variable_get(:a) #=> 1
543 * binding.local_variable_get(:b) #=> NameError
544 * end
546 * This method is the short version of the following code:
548 * binding.eval("#{symbol}")
551 static VALUE
552 bind_local_variable_get(VALUE bindval, VALUE sym)
554 ID lid = check_local_id(bindval, &sym);
555 const rb_binding_t *bind;
556 const VALUE *ptr;
557 const rb_env_t *env;
559 if (!lid) goto undefined;
561 GetBindingPtr(bindval, bind);
563 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
564 if ((ptr = get_local_variable_ptr(&env, lid)) != NULL) {
565 return *ptr;
568 sym = ID2SYM(lid);
569 undefined:
570 rb_name_err_raise("local variable `%1$s' is not defined for %2$s",
571 bindval, sym);
572 UNREACHABLE_RETURN(Qundef);
576 * call-seq:
577 * binding.local_variable_set(symbol, obj) -> obj
579 * Set local variable named +symbol+ as +obj+.
581 * def foo
582 * a = 1
583 * bind = binding
584 * bind.local_variable_set(:a, 2) # set existing local variable `a'
585 * bind.local_variable_set(:b, 3) # create new local variable `b'
586 * # `b' exists only in binding
588 * p bind.local_variable_get(:a) #=> 2
589 * p bind.local_variable_get(:b) #=> 3
590 * p a #=> 2
591 * p b #=> NameError
592 * end
594 * This method behaves similarly to the following code:
596 * binding.eval("#{symbol} = #{obj}")
598 * if +obj+ can be dumped in Ruby code.
600 static VALUE
601 bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
603 ID lid = check_local_id(bindval, &sym);
604 rb_binding_t *bind;
605 const VALUE *ptr;
606 const rb_env_t *env;
608 if (!lid) lid = rb_intern_str(sym);
610 GetBindingPtr(bindval, bind);
611 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
612 if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) {
613 /* not found. create new env */
614 ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
615 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
618 #if YJIT_STATS
619 rb_yjit_collect_binding_set();
620 #endif
622 RB_OBJ_WRITE(env, ptr, val);
624 return val;
628 * call-seq:
629 * binding.local_variable_defined?(symbol) -> obj
631 * Returns +true+ if a local variable +symbol+ exists.
633 * def foo
634 * a = 1
635 * binding.local_variable_defined?(:a) #=> true
636 * binding.local_variable_defined?(:b) #=> false
637 * end
639 * This method is the short version of the following code:
641 * binding.eval("defined?(#{symbol}) == 'local-variable'")
644 static VALUE
645 bind_local_variable_defined_p(VALUE bindval, VALUE sym)
647 ID lid = check_local_id(bindval, &sym);
648 const rb_binding_t *bind;
649 const rb_env_t *env;
651 if (!lid) return Qfalse;
653 GetBindingPtr(bindval, bind);
654 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
655 return RBOOL(get_local_variable_ptr(&env, lid));
659 * call-seq:
660 * binding.receiver -> object
662 * Returns the bound receiver of the binding object.
664 static VALUE
665 bind_receiver(VALUE bindval)
667 const rb_binding_t *bind;
668 GetBindingPtr(bindval, bind);
669 return vm_block_self(&bind->block);
673 * call-seq:
674 * binding.source_location -> [String, Integer]
676 * Returns the Ruby source filename and line number of the binding object.
678 static VALUE
679 bind_location(VALUE bindval)
681 VALUE loc[2];
682 const rb_binding_t *bind;
683 GetBindingPtr(bindval, bind);
684 loc[0] = pathobj_path(bind->pathobj);
685 loc[1] = INT2FIX(bind->first_lineno);
687 return rb_ary_new4(2, loc);
690 static VALUE
691 cfunc_proc_new(VALUE klass, VALUE ifunc)
693 rb_proc_t *proc;
694 cfunc_proc_t *sproc;
695 VALUE procval = TypedData_Make_Struct(klass, cfunc_proc_t, &proc_data_type, sproc);
696 VALUE *ep;
698 proc = &sproc->basic;
699 vm_block_type_set(&proc->block, block_type_ifunc);
701 *(VALUE **)&proc->block.as.captured.ep = ep = sproc->env + VM_ENV_DATA_SIZE-1;
702 ep[VM_ENV_DATA_INDEX_FLAGS] = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL | VM_ENV_FLAG_ESCAPED;
703 ep[VM_ENV_DATA_INDEX_ME_CREF] = Qfalse;
704 ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
705 ep[VM_ENV_DATA_INDEX_ENV] = Qundef; /* envval */
707 /* self? */
708 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.ifunc, ifunc);
709 proc->is_lambda = TRUE;
710 return procval;
713 static VALUE
714 sym_proc_new(VALUE klass, VALUE sym)
716 VALUE procval = rb_proc_alloc(klass);
717 rb_proc_t *proc;
718 GetProcPtr(procval, proc);
720 vm_block_type_set(&proc->block, block_type_symbol);
721 proc->is_lambda = TRUE;
722 RB_OBJ_WRITE(procval, &proc->block.as.symbol, sym);
723 return procval;
726 struct vm_ifunc *
727 rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc)
729 union {
730 struct vm_ifunc_argc argc;
731 VALUE packed;
732 } arity;
734 if (min_argc < UNLIMITED_ARGUMENTS ||
735 #if SIZEOF_INT * 2 > SIZEOF_VALUE
736 min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
737 #endif
738 0) {
739 rb_raise(rb_eRangeError, "minimum argument number out of range: %d",
740 min_argc);
742 if (max_argc < UNLIMITED_ARGUMENTS ||
743 #if SIZEOF_INT * 2 > SIZEOF_VALUE
744 max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
745 #endif
746 0) {
747 rb_raise(rb_eRangeError, "maximum argument number out of range: %d",
748 max_argc);
750 arity.argc.min = min_argc;
751 arity.argc.max = max_argc;
752 VALUE ret = rb_imemo_new(imemo_ifunc, (VALUE)func, (VALUE)data, arity.packed, 0);
753 return (struct vm_ifunc *)ret;
756 MJIT_FUNC_EXPORTED VALUE
757 rb_func_proc_new(rb_block_call_func_t func, VALUE val)
759 struct vm_ifunc *ifunc = rb_vm_ifunc_proc_new(func, (void *)val);
760 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
763 MJIT_FUNC_EXPORTED VALUE
764 rb_func_lambda_new(rb_block_call_func_t func, VALUE val, int min_argc, int max_argc)
766 struct vm_ifunc *ifunc = rb_vm_ifunc_new(func, (void *)val, min_argc, max_argc);
767 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
770 static const char proc_without_block[] = "tried to create Proc object without a block";
772 static VALUE
773 proc_new(VALUE klass, int8_t is_lambda, int8_t kernel)
775 VALUE procval;
776 const rb_execution_context_t *ec = GET_EC();
777 rb_control_frame_t *cfp = ec->cfp;
778 VALUE block_handler;
780 if ((block_handler = rb_vm_frame_block_handler(cfp)) == VM_BLOCK_HANDLER_NONE) {
781 rb_raise(rb_eArgError, proc_without_block);
784 /* block is in cf */
785 switch (vm_block_handler_type(block_handler)) {
786 case block_handler_type_proc:
787 procval = VM_BH_TO_PROC(block_handler);
789 if (RBASIC_CLASS(procval) == klass) {
790 return procval;
792 else {
793 VALUE newprocval = rb_proc_dup(procval);
794 RBASIC_SET_CLASS(newprocval, klass);
795 return newprocval;
797 break;
799 case block_handler_type_symbol:
800 return (klass != rb_cProc) ?
801 sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) :
802 rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
803 break;
805 case block_handler_type_ifunc:
806 return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda);
807 case block_handler_type_iseq:
809 const struct rb_captured_block *captured = VM_BH_TO_CAPT_BLOCK(block_handler);
810 rb_control_frame_t *last_ruby_cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
811 if (is_lambda && last_ruby_cfp && vm_cfp_forwarded_bh_p(last_ruby_cfp, block_handler)) {
812 is_lambda = false;
814 return rb_vm_make_proc_lambda(ec, captured, klass, is_lambda);
817 VM_UNREACHABLE(proc_new);
818 return Qnil;
822 * call-seq:
823 * Proc.new {|...| block } -> a_proc
825 * Creates a new Proc object, bound to the current context.
827 * proc = Proc.new { "hello" }
828 * proc.call #=> "hello"
830 * Raises ArgumentError if called without a block.
832 * Proc.new #=> ArgumentError
835 static VALUE
836 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
838 VALUE block = proc_new(klass, FALSE, FALSE);
840 rb_obj_call_init_kw(block, argc, argv, RB_PASS_CALLED_KEYWORDS);
841 return block;
844 VALUE
845 rb_block_proc(void)
847 return proc_new(rb_cProc, FALSE, FALSE);
851 * call-seq:
852 * proc { |...| block } -> a_proc
854 * Equivalent to Proc.new.
857 static VALUE
858 f_proc(VALUE _)
860 return proc_new(rb_cProc, FALSE, TRUE);
863 VALUE
864 rb_block_lambda(void)
866 return proc_new(rb_cProc, TRUE, FALSE);
869 static void
870 f_lambda_warn(void)
872 rb_control_frame_t *cfp = GET_EC()->cfp;
873 VALUE block_handler = rb_vm_frame_block_handler(cfp);
875 if (block_handler != VM_BLOCK_HANDLER_NONE) {
876 switch (vm_block_handler_type(block_handler)) {
877 case block_handler_type_iseq:
878 if (RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)->ep == VM_BH_TO_ISEQ_BLOCK(block_handler)->ep) {
879 return;
881 break;
882 case block_handler_type_symbol:
883 return;
884 case block_handler_type_proc:
885 if (rb_proc_lambda_p(VM_BH_TO_PROC(block_handler))) {
886 return;
888 break;
889 case block_handler_type_ifunc:
890 break;
894 rb_warn_deprecated("lambda without a literal block", "the proc without lambda");
898 * call-seq:
899 * lambda { |...| block } -> a_proc
901 * Equivalent to Proc.new, except the resulting Proc objects check the
902 * number of parameters passed when called.
905 static VALUE
906 f_lambda(VALUE _)
908 f_lambda_warn();
909 return rb_block_lambda();
912 /* Document-method: Proc#===
914 * call-seq:
915 * proc === obj -> result_of_proc
917 * Invokes the block with +obj+ as the proc's parameter like Proc#call.
918 * This allows a proc object to be the target of a +when+ clause
919 * in a case statement.
922 /* CHECKME: are the argument checking semantics correct? */
925 * Document-method: Proc#[]
926 * Document-method: Proc#call
927 * Document-method: Proc#yield
929 * call-seq:
930 * prc.call(params,...) -> obj
931 * prc[params,...] -> obj
932 * prc.(params,...) -> obj
933 * prc.yield(params,...) -> obj
935 * Invokes the block, setting the block's parameters to the values in
936 * <i>params</i> using something close to method calling semantics.
937 * Returns the value of the last expression evaluated in the block.
939 * a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
940 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
941 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
942 * a_proc.(9, 1, 2, 3) #=> [9, 18, 27]
943 * a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
945 * Note that <code>prc.()</code> invokes <code>prc.call()</code> with
946 * the parameters given. It's syntactic sugar to hide "call".
948 * For procs created using #lambda or <code>->()</code> an error is
949 * generated if the wrong number of parameters are passed to the
950 * proc. For procs created using Proc.new or Kernel.proc, extra
951 * parameters are silently discarded and missing parameters are set
952 * to +nil+.
954 * a_proc = proc {|a,b| [a,b] }
955 * a_proc.call(1) #=> [1, nil]
957 * a_proc = lambda {|a,b| [a,b] }
958 * a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
960 * See also Proc#lambda?.
962 #if 0
963 static VALUE
964 proc_call(int argc, VALUE *argv, VALUE procval)
966 /* removed */
968 #endif
970 #if SIZEOF_LONG > SIZEOF_INT
971 static inline int
972 check_argc(long argc)
974 if (argc > INT_MAX || argc < 0) {
975 rb_raise(rb_eArgError, "too many arguments (%lu)",
976 (unsigned long)argc);
978 return (int)argc;
980 #else
981 #define check_argc(argc) (argc)
982 #endif
984 VALUE
985 rb_proc_call_kw(VALUE self, VALUE args, int kw_splat)
987 VALUE vret;
988 rb_proc_t *proc;
989 int argc = check_argc(RARRAY_LEN(args));
990 const VALUE *argv = RARRAY_CONST_PTR(args);
991 GetProcPtr(self, proc);
992 vret = rb_vm_invoke_proc(GET_EC(), proc, argc, argv,
993 kw_splat, VM_BLOCK_HANDLER_NONE);
994 RB_GC_GUARD(self);
995 RB_GC_GUARD(args);
996 return vret;
999 VALUE
1000 rb_proc_call(VALUE self, VALUE args)
1002 return rb_proc_call_kw(self, args, RB_NO_KEYWORDS);
1005 static VALUE
1006 proc_to_block_handler(VALUE procval)
1008 return NIL_P(procval) ? VM_BLOCK_HANDLER_NONE : procval;
1011 VALUE
1012 rb_proc_call_with_block_kw(VALUE self, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
1014 rb_execution_context_t *ec = GET_EC();
1015 VALUE vret;
1016 rb_proc_t *proc;
1017 GetProcPtr(self, proc);
1018 vret = rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, proc_to_block_handler(passed_procval));
1019 RB_GC_GUARD(self);
1020 return vret;
1023 VALUE
1024 rb_proc_call_with_block(VALUE self, int argc, const VALUE *argv, VALUE passed_procval)
1026 return rb_proc_call_with_block_kw(self, argc, argv, passed_procval, RB_NO_KEYWORDS);
1031 * call-seq:
1032 * prc.arity -> integer
1034 * Returns the number of mandatory arguments. If the block
1035 * is declared to take no arguments, returns 0. If the block is known
1036 * to take exactly n arguments, returns n.
1037 * If the block has optional arguments, returns -n-1, where n is the
1038 * number of mandatory arguments, with the exception for blocks that
1039 * are not lambdas and have only a finite number of optional arguments;
1040 * in this latter case, returns n.
1041 * Keyword arguments will be considered as a single additional argument,
1042 * that argument being mandatory if any keyword argument is mandatory.
1043 * A #proc with no argument declarations is the same as a block
1044 * declaring <code>||</code> as its arguments.
1046 * proc {}.arity #=> 0
1047 * proc { || }.arity #=> 0
1048 * proc { |a| }.arity #=> 1
1049 * proc { |a, b| }.arity #=> 2
1050 * proc { |a, b, c| }.arity #=> 3
1051 * proc { |*a| }.arity #=> -1
1052 * proc { |a, *b| }.arity #=> -2
1053 * proc { |a, *b, c| }.arity #=> -3
1054 * proc { |x:, y:, z:0| }.arity #=> 1
1055 * proc { |*a, x:, y:0| }.arity #=> -2
1057 * proc { |a=0| }.arity #=> 0
1058 * lambda { |a=0| }.arity #=> -1
1059 * proc { |a=0, b| }.arity #=> 1
1060 * lambda { |a=0, b| }.arity #=> -2
1061 * proc { |a=0, b=0| }.arity #=> 0
1062 * lambda { |a=0, b=0| }.arity #=> -1
1063 * proc { |a, b=0| }.arity #=> 1
1064 * lambda { |a, b=0| }.arity #=> -2
1065 * proc { |(a, b), c=0| }.arity #=> 1
1066 * lambda { |(a, b), c=0| }.arity #=> -2
1067 * proc { |a, x:0, y:0| }.arity #=> 1
1068 * lambda { |a, x:0, y:0| }.arity #=> -2
1071 static VALUE
1072 proc_arity(VALUE self)
1074 int arity = rb_proc_arity(self);
1075 return INT2FIX(arity);
1078 static inline int
1079 rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
1081 *max = iseq->body->param.flags.has_rest == FALSE ?
1082 iseq->body->param.lead_num + iseq->body->param.opt_num + iseq->body->param.post_num +
1083 (iseq->body->param.flags.has_kw == TRUE || iseq->body->param.flags.has_kwrest == TRUE)
1084 : UNLIMITED_ARGUMENTS;
1085 return iseq->body->param.lead_num + iseq->body->param.post_num + (iseq->body->param.flags.has_kw && iseq->body->param.keyword->required_num > 0);
1088 static int
1089 rb_vm_block_min_max_arity(const struct rb_block *block, int *max)
1091 again:
1092 switch (vm_block_type(block)) {
1093 case block_type_iseq:
1094 return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max);
1095 case block_type_proc:
1096 block = vm_proc_block(block->as.proc);
1097 goto again;
1098 case block_type_ifunc:
1100 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1101 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1102 /* e.g. method(:foo).to_proc.arity */
1103 return method_min_max_arity((VALUE)ifunc->data, max);
1105 *max = ifunc->argc.max;
1106 return ifunc->argc.min;
1108 case block_type_symbol:
1109 *max = UNLIMITED_ARGUMENTS;
1110 return 1;
1112 *max = UNLIMITED_ARGUMENTS;
1113 return 0;
1117 * Returns the number of required parameters and stores the maximum
1118 * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
1119 * For non-lambda procs, the maximum is the number of non-ignored
1120 * parameters even though there is no actual limit to the number of parameters
1122 static int
1123 rb_proc_min_max_arity(VALUE self, int *max)
1125 rb_proc_t *proc;
1126 GetProcPtr(self, proc);
1127 return rb_vm_block_min_max_arity(&proc->block, max);
1131 rb_proc_arity(VALUE self)
1133 rb_proc_t *proc;
1134 int max, min;
1135 GetProcPtr(self, proc);
1136 min = rb_vm_block_min_max_arity(&proc->block, &max);
1137 return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1140 static void
1141 block_setup(struct rb_block *block, VALUE block_handler)
1143 switch (vm_block_handler_type(block_handler)) {
1144 case block_handler_type_iseq:
1145 block->type = block_type_iseq;
1146 block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler);
1147 break;
1148 case block_handler_type_ifunc:
1149 block->type = block_type_ifunc;
1150 block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler);
1151 break;
1152 case block_handler_type_symbol:
1153 block->type = block_type_symbol;
1154 block->as.symbol = VM_BH_TO_SYMBOL(block_handler);
1155 break;
1156 case block_handler_type_proc:
1157 block->type = block_type_proc;
1158 block->as.proc = VM_BH_TO_PROC(block_handler);
1163 rb_block_pair_yield_optimizable(void)
1165 int min, max;
1166 const rb_execution_context_t *ec = GET_EC();
1167 rb_control_frame_t *cfp = ec->cfp;
1168 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1169 struct rb_block block;
1171 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1172 rb_raise(rb_eArgError, "no block given");
1175 block_setup(&block, block_handler);
1176 min = rb_vm_block_min_max_arity(&block, &max);
1178 switch (vm_block_type(&block)) {
1179 case block_handler_type_symbol:
1180 return 0;
1182 case block_handler_type_proc:
1184 VALUE procval = block_handler;
1185 rb_proc_t *proc;
1186 GetProcPtr(procval, proc);
1187 if (proc->is_lambda) return 0;
1188 if (min != max) return 0;
1189 return min > 1;
1192 default:
1193 return min > 1;
1198 rb_block_arity(void)
1200 int min, max;
1201 const rb_execution_context_t *ec = GET_EC();
1202 rb_control_frame_t *cfp = ec->cfp;
1203 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1204 struct rb_block block;
1206 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1207 rb_raise(rb_eArgError, "no block given");
1210 block_setup(&block, block_handler);
1211 min = rb_vm_block_min_max_arity(&block, &max);
1213 switch (vm_block_type(&block)) {
1214 case block_handler_type_symbol:
1215 return -1;
1217 case block_handler_type_proc:
1219 VALUE procval = block_handler;
1220 rb_proc_t *proc;
1221 GetProcPtr(procval, proc);
1222 return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1225 default:
1226 return max != UNLIMITED_ARGUMENTS ? min : -min-1;
1231 rb_block_min_max_arity(int *max)
1233 const rb_execution_context_t *ec = GET_EC();
1234 rb_control_frame_t *cfp = ec->cfp;
1235 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1236 struct rb_block block;
1238 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1239 rb_raise(rb_eArgError, "no block given");
1242 block_setup(&block, block_handler);
1243 return rb_vm_block_min_max_arity(&block, max);
1246 const rb_iseq_t *
1247 rb_proc_get_iseq(VALUE self, int *is_proc)
1249 const rb_proc_t *proc;
1250 const struct rb_block *block;
1252 GetProcPtr(self, proc);
1253 block = &proc->block;
1254 if (is_proc) *is_proc = !proc->is_lambda;
1256 switch (vm_block_type(block)) {
1257 case block_type_iseq:
1258 return rb_iseq_check(block->as.captured.code.iseq);
1259 case block_type_proc:
1260 return rb_proc_get_iseq(block->as.proc, is_proc);
1261 case block_type_ifunc:
1263 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1264 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1265 /* method(:foo).to_proc */
1266 if (is_proc) *is_proc = 0;
1267 return rb_method_iseq((VALUE)ifunc->data);
1269 else {
1270 return NULL;
1273 case block_type_symbol:
1274 return NULL;
1277 VM_UNREACHABLE(rb_proc_get_iseq);
1278 return NULL;
1281 /* call-seq:
1282 * prc == other -> true or false
1283 * prc.eql?(other) -> true or false
1285 * Two procs are the same if, and only if, they were created from the same code block.
1287 * def return_block(&block)
1288 * block
1289 * end
1291 * def pass_block_twice(&block)
1292 * [return_block(&block), return_block(&block)]
1293 * end
1295 * block1, block2 = pass_block_twice { puts 'test' }
1296 * # Blocks might be instantiated into Proc's lazily, so they may, or may not,
1297 * # be the same object.
1298 * # But they are produced from the same code block, so they are equal
1299 * block1 == block2
1300 * #=> true
1302 * # Another Proc will never be equal, even if the code is the "same"
1303 * block1 == proc { puts 'test' }
1304 * #=> false
1307 static VALUE
1308 proc_eq(VALUE self, VALUE other)
1310 const rb_proc_t *self_proc, *other_proc;
1311 const struct rb_block *self_block, *other_block;
1313 if (rb_obj_class(self) != rb_obj_class(other)) {
1314 return Qfalse;
1317 GetProcPtr(self, self_proc);
1318 GetProcPtr(other, other_proc);
1320 if (self_proc->is_from_method != other_proc->is_from_method ||
1321 self_proc->is_lambda != other_proc->is_lambda) {
1322 return Qfalse;
1325 self_block = &self_proc->block;
1326 other_block = &other_proc->block;
1328 if (vm_block_type(self_block) != vm_block_type(other_block)) {
1329 return Qfalse;
1332 switch (vm_block_type(self_block)) {
1333 case block_type_iseq:
1334 if (self_block->as.captured.ep != \
1335 other_block->as.captured.ep ||
1336 self_block->as.captured.code.iseq != \
1337 other_block->as.captured.code.iseq) {
1338 return Qfalse;
1340 break;
1341 case block_type_ifunc:
1342 if (self_block->as.captured.ep != \
1343 other_block->as.captured.ep ||
1344 self_block->as.captured.code.ifunc != \
1345 other_block->as.captured.code.ifunc) {
1346 return Qfalse;
1348 break;
1349 case block_type_proc:
1350 if (self_block->as.proc != other_block->as.proc) {
1351 return Qfalse;
1353 break;
1354 case block_type_symbol:
1355 if (self_block->as.symbol != other_block->as.symbol) {
1356 return Qfalse;
1358 break;
1361 return Qtrue;
1364 static VALUE
1365 iseq_location(const rb_iseq_t *iseq)
1367 VALUE loc[2];
1369 if (!iseq) return Qnil;
1370 rb_iseq_check(iseq);
1371 loc[0] = rb_iseq_path(iseq);
1372 loc[1] = iseq->body->location.first_lineno;
1374 return rb_ary_new4(2, loc);
1377 MJIT_FUNC_EXPORTED VALUE
1378 rb_iseq_location(const rb_iseq_t *iseq)
1380 return iseq_location(iseq);
1384 * call-seq:
1385 * prc.source_location -> [String, Integer]
1387 * Returns the Ruby source filename and line number containing this proc
1388 * or +nil+ if this proc was not defined in Ruby (i.e. native).
1391 VALUE
1392 rb_proc_location(VALUE self)
1394 return iseq_location(rb_proc_get_iseq(self, 0));
1397 VALUE
1398 rb_unnamed_parameters(int arity)
1400 VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
1401 int n = (arity < 0) ? ~arity : arity;
1402 ID req, rest;
1403 CONST_ID(req, "req");
1404 a = rb_ary_new3(1, ID2SYM(req));
1405 OBJ_FREEZE(a);
1406 for (; n; --n) {
1407 rb_ary_push(param, a);
1409 if (arity < 0) {
1410 CONST_ID(rest, "rest");
1411 rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
1413 return param;
1417 * call-seq:
1418 * prc.parameters -> array
1420 * Returns the parameter information of this proc.
1422 * prc = lambda{|x, y=42, *other|}
1423 * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1426 static VALUE
1427 rb_proc_parameters(VALUE self)
1429 int is_proc;
1430 const rb_iseq_t *iseq = rb_proc_get_iseq(self, &is_proc);
1431 if (!iseq) {
1432 return rb_unnamed_parameters(rb_proc_arity(self));
1434 return rb_iseq_parameters(iseq, is_proc);
1437 st_index_t
1438 rb_hash_proc(st_index_t hash, VALUE prc)
1440 rb_proc_t *proc;
1441 GetProcPtr(prc, proc);
1442 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.code.val);
1443 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.self);
1444 return rb_hash_uint(hash, (st_index_t)proc->block.as.captured.ep);
1447 MJIT_FUNC_EXPORTED VALUE
1448 rb_sym_to_proc(VALUE sym)
1450 static VALUE sym_proc_cache = Qfalse;
1451 enum {SYM_PROC_CACHE_SIZE = 67};
1452 VALUE proc;
1453 long index;
1454 ID id;
1456 if (!sym_proc_cache) {
1457 sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2);
1458 rb_gc_register_mark_object(sym_proc_cache);
1459 rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil);
1462 id = SYM2ID(sym);
1463 index = (id % SYM_PROC_CACHE_SIZE) << 1;
1465 if (RARRAY_AREF(sym_proc_cache, index) == sym) {
1466 return RARRAY_AREF(sym_proc_cache, index + 1);
1468 else {
1469 proc = sym_proc_new(rb_cProc, ID2SYM(id));
1470 RARRAY_ASET(sym_proc_cache, index, sym);
1471 RARRAY_ASET(sym_proc_cache, index + 1, proc);
1472 return proc;
1477 * call-seq:
1478 * prc.hash -> integer
1480 * Returns a hash value corresponding to proc body.
1482 * See also Object#hash.
1485 static VALUE
1486 proc_hash(VALUE self)
1488 st_index_t hash;
1489 hash = rb_hash_start(0);
1490 hash = rb_hash_proc(hash, self);
1491 hash = rb_hash_end(hash);
1492 return ST2FIX(hash);
1495 VALUE
1496 rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
1498 VALUE cname = rb_obj_class(self);
1499 VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
1501 again:
1502 switch (vm_block_type(block)) {
1503 case block_type_proc:
1504 block = vm_proc_block(block->as.proc);
1505 goto again;
1506 case block_type_iseq:
1508 const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
1509 rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
1510 rb_iseq_path(iseq),
1511 FIX2INT(iseq->body->location.first_lineno));
1513 break;
1514 case block_type_symbol:
1515 rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
1516 break;
1517 case block_type_ifunc:
1518 rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
1519 break;
1522 if (additional_info) rb_str_cat_cstr(str, additional_info);
1523 rb_str_cat_cstr(str, ">");
1524 return str;
1528 * call-seq:
1529 * prc.to_s -> string
1531 * Returns the unique identifier for this proc, along with
1532 * an indication of where the proc was defined.
1535 static VALUE
1536 proc_to_s(VALUE self)
1538 const rb_proc_t *proc;
1539 GetProcPtr(self, proc);
1540 return rb_block_to_s(self, &proc->block, proc->is_lambda ? " (lambda)" : NULL);
1544 * call-seq:
1545 * prc.to_proc -> proc
1547 * Part of the protocol for converting objects to Proc objects.
1548 * Instances of class Proc simply return themselves.
1551 static VALUE
1552 proc_to_proc(VALUE self)
1554 return self;
1557 static void
1558 bm_mark(void *ptr)
1560 struct METHOD *data = ptr;
1561 rb_gc_mark_movable(data->recv);
1562 rb_gc_mark_movable(data->klass);
1563 rb_gc_mark_movable(data->iclass);
1564 rb_gc_mark_movable((VALUE)data->me);
1567 static void
1568 bm_compact(void *ptr)
1570 struct METHOD *data = ptr;
1571 UPDATE_REFERENCE(data->recv);
1572 UPDATE_REFERENCE(data->klass);
1573 UPDATE_REFERENCE(data->iclass);
1574 UPDATE_TYPED_REFERENCE(rb_method_entry_t *, data->me);
1577 static size_t
1578 bm_memsize(const void *ptr)
1580 return sizeof(struct METHOD);
1583 static const rb_data_type_t method_data_type = {
1584 "method",
1586 bm_mark,
1587 RUBY_TYPED_DEFAULT_FREE,
1588 bm_memsize,
1589 bm_compact,
1591 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1594 VALUE
1595 rb_obj_is_method(VALUE m)
1597 return RBOOL(rb_typeddata_is_kind_of(m, &method_data_type));
1600 static int
1601 respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
1603 /* TODO: merge with obj_respond_to() */
1604 ID rmiss = idRespond_to_missing;
1606 if (obj == Qundef) return 0;
1607 if (rb_method_basic_definition_p(klass, rmiss)) return 0;
1608 return RTEST(rb_funcall(obj, rmiss, 2, sym, RBOOL(!scope)));
1612 static VALUE
1613 mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
1615 struct METHOD *data;
1616 VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1617 rb_method_entry_t *me;
1618 rb_method_definition_t *def;
1620 RB_OBJ_WRITE(method, &data->recv, obj);
1621 RB_OBJ_WRITE(method, &data->klass, klass);
1623 def = ZALLOC(rb_method_definition_t);
1624 def->type = VM_METHOD_TYPE_MISSING;
1625 def->original_id = id;
1627 me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
1629 RB_OBJ_WRITE(method, &data->me, me);
1630 data->visibility = METHOD_ENTRY_VISI(me);
1632 return method;
1635 static VALUE
1636 mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
1638 VALUE vid = rb_str_intern(*name);
1639 *name = vid;
1640 if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
1641 return mnew_missing(klass, obj, SYM2ID(vid), mclass);
1644 static VALUE
1645 mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1646 VALUE obj, ID id, VALUE mclass, int scope, int error)
1648 struct METHOD *data;
1649 VALUE method;
1650 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
1652 again:
1653 if (UNDEFINED_METHOD_ENTRY_P(me)) {
1654 if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
1655 return mnew_missing(klass, obj, id, mclass);
1657 if (!error) return Qnil;
1658 rb_print_undef(klass, id, METHOD_VISI_UNDEF);
1660 if (visi == METHOD_VISI_UNDEF) {
1661 visi = METHOD_ENTRY_VISI(me);
1662 RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */
1663 if (scope && (visi != METHOD_VISI_PUBLIC)) {
1664 if (!error) return Qnil;
1665 rb_print_inaccessible(klass, id, visi);
1668 if (me->def->type == VM_METHOD_TYPE_ZSUPER) {
1669 if (me->defined_class) {
1670 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
1671 id = me->def->original_id;
1672 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1674 else {
1675 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner));
1676 id = me->def->original_id;
1677 me = rb_method_entry_without_refinements(klass, id, &iclass);
1679 goto again;
1682 method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1684 RB_OBJ_WRITE(method, &data->recv, obj);
1685 RB_OBJ_WRITE(method, &data->klass, klass);
1686 RB_OBJ_WRITE(method, &data->iclass, iclass);
1687 RB_OBJ_WRITE(method, &data->me, me);
1688 data->visibility = visi;
1690 return method;
1693 static VALUE
1694 mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1695 VALUE obj, ID id, VALUE mclass, int scope)
1697 return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
1700 static VALUE
1701 mnew_callable(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
1703 const rb_method_entry_t *me;
1704 VALUE iclass = Qnil;
1706 ASSUME(obj != Qundef);
1707 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1708 return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
1711 static VALUE
1712 mnew_unbound(VALUE klass, ID id, VALUE mclass, int scope)
1714 const rb_method_entry_t *me;
1715 VALUE iclass = Qnil;
1717 me = rb_method_entry_with_refinements(klass, id, &iclass);
1718 return mnew_from_me(me, klass, iclass, Qundef, id, mclass, scope);
1721 static inline VALUE
1722 method_entry_defined_class(const rb_method_entry_t *me)
1724 VALUE defined_class = me->defined_class;
1725 return defined_class ? defined_class : me->owner;
1728 /**********************************************************************
1730 * Document-class: Method
1732 * Method objects are created by Object#method, and are associated
1733 * with a particular object (not just with a class). They may be
1734 * used to invoke the method within the object, and as a block
1735 * associated with an iterator. They may also be unbound from one
1736 * object (creating an UnboundMethod) and bound to another.
1738 * class Thing
1739 * def square(n)
1740 * n*n
1741 * end
1742 * end
1743 * thing = Thing.new
1744 * meth = thing.method(:square)
1746 * meth.call(9) #=> 81
1747 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1749 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
1751 * require 'date'
1752 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1753 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1757 * call-seq:
1758 * meth.eql?(other_meth) -> true or false
1759 * meth == other_meth -> true or false
1761 * Two method objects are equal if they are bound to the same
1762 * object and refer to the same method definition and the classes
1763 * defining the methods are the same class or module.
1766 static VALUE
1767 method_eq(VALUE method, VALUE other)
1769 struct METHOD *m1, *m2;
1770 VALUE klass1, klass2;
1772 if (!rb_obj_is_method(other))
1773 return Qfalse;
1774 if (CLASS_OF(method) != CLASS_OF(other))
1775 return Qfalse;
1777 Check_TypedStruct(method, &method_data_type);
1778 m1 = (struct METHOD *)DATA_PTR(method);
1779 m2 = (struct METHOD *)DATA_PTR(other);
1781 klass1 = method_entry_defined_class(m1->me);
1782 klass2 = method_entry_defined_class(m2->me);
1784 if (!rb_method_entry_eq(m1->me, m2->me) ||
1785 klass1 != klass2 ||
1786 m1->visibility != m2->visibility ||
1787 m1->klass != m2->klass ||
1788 m1->recv != m2->recv) {
1789 return Qfalse;
1792 return Qtrue;
1796 * call-seq:
1797 * meth.hash -> integer
1799 * Returns a hash value corresponding to the method object.
1801 * See also Object#hash.
1804 static VALUE
1805 method_hash(VALUE method)
1807 struct METHOD *m;
1808 st_index_t hash;
1810 TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
1811 hash = rb_hash_start((st_index_t)m->recv);
1812 hash = rb_hash_method_entry(hash, m->me);
1813 hash = rb_hash_end(hash);
1815 return ST2FIX(hash);
1819 * call-seq:
1820 * meth.unbind -> unbound_method
1822 * Dissociates <i>meth</i> from its current receiver. The resulting
1823 * UnboundMethod can subsequently be bound to a new object of the
1824 * same class (see UnboundMethod).
1827 static VALUE
1828 method_unbind(VALUE obj)
1830 VALUE method;
1831 struct METHOD *orig, *data;
1833 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
1834 method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
1835 &method_data_type, data);
1836 RB_OBJ_WRITE(method, &data->recv, Qundef);
1837 RB_OBJ_WRITE(method, &data->klass, orig->klass);
1838 RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
1839 RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
1840 data->visibility = orig->visibility;
1842 return method;
1846 * call-seq:
1847 * meth.receiver -> object
1849 * Returns the bound receiver of the method object.
1851 * (1..3).method(:map).receiver # => 1..3
1854 static VALUE
1855 method_receiver(VALUE obj)
1857 struct METHOD *data;
1859 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1860 return data->recv;
1864 * call-seq:
1865 * meth.name -> symbol
1867 * Returns the name of the method.
1870 static VALUE
1871 method_name(VALUE obj)
1873 struct METHOD *data;
1875 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1876 return ID2SYM(data->me->called_id);
1880 * call-seq:
1881 * meth.original_name -> symbol
1883 * Returns the original name of the method.
1885 * class C
1886 * def foo; end
1887 * alias bar foo
1888 * end
1889 * C.instance_method(:bar).original_name # => :foo
1892 static VALUE
1893 method_original_name(VALUE obj)
1895 struct METHOD *data;
1897 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1898 return ID2SYM(data->me->def->original_id);
1902 * call-seq:
1903 * meth.owner -> class_or_module
1905 * Returns the class or module that defines the method.
1906 * See also Method#receiver.
1908 * (1..3).method(:map).owner #=> Enumerable
1911 static VALUE
1912 method_owner(VALUE obj)
1914 struct METHOD *data;
1915 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1916 return data->me->owner;
1919 void
1920 rb_method_name_error(VALUE klass, VALUE str)
1922 #define MSG(s) rb_fstring_lit("undefined method `%1$s' for"s" `%2$s'")
1923 VALUE c = klass;
1924 VALUE s = Qundef;
1926 if (FL_TEST(c, FL_SINGLETON)) {
1927 VALUE obj = rb_ivar_get(klass, attached);
1929 switch (BUILTIN_TYPE(obj)) {
1930 case T_MODULE:
1931 case T_CLASS:
1932 c = obj;
1933 break;
1934 default:
1935 break;
1938 else if (RB_TYPE_P(c, T_MODULE)) {
1939 s = MSG(" module");
1941 if (s == Qundef) {
1942 s = MSG(" class");
1944 rb_name_err_raise_str(s, c, str);
1945 #undef MSG
1948 static VALUE
1949 obj_method(VALUE obj, VALUE vid, int scope)
1951 ID id = rb_check_id(&vid);
1952 const VALUE klass = CLASS_OF(obj);
1953 const VALUE mclass = rb_cMethod;
1955 if (!id) {
1956 VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
1957 if (m) return m;
1958 rb_method_name_error(klass, vid);
1960 return mnew_callable(klass, obj, id, mclass, scope);
1964 * call-seq:
1965 * obj.method(sym) -> method
1967 * Looks up the named method as a receiver in <i>obj</i>, returning a
1968 * Method object (or raising NameError). The Method object acts as a
1969 * closure in <i>obj</i>'s object instance, so instance variables and
1970 * the value of <code>self</code> remain available.
1972 * class Demo
1973 * def initialize(n)
1974 * @iv = n
1975 * end
1976 * def hello()
1977 * "Hello, @iv = #{@iv}"
1978 * end
1979 * end
1981 * k = Demo.new(99)
1982 * m = k.method(:hello)
1983 * m.call #=> "Hello, @iv = 99"
1985 * l = Demo.new('Fred')
1986 * m = l.method("hello")
1987 * m.call #=> "Hello, @iv = Fred"
1989 * Note that Method implements <code>to_proc</code> method, which
1990 * means it can be used with iterators.
1992 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
1994 * out = File.open('test.txt', 'w')
1995 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
1997 * require 'date'
1998 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1999 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2002 VALUE
2003 rb_obj_method(VALUE obj, VALUE vid)
2005 return obj_method(obj, vid, FALSE);
2009 * call-seq:
2010 * obj.public_method(sym) -> method
2012 * Similar to _method_, searches public method only.
2015 VALUE
2016 rb_obj_public_method(VALUE obj, VALUE vid)
2018 return obj_method(obj, vid, TRUE);
2022 * call-seq:
2023 * obj.singleton_method(sym) -> method
2025 * Similar to _method_, searches singleton method only.
2027 * class Demo
2028 * def initialize(n)
2029 * @iv = n
2030 * end
2031 * def hello()
2032 * "Hello, @iv = #{@iv}"
2033 * end
2034 * end
2036 * k = Demo.new(99)
2037 * def k.hi
2038 * "Hi, @iv = #{@iv}"
2039 * end
2040 * m = k.singleton_method(:hi)
2041 * m.call #=> "Hi, @iv = 99"
2042 * m = k.singleton_method(:hello) #=> NameError
2045 VALUE
2046 rb_obj_singleton_method(VALUE obj, VALUE vid)
2048 VALUE klass = rb_singleton_class_get(obj);
2049 ID id = rb_check_id(&vid);
2051 if (NIL_P(klass)) {
2052 /* goto undef; */
2054 else if (NIL_P(klass = RCLASS_ORIGIN(klass))) {
2055 /* goto undef; */
2057 else if (! id) {
2058 VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
2059 if (m) return m;
2060 /* else goto undef; */
2062 else {
2063 const rb_method_entry_t *me = rb_method_entry_at(klass, id);
2064 vid = ID2SYM(id);
2066 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2067 /* goto undef; */
2069 else if (UNDEFINED_REFINED_METHOD_P(me->def)) {
2070 /* goto undef; */
2072 else {
2073 return mnew_from_me(me, klass, klass, obj, id, rb_cMethod, FALSE);
2077 /* undef: */
2078 rb_name_err_raise("undefined singleton method `%1$s' for `%2$s'",
2079 obj, vid);
2080 UNREACHABLE_RETURN(Qundef);
2084 * call-seq:
2085 * mod.instance_method(symbol) -> unbound_method
2087 * Returns an +UnboundMethod+ representing the given
2088 * instance method in _mod_.
2090 * class Interpreter
2091 * def do_a() print "there, "; end
2092 * def do_d() print "Hello "; end
2093 * def do_e() print "!\n"; end
2094 * def do_v() print "Dave"; end
2095 * Dispatcher = {
2096 * "a" => instance_method(:do_a),
2097 * "d" => instance_method(:do_d),
2098 * "e" => instance_method(:do_e),
2099 * "v" => instance_method(:do_v)
2101 * def interpret(string)
2102 * string.each_char {|b| Dispatcher[b].bind(self).call }
2103 * end
2104 * end
2106 * interpreter = Interpreter.new
2107 * interpreter.interpret('dave')
2109 * <em>produces:</em>
2111 * Hello there, Dave!
2114 static VALUE
2115 rb_mod_instance_method(VALUE mod, VALUE vid)
2117 ID id = rb_check_id(&vid);
2118 if (!id) {
2119 rb_method_name_error(mod, vid);
2121 return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
2125 * call-seq:
2126 * mod.public_instance_method(symbol) -> unbound_method
2128 * Similar to _instance_method_, searches public method only.
2131 static VALUE
2132 rb_mod_public_instance_method(VALUE mod, VALUE vid)
2134 ID id = rb_check_id(&vid);
2135 if (!id) {
2136 rb_method_name_error(mod, vid);
2138 return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
2142 * call-seq:
2143 * define_method(symbol, method) -> symbol
2144 * define_method(symbol) { block } -> symbol
2146 * Defines an instance method in the receiver. The _method_
2147 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2148 * If a block is specified, it is used as the method body.
2149 * If a block or the _method_ parameter has parameters,
2150 * they're used as method parameters.
2151 * This block is evaluated using #instance_eval.
2153 * class A
2154 * def fred
2155 * puts "In Fred"
2156 * end
2157 * def create_method(name, &block)
2158 * self.class.define_method(name, &block)
2159 * end
2160 * define_method(:wilma) { puts "Charge it!" }
2161 * define_method(:flint) {|name| puts "I'm #{name}!"}
2162 * end
2163 * class B < A
2164 * define_method(:barney, instance_method(:fred))
2165 * end
2166 * a = B.new
2167 * a.barney
2168 * a.wilma
2169 * a.flint('Dino')
2170 * a.create_method(:betty) { p self }
2171 * a.betty
2173 * <em>produces:</em>
2175 * In Fred
2176 * Charge it!
2177 * I'm Dino!
2178 * #<B:0x401b39e8>
2181 static VALUE
2182 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
2184 ID id;
2185 VALUE body;
2186 VALUE name;
2187 const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
2188 const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2189 const rb_scope_visibility_t *scope_visi = &default_scope_visi;
2190 int is_method = FALSE;
2192 if (cref) {
2193 scope_visi = CREF_SCOPE_VISI(cref);
2196 rb_check_arity(argc, 1, 2);
2197 name = argv[0];
2198 id = rb_check_id(&name);
2199 if (argc == 1) {
2200 body = rb_block_lambda();
2202 else {
2203 body = argv[1];
2205 if (rb_obj_is_method(body)) {
2206 is_method = TRUE;
2208 else if (rb_obj_is_proc(body)) {
2209 is_method = FALSE;
2211 else {
2212 rb_raise(rb_eTypeError,
2213 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
2214 rb_obj_classname(body));
2217 if (!id) id = rb_to_id(name);
2219 if (is_method) {
2220 struct METHOD *method = (struct METHOD *)DATA_PTR(body);
2221 if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
2222 !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
2223 if (FL_TEST(method->me->owner, FL_SINGLETON)) {
2224 rb_raise(rb_eTypeError,
2225 "can't bind singleton method to a different class");
2227 else {
2228 rb_raise(rb_eTypeError,
2229 "bind argument must be a subclass of % "PRIsVALUE,
2230 method->me->owner);
2233 rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
2234 if (scope_visi->module_func) {
2235 rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
2237 RB_GC_GUARD(body);
2239 else {
2240 VALUE procval = rb_proc_dup(body);
2241 if (vm_proc_iseq(procval) != NULL) {
2242 rb_proc_t *proc;
2243 GetProcPtr(procval, proc);
2244 proc->is_lambda = TRUE;
2245 proc->is_from_method = TRUE;
2247 rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
2248 if (scope_visi->module_func) {
2249 rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
2253 return ID2SYM(id);
2257 * call-seq:
2258 * define_singleton_method(symbol, method) -> symbol
2259 * define_singleton_method(symbol) { block } -> symbol
2261 * Defines a singleton method in the receiver. The _method_
2262 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2263 * If a block is specified, it is used as the method body.
2264 * If a block or a method has parameters, they're used as method parameters.
2266 * class A
2267 * class << self
2268 * def class_name
2269 * to_s
2270 * end
2271 * end
2272 * end
2273 * A.define_singleton_method(:who_am_i) do
2274 * "I am: #{class_name}"
2275 * end
2276 * A.who_am_i # ==> "I am: A"
2278 * guy = "Bob"
2279 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
2280 * guy.hello #=> "Bob: Hello there!"
2282 * chris = "Chris"
2283 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
2284 * chris.greet("Hi") #=> "Hi, I'm Chris!"
2287 static VALUE
2288 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
2290 VALUE klass = rb_singleton_class(obj);
2292 return rb_mod_define_method(argc, argv, klass);
2296 * define_method(symbol, method) -> symbol
2297 * define_method(symbol) { block } -> symbol
2299 * Defines a global function by _method_ or the block.
2302 static VALUE
2303 top_define_method(int argc, VALUE *argv, VALUE obj)
2305 rb_thread_t *th = GET_THREAD();
2306 VALUE klass;
2308 klass = th->top_wrapper;
2309 if (klass) {
2310 rb_warning("main.define_method in the wrapped load is effective only in wrapper module");
2312 else {
2313 klass = rb_cObject;
2315 return rb_mod_define_method(argc, argv, klass);
2319 * call-seq:
2320 * method.clone -> new_method
2322 * Returns a clone of this method.
2324 * class A
2325 * def foo
2326 * return "bar"
2327 * end
2328 * end
2330 * m = A.new.method(:foo)
2331 * m.call # => "bar"
2332 * n = m.clone.call # => "bar"
2335 static VALUE
2336 method_clone(VALUE self)
2338 VALUE clone;
2339 struct METHOD *orig, *data;
2341 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2342 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2343 CLONESETUP(clone, self);
2344 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2345 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2346 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2347 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2348 data->visibility = orig->visibility;
2349 return clone;
2352 /* Document-method: Method#===
2354 * call-seq:
2355 * method === obj -> result_of_method
2357 * Invokes the method with +obj+ as the parameter like #call.
2358 * This allows a method object to be the target of a +when+ clause
2359 * in a case statement.
2361 * require 'prime'
2363 * case 1373
2364 * when Prime.method(:prime?)
2365 * # ...
2366 * end
2370 /* Document-method: Method#[]
2372 * call-seq:
2373 * meth[args, ...] -> obj
2375 * Invokes the <i>meth</i> with the specified arguments, returning the
2376 * method's return value, like #call.
2378 * m = 12.method("+")
2379 * m[3] #=> 15
2380 * m[20] #=> 32
2384 * call-seq:
2385 * meth.call(args, ...) -> obj
2387 * Invokes the <i>meth</i> with the specified arguments, returning the
2388 * method's return value.
2390 * m = 12.method("+")
2391 * m.call(3) #=> 15
2392 * m.call(20) #=> 32
2395 static VALUE
2396 rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
2398 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2399 return rb_method_call_with_block_kw(argc, argv, method, procval, RB_PASS_CALLED_KEYWORDS);
2402 VALUE
2403 rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
2405 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2406 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
2409 VALUE
2410 rb_method_call(int argc, const VALUE *argv, VALUE method)
2412 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2413 return rb_method_call_with_block(argc, argv, method, procval);
2416 static const rb_callable_method_entry_t *
2417 method_callable_method_entry(const struct METHOD *data)
2419 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
2420 return (const rb_callable_method_entry_t *)data->me;
2423 static inline VALUE
2424 call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
2425 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
2427 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2428 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
2429 method_callable_method_entry(data), kw_splat);
2432 VALUE
2433 rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
2435 const struct METHOD *data;
2436 rb_execution_context_t *ec = GET_EC();
2438 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2439 if (data->recv == Qundef) {
2440 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
2442 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
2445 VALUE
2446 rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
2448 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
2451 /**********************************************************************
2453 * Document-class: UnboundMethod
2455 * Ruby supports two forms of objectified methods. Class Method is
2456 * used to represent methods that are associated with a particular
2457 * object: these method objects are bound to that object. Bound
2458 * method objects for an object can be created using Object#method.
2460 * Ruby also supports unbound methods; methods objects that are not
2461 * associated with a particular object. These can be created either
2462 * by calling Module#instance_method or by calling #unbind on a bound
2463 * method object. The result of both of these is an UnboundMethod
2464 * object.
2466 * Unbound methods can only be called after they are bound to an
2467 * object. That object must be a kind_of? the method's original
2468 * class.
2470 * class Square
2471 * def area
2472 * @side * @side
2473 * end
2474 * def initialize(side)
2475 * @side = side
2476 * end
2477 * end
2479 * area_un = Square.instance_method(:area)
2481 * s = Square.new(12)
2482 * area = area_un.bind(s)
2483 * area.call #=> 144
2485 * Unbound methods are a reference to the method at the time it was
2486 * objectified: subsequent changes to the underlying class will not
2487 * affect the unbound method.
2489 * class Test
2490 * def test
2491 * :original
2492 * end
2493 * end
2494 * um = Test.instance_method(:test)
2495 * class Test
2496 * def test
2497 * :modified
2498 * end
2499 * end
2500 * t = Test.new
2501 * t.test #=> :modified
2502 * um.bind(t).call #=> :original
2506 static void
2507 convert_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)
2509 VALUE methclass = data->me->owner;
2510 VALUE iclass = data->me->defined_class;
2511 VALUE klass = CLASS_OF(recv);
2513 if (RB_TYPE_P(methclass, T_MODULE)) {
2514 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
2515 if (!NIL_P(refined_class)) methclass = refined_class;
2517 if (!RB_TYPE_P(methclass, T_MODULE) &&
2518 methclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, methclass)) {
2519 if (FL_TEST(methclass, FL_SINGLETON)) {
2520 rb_raise(rb_eTypeError,
2521 "singleton method called for a different object");
2523 else {
2524 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
2525 methclass);
2529 const rb_method_entry_t *me = rb_method_entry_clone(data->me);
2531 if (RB_TYPE_P(me->owner, T_MODULE)) {
2532 VALUE ic = rb_class_search_ancestor(klass, me->owner);
2533 if (ic) {
2534 klass = ic;
2535 iclass = ic;
2537 else {
2538 klass = rb_include_class_new(methclass, klass);
2540 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
2543 *methclass_out = methclass;
2544 *klass_out = klass;
2545 *iclass_out = iclass;
2546 *me_out = me;
2550 * call-seq:
2551 * umeth.bind(obj) -> method
2553 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2554 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2555 * be true.
2557 * class A
2558 * def test
2559 * puts "In test, class = #{self.class}"
2560 * end
2561 * end
2562 * class B < A
2563 * end
2564 * class C < B
2565 * end
2568 * um = B.instance_method(:test)
2569 * bm = um.bind(C.new)
2570 * bm.call
2571 * bm = um.bind(B.new)
2572 * bm.call
2573 * bm = um.bind(A.new)
2574 * bm.call
2576 * <em>produces:</em>
2578 * In test, class = C
2579 * In test, class = B
2580 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2581 * from prog.rb:16
2584 static VALUE
2585 umethod_bind(VALUE method, VALUE recv)
2587 VALUE methclass, klass, iclass;
2588 const rb_method_entry_t *me;
2589 const struct METHOD *data;
2590 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2591 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me);
2593 struct METHOD *bound;
2594 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
2595 RB_OBJ_WRITE(method, &bound->recv, recv);
2596 RB_OBJ_WRITE(method, &bound->klass, klass);
2597 RB_OBJ_WRITE(method, &bound->iclass, iclass);
2598 RB_OBJ_WRITE(method, &bound->me, me);
2599 bound->visibility = data->visibility;
2601 return method;
2605 * call-seq:
2606 * umeth.bind_call(recv, args, ...) -> obj
2608 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2609 * specified arguments.
2610 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2612 static VALUE
2613 umethod_bind_call(int argc, VALUE *argv, VALUE method)
2615 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2616 VALUE recv = argv[0];
2617 argc--;
2618 argv++;
2620 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2621 rb_execution_context_t *ec = GET_EC();
2623 const struct METHOD *data;
2624 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2626 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
2627 if (data->me == (const rb_method_entry_t *)cme) {
2628 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2629 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
2631 else {
2632 VALUE methclass, klass, iclass;
2633 const rb_method_entry_t *me;
2634 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me);
2635 struct METHOD bound = { recv, klass, 0, me, METHOD_ENTRY_VISI(me) };
2637 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
2642 * Returns the number of required parameters and stores the maximum
2643 * number of parameters in max, or UNLIMITED_ARGUMENTS
2644 * if there is no maximum.
2646 static int
2647 method_def_min_max_arity(const rb_method_definition_t *def, int *max)
2649 again:
2650 if (!def) return *max = 0;
2651 switch (def->type) {
2652 case VM_METHOD_TYPE_CFUNC:
2653 if (def->body.cfunc.argc < 0) {
2654 *max = UNLIMITED_ARGUMENTS;
2655 return 0;
2657 return *max = check_argc(def->body.cfunc.argc);
2658 case VM_METHOD_TYPE_ZSUPER:
2659 *max = UNLIMITED_ARGUMENTS;
2660 return 0;
2661 case VM_METHOD_TYPE_ATTRSET:
2662 return *max = 1;
2663 case VM_METHOD_TYPE_IVAR:
2664 return *max = 0;
2665 case VM_METHOD_TYPE_ALIAS:
2666 def = def->body.alias.original_me->def;
2667 goto again;
2668 case VM_METHOD_TYPE_BMETHOD:
2669 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
2670 case VM_METHOD_TYPE_ISEQ:
2671 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
2672 case VM_METHOD_TYPE_UNDEF:
2673 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2674 return *max = 0;
2675 case VM_METHOD_TYPE_MISSING:
2676 *max = UNLIMITED_ARGUMENTS;
2677 return 0;
2678 case VM_METHOD_TYPE_OPTIMIZED: {
2679 switch (def->body.optimized.type) {
2680 case OPTIMIZED_METHOD_TYPE_SEND:
2681 *max = UNLIMITED_ARGUMENTS;
2682 return 0;
2683 case OPTIMIZED_METHOD_TYPE_CALL:
2684 *max = UNLIMITED_ARGUMENTS;
2685 return 0;
2686 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
2687 *max = UNLIMITED_ARGUMENTS;
2688 return 0;
2689 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
2690 *max = 0;
2691 return 0;
2692 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
2693 *max = 1;
2694 return 1;
2695 default:
2696 break;
2698 break;
2700 case VM_METHOD_TYPE_REFINED:
2701 *max = UNLIMITED_ARGUMENTS;
2702 return 0;
2704 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
2705 UNREACHABLE_RETURN(Qnil);
2708 static int
2709 method_def_arity(const rb_method_definition_t *def)
2711 int max, min = method_def_min_max_arity(def, &max);
2712 return min == max ? min : -min-1;
2716 rb_method_entry_arity(const rb_method_entry_t *me)
2718 return method_def_arity(me->def);
2722 * call-seq:
2723 * meth.arity -> integer
2725 * Returns an indication of the number of arguments accepted by a
2726 * method. Returns a nonnegative integer for methods that take a fixed
2727 * number of arguments. For Ruby methods that take a variable number of
2728 * arguments, returns -n-1, where n is the number of required arguments.
2729 * Keyword arguments will be considered as a single additional argument,
2730 * that argument being mandatory if any keyword argument is mandatory.
2731 * For methods written in C, returns -1 if the call takes a
2732 * variable number of arguments.
2734 * class C
2735 * def one; end
2736 * def two(a); end
2737 * def three(*a); end
2738 * def four(a, b); end
2739 * def five(a, b, *c); end
2740 * def six(a, b, *c, &d); end
2741 * def seven(a, b, x:0); end
2742 * def eight(x:, y:); end
2743 * def nine(x:, y:, **z); end
2744 * def ten(*a, x:, y:); end
2745 * end
2746 * c = C.new
2747 * c.method(:one).arity #=> 0
2748 * c.method(:two).arity #=> 1
2749 * c.method(:three).arity #=> -1
2750 * c.method(:four).arity #=> 2
2751 * c.method(:five).arity #=> -3
2752 * c.method(:six).arity #=> -3
2753 * c.method(:seven).arity #=> -3
2754 * c.method(:eight).arity #=> 1
2755 * c.method(:nine).arity #=> 1
2756 * c.method(:ten).arity #=> -2
2758 * "cat".method(:size).arity #=> 0
2759 * "cat".method(:replace).arity #=> 1
2760 * "cat".method(:squeeze).arity #=> -1
2761 * "cat".method(:count).arity #=> -1
2764 static VALUE
2765 method_arity_m(VALUE method)
2767 int n = method_arity(method);
2768 return INT2FIX(n);
2771 static int
2772 method_arity(VALUE method)
2774 struct METHOD *data;
2776 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2777 return rb_method_entry_arity(data->me);
2780 static const rb_method_entry_t *
2781 original_method_entry(VALUE mod, ID id)
2783 const rb_method_entry_t *me;
2785 while ((me = rb_method_entry(mod, id)) != 0) {
2786 const rb_method_definition_t *def = me->def;
2787 if (def->type != VM_METHOD_TYPE_ZSUPER) break;
2788 mod = RCLASS_SUPER(me->owner);
2789 id = def->original_id;
2791 return me;
2794 static int
2795 method_min_max_arity(VALUE method, int *max)
2797 const struct METHOD *data;
2799 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2800 return method_def_min_max_arity(data->me->def, max);
2804 rb_mod_method_arity(VALUE mod, ID id)
2806 const rb_method_entry_t *me = original_method_entry(mod, id);
2807 if (!me) return 0; /* should raise? */
2808 return rb_method_entry_arity(me);
2812 rb_obj_method_arity(VALUE obj, ID id)
2814 return rb_mod_method_arity(CLASS_OF(obj), id);
2817 VALUE
2818 rb_callable_receiver(VALUE callable)
2820 if (rb_obj_is_proc(callable)) {
2821 VALUE binding = proc_binding(callable);
2822 return rb_funcall(binding, rb_intern("receiver"), 0);
2824 else if (rb_obj_is_method(callable)) {
2825 return method_receiver(callable);
2827 else {
2828 return Qundef;
2832 const rb_method_definition_t *
2833 rb_method_def(VALUE method)
2835 const struct METHOD *data;
2837 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2838 return data->me->def;
2841 static const rb_iseq_t *
2842 method_def_iseq(const rb_method_definition_t *def)
2844 switch (def->type) {
2845 case VM_METHOD_TYPE_ISEQ:
2846 return rb_iseq_check(def->body.iseq.iseqptr);
2847 case VM_METHOD_TYPE_BMETHOD:
2848 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
2849 case VM_METHOD_TYPE_ALIAS:
2850 return method_def_iseq(def->body.alias.original_me->def);
2851 case VM_METHOD_TYPE_CFUNC:
2852 case VM_METHOD_TYPE_ATTRSET:
2853 case VM_METHOD_TYPE_IVAR:
2854 case VM_METHOD_TYPE_ZSUPER:
2855 case VM_METHOD_TYPE_UNDEF:
2856 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2857 case VM_METHOD_TYPE_OPTIMIZED:
2858 case VM_METHOD_TYPE_MISSING:
2859 case VM_METHOD_TYPE_REFINED:
2860 break;
2862 return NULL;
2865 const rb_iseq_t *
2866 rb_method_iseq(VALUE method)
2868 return method_def_iseq(rb_method_def(method));
2871 static const rb_cref_t *
2872 method_cref(VALUE method)
2874 const rb_method_definition_t *def = rb_method_def(method);
2876 again:
2877 switch (def->type) {
2878 case VM_METHOD_TYPE_ISEQ:
2879 return def->body.iseq.cref;
2880 case VM_METHOD_TYPE_ALIAS:
2881 def = def->body.alias.original_me->def;
2882 goto again;
2883 default:
2884 return NULL;
2888 static VALUE
2889 method_def_location(const rb_method_definition_t *def)
2891 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
2892 if (!def->body.attr.location)
2893 return Qnil;
2894 return rb_ary_dup(def->body.attr.location);
2896 return iseq_location(method_def_iseq(def));
2899 VALUE
2900 rb_method_entry_location(const rb_method_entry_t *me)
2902 if (!me) return Qnil;
2903 return method_def_location(me->def);
2907 * call-seq:
2908 * meth.source_location -> [String, Integer]
2910 * Returns the Ruby source filename and line number containing this method
2911 * or nil if this method was not defined in Ruby (i.e. native).
2914 VALUE
2915 rb_method_location(VALUE method)
2917 return method_def_location(rb_method_def(method));
2920 static const rb_method_definition_t *
2921 vm_proc_method_def(VALUE procval)
2923 const rb_proc_t *proc;
2924 const struct rb_block *block;
2925 const struct vm_ifunc *ifunc;
2927 GetProcPtr(procval, proc);
2928 block = &proc->block;
2930 if (vm_block_type(block) == block_type_ifunc &&
2931 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
2932 return rb_method_def((VALUE)ifunc->data);
2934 else {
2935 return NULL;
2939 static VALUE
2940 method_def_parameters(const rb_method_definition_t *def)
2942 const rb_iseq_t *iseq;
2943 const rb_method_definition_t *bmethod_def;
2945 switch (def->type) {
2946 case VM_METHOD_TYPE_ISEQ:
2947 iseq = method_def_iseq(def);
2948 return rb_iseq_parameters(iseq, 0);
2949 case VM_METHOD_TYPE_BMETHOD:
2950 if ((iseq = method_def_iseq(def)) != NULL) {
2951 return rb_iseq_parameters(iseq, 0);
2953 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
2954 return method_def_parameters(bmethod_def);
2956 break;
2958 case VM_METHOD_TYPE_ALIAS:
2959 return method_def_parameters(def->body.alias.original_me->def);
2961 case VM_METHOD_TYPE_OPTIMIZED:
2962 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
2963 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
2964 return rb_ary_new_from_args(1, param);
2966 break;
2968 case VM_METHOD_TYPE_CFUNC:
2969 case VM_METHOD_TYPE_ATTRSET:
2970 case VM_METHOD_TYPE_IVAR:
2971 case VM_METHOD_TYPE_ZSUPER:
2972 case VM_METHOD_TYPE_UNDEF:
2973 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2974 case VM_METHOD_TYPE_MISSING:
2975 case VM_METHOD_TYPE_REFINED:
2976 break;
2979 return rb_unnamed_parameters(method_def_arity(def));
2984 * call-seq:
2985 * meth.parameters -> array
2987 * Returns the parameter information of this method.
2989 * def foo(bar); end
2990 * method(:foo).parameters #=> [[:req, :bar]]
2992 * def foo(bar, baz, bat, &blk); end
2993 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
2995 * def foo(bar, *args); end
2996 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
2998 * def foo(bar, baz, *args, &blk); end
2999 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
3002 static VALUE
3003 rb_method_parameters(VALUE method)
3005 return method_def_parameters(rb_method_def(method));
3009 * call-seq:
3010 * meth.to_s -> string
3011 * meth.inspect -> string
3013 * Returns a human-readable description of the underlying method.
3015 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3016 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3018 * In the latter case, the method description includes the "owner" of the
3019 * original method (+Enumerable+ module, which is included into +Range+).
3021 * +inspect+ also provides, when possible, method argument names (call
3022 * sequence) and source location.
3024 * require 'net/http'
3025 * Net::HTTP.method(:get).inspect
3026 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3028 * <code>...</code> in argument definition means argument is optional (has
3029 * some default value).
3031 * For methods defined in C (language core and extensions), location and
3032 * argument names can't be extracted, and only generic information is provided
3033 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3034 * positional argument).
3036 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3037 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3041 static VALUE
3042 method_inspect(VALUE method)
3044 struct METHOD *data;
3045 VALUE str;
3046 const char *sharp = "#";
3047 VALUE mklass;
3048 VALUE defined_class;
3050 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3051 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
3053 mklass = data->iclass;
3054 if (!mklass) mklass = data->klass;
3056 if (RB_TYPE_P(mklass, T_ICLASS)) {
3057 /* TODO: I'm not sure why mklass is T_ICLASS.
3058 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3059 * but not sure it is needed.
3061 mklass = RBASIC_CLASS(mklass);
3064 if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
3065 defined_class = data->me->def->body.alias.original_me->owner;
3067 else {
3068 defined_class = method_entry_defined_class(data->me);
3071 if (RB_TYPE_P(defined_class, T_ICLASS)) {
3072 defined_class = RBASIC_CLASS(defined_class);
3075 if (FL_TEST(mklass, FL_SINGLETON)) {
3076 VALUE v = rb_ivar_get(mklass, attached);
3078 if (data->recv == Qundef) {
3079 rb_str_buf_append(str, rb_inspect(mklass));
3081 else if (data->recv == v) {
3082 rb_str_buf_append(str, rb_inspect(v));
3083 sharp = ".";
3085 else {
3086 rb_str_buf_append(str, rb_inspect(data->recv));
3087 rb_str_buf_cat2(str, "(");
3088 rb_str_buf_append(str, rb_inspect(v));
3089 rb_str_buf_cat2(str, ")");
3090 sharp = ".";
3093 else {
3094 mklass = data->klass;
3095 if (FL_TEST(mklass, FL_SINGLETON)) {
3096 VALUE v = rb_ivar_get(mklass, attached);
3097 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
3098 do {
3099 mklass = RCLASS_SUPER(mklass);
3100 } while (RB_TYPE_P(mklass, T_ICLASS));
3103 rb_str_buf_append(str, rb_inspect(mklass));
3104 if (defined_class != mklass) {
3105 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
3108 rb_str_buf_cat2(str, sharp);
3109 rb_str_append(str, rb_id2str(data->me->called_id));
3110 if (data->me->called_id != data->me->def->original_id) {
3111 rb_str_catf(str, "(%"PRIsVALUE")",
3112 rb_id2str(data->me->def->original_id));
3114 if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
3115 rb_str_buf_cat2(str, " (not-implemented)");
3118 // parameter information
3120 VALUE params = rb_method_parameters(method);
3121 VALUE pair, name, kind;
3122 const VALUE req = ID2SYM(rb_intern("req"));
3123 const VALUE opt = ID2SYM(rb_intern("opt"));
3124 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
3125 const VALUE key = ID2SYM(rb_intern("key"));
3126 const VALUE rest = ID2SYM(rb_intern("rest"));
3127 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
3128 const VALUE block = ID2SYM(rb_intern("block"));
3129 const VALUE nokey = ID2SYM(rb_intern("nokey"));
3130 int forwarding = 0;
3132 rb_str_buf_cat2(str, "(");
3134 if (RARRAY_LEN(params) == 3 &&
3135 RARRAY_AREF(RARRAY_AREF(params, 0), 0) == rest &&
3136 RARRAY_AREF(RARRAY_AREF(params, 0), 1) == ID2SYM('*') &&
3137 RARRAY_AREF(RARRAY_AREF(params, 1), 0) == keyrest &&
3138 RARRAY_AREF(RARRAY_AREF(params, 1), 1) == ID2SYM(idPow) &&
3139 RARRAY_AREF(RARRAY_AREF(params, 2), 0) == block &&
3140 RARRAY_AREF(RARRAY_AREF(params, 2), 1) == ID2SYM('&')) {
3141 forwarding = 1;
3144 for (int i = 0; i < RARRAY_LEN(params); i++) {
3145 pair = RARRAY_AREF(params, i);
3146 kind = RARRAY_AREF(pair, 0);
3147 name = RARRAY_AREF(pair, 1);
3148 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3149 if (NIL_P(name) || name == Qfalse) {
3150 // FIXME: can it be reduced to switch/case?
3151 if (kind == req || kind == opt) {
3152 name = rb_str_new2("_");
3154 else if (kind == rest || kind == keyrest) {
3155 name = rb_str_new2("");
3157 else if (kind == block) {
3158 name = rb_str_new2("block");
3160 else if (kind == nokey) {
3161 name = rb_str_new2("nil");
3165 if (kind == req) {
3166 rb_str_catf(str, "%"PRIsVALUE, name);
3168 else if (kind == opt) {
3169 rb_str_catf(str, "%"PRIsVALUE"=...", name);
3171 else if (kind == keyreq) {
3172 rb_str_catf(str, "%"PRIsVALUE":", name);
3174 else if (kind == key) {
3175 rb_str_catf(str, "%"PRIsVALUE": ...", name);
3177 else if (kind == rest) {
3178 if (name == ID2SYM('*')) {
3179 rb_str_cat_cstr(str, forwarding ? "..." : "*");
3181 else {
3182 rb_str_catf(str, "*%"PRIsVALUE, name);
3185 else if (kind == keyrest) {
3186 if (name != ID2SYM(idPow)) {
3187 rb_str_catf(str, "**%"PRIsVALUE, name);
3189 else if (i > 0) {
3190 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3192 else {
3193 rb_str_cat_cstr(str, "**");
3196 else if (kind == block) {
3197 if (name == ID2SYM('&')) {
3198 if (forwarding) {
3199 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3201 else {
3202 rb_str_cat_cstr(str, "...");
3205 else {
3206 rb_str_catf(str, "&%"PRIsVALUE, name);
3209 else if (kind == nokey) {
3210 rb_str_buf_cat2(str, "**nil");
3213 if (i < RARRAY_LEN(params) - 1) {
3214 rb_str_buf_cat2(str, ", ");
3217 rb_str_buf_cat2(str, ")");
3220 { // source location
3221 VALUE loc = rb_method_location(method);
3222 if (!NIL_P(loc)) {
3223 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
3224 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
3228 rb_str_buf_cat2(str, ">");
3230 return str;
3233 static VALUE
3234 bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
3236 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
3239 VALUE
3240 rb_proc_new(
3241 rb_block_call_func_t func,
3242 VALUE val)
3244 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
3245 return procval;
3249 * call-seq:
3250 * meth.to_proc -> proc
3252 * Returns a Proc object corresponding to this method.
3255 static VALUE
3256 method_to_proc(VALUE method)
3258 VALUE procval;
3259 rb_proc_t *proc;
3262 * class Method
3263 * def to_proc
3264 * lambda{|*args|
3265 * self.call(*args)
3267 * end
3268 * end
3270 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
3271 GetProcPtr(procval, proc);
3272 proc->is_from_method = 1;
3273 return procval;
3276 extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
3279 * call-seq:
3280 * meth.super_method -> method
3282 * Returns a Method of superclass which would be called when super is used
3283 * or nil if there is no method on superclass.
3286 static VALUE
3287 method_super_method(VALUE method)
3289 const struct METHOD *data;
3290 VALUE super_class, iclass;
3291 ID mid;
3292 const rb_method_entry_t *me;
3294 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3295 iclass = data->iclass;
3296 if (!iclass) return Qnil;
3297 if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
3298 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
3299 data->me->def->body.alias.original_me->owner));
3300 mid = data->me->def->body.alias.original_me->def->original_id;
3302 else {
3303 super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
3304 mid = data->me->def->original_id;
3306 if (!super_class) return Qnil;
3307 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
3308 if (!me) return Qnil;
3309 return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
3313 * call-seq:
3314 * meth.public? -> true or false
3316 * Returns whether the method is public.
3319 static VALUE
3320 method_public_p(VALUE method)
3322 const struct METHOD *data;
3323 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3324 return RBOOL(data->visibility == METHOD_VISI_PUBLIC);
3328 * call-seq:
3329 * meth.protected? -> true or false
3331 * Returns whether the method is protected.
3334 static VALUE
3335 method_protected_p(VALUE method)
3337 const struct METHOD *data;
3338 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3339 return RBOOL(data->visibility == METHOD_VISI_PROTECTED);
3343 * call-seq:
3344 * meth.private? -> true or false
3346 * Returns whether the method is private.
3349 static VALUE
3350 method_private_p(VALUE method)
3352 const struct METHOD *data;
3353 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3354 return RBOOL(data->visibility == METHOD_VISI_PRIVATE);
3358 * call-seq:
3359 * local_jump_error.exit_value -> obj
3361 * Returns the exit value associated with this +LocalJumpError+.
3363 static VALUE
3364 localjump_xvalue(VALUE exc)
3366 return rb_iv_get(exc, "@exit_value");
3370 * call-seq:
3371 * local_jump_error.reason -> symbol
3373 * The reason this block was terminated:
3374 * :break, :redo, :retry, :next, :return, or :noreason.
3377 static VALUE
3378 localjump_reason(VALUE exc)
3380 return rb_iv_get(exc, "@reason");
3383 rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
3385 static const rb_env_t *
3386 env_clone(const rb_env_t *env, const rb_cref_t *cref)
3388 VALUE *new_ep;
3389 VALUE *new_body;
3390 const rb_env_t *new_env;
3392 VM_ASSERT(env->ep > env->env);
3393 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
3395 if (cref == NULL) {
3396 cref = rb_vm_cref_new_toplevel();
3399 new_body = ALLOC_N(VALUE, env->env_size);
3400 MEMCPY(new_body, env->env, VALUE, env->env_size);
3401 new_ep = &new_body[env->ep - env->env];
3402 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
3403 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
3404 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
3405 return new_env;
3409 * call-seq:
3410 * prc.binding -> binding
3412 * Returns the binding associated with <i>prc</i>.
3414 * def fred(param)
3415 * proc {}
3416 * end
3418 * b = fred(99)
3419 * eval("param", b.binding) #=> 99
3421 static VALUE
3422 proc_binding(VALUE self)
3424 VALUE bindval, binding_self = Qundef;
3425 rb_binding_t *bind;
3426 const rb_proc_t *proc;
3427 const rb_iseq_t *iseq = NULL;
3428 const struct rb_block *block;
3429 const rb_env_t *env = NULL;
3431 GetProcPtr(self, proc);
3432 block = &proc->block;
3434 if (proc->is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
3436 again:
3437 switch (vm_block_type(block)) {
3438 case block_type_iseq:
3439 iseq = block->as.captured.code.iseq;
3440 binding_self = block->as.captured.self;
3441 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3442 break;
3443 case block_type_proc:
3444 GetProcPtr(block->as.proc, proc);
3445 block = &proc->block;
3446 goto again;
3447 case block_type_ifunc:
3449 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
3450 if (IS_METHOD_PROC_IFUNC(ifunc)) {
3451 VALUE method = (VALUE)ifunc->data;
3452 VALUE name = rb_fstring_lit("<empty_iseq>");
3453 rb_iseq_t *empty;
3454 binding_self = method_receiver(method);
3455 iseq = rb_method_iseq(method);
3456 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3457 env = env_clone(env, method_cref(method));
3458 /* set empty iseq */
3459 empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP);
3460 RB_OBJ_WRITE(env, &env->iseq, empty);
3461 break;
3464 /* FALLTHROUGH */
3465 case block_type_symbol:
3466 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
3467 UNREACHABLE_RETURN(Qnil);
3470 bindval = rb_binding_alloc(rb_cBinding);
3471 GetBindingPtr(bindval, bind);
3472 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
3473 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
3474 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
3475 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
3477 if (iseq) {
3478 rb_iseq_check(iseq);
3479 RB_OBJ_WRITE(bindval, &bind->pathobj, iseq->body->location.pathobj);
3480 bind->first_lineno = FIX2INT(rb_iseq_first_lineno(iseq));
3482 else {
3483 RB_OBJ_WRITE(bindval, &bind->pathobj,
3484 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
3485 bind->first_lineno = 1;
3488 return bindval;
3491 static rb_block_call_func curry;
3493 static VALUE
3494 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
3496 VALUE args = rb_ary_new3(3, proc, passed, arity);
3497 rb_proc_t *procp;
3498 int is_lambda;
3500 GetProcPtr(proc, procp);
3501 is_lambda = procp->is_lambda;
3502 rb_ary_freeze(passed);
3503 rb_ary_freeze(args);
3504 proc = rb_proc_new(curry, args);
3505 GetProcPtr(proc, procp);
3506 procp->is_lambda = is_lambda;
3507 return proc;
3510 static VALUE
3511 curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3513 VALUE proc, passed, arity;
3514 proc = RARRAY_AREF(args, 0);
3515 passed = RARRAY_AREF(args, 1);
3516 arity = RARRAY_AREF(args, 2);
3518 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
3519 rb_ary_freeze(passed);
3521 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
3522 if (!NIL_P(blockarg)) {
3523 rb_warn("given block not used");
3525 arity = make_curry_proc(proc, passed, arity);
3526 return arity;
3528 else {
3529 return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
3534 * call-seq:
3535 * prc.curry -> a_proc
3536 * prc.curry(arity) -> a_proc
3538 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3539 * it determines the number of arguments.
3540 * A curried proc receives some arguments. If a sufficient number of
3541 * arguments are supplied, it passes the supplied arguments to the original
3542 * proc and returns the result. Otherwise, returns another curried proc that
3543 * takes the rest of arguments.
3545 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3546 * p b.curry[1][2][3] #=> 6
3547 * p b.curry[1, 2][3, 4] #=> 6
3548 * p b.curry(5)[1][2][3][4][5] #=> 6
3549 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3550 * p b.curry(1)[1] #=> 1
3552 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3553 * p b.curry[1][2][3] #=> 6
3554 * p b.curry[1, 2][3, 4] #=> 10
3555 * p b.curry(5)[1][2][3][4][5] #=> 15
3556 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3557 * p b.curry(1)[1] #=> 1
3559 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3560 * p b.curry[1][2][3] #=> 6
3561 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3562 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3563 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3565 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3566 * p b.curry[1][2][3] #=> 6
3567 * p b.curry[1, 2][3, 4] #=> 10
3568 * p b.curry(5)[1][2][3][4][5] #=> 15
3569 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3570 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3572 * b = proc { :foo }
3573 * p b.curry[] #=> :foo
3575 static VALUE
3576 proc_curry(int argc, const VALUE *argv, VALUE self)
3578 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
3579 VALUE arity;
3581 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
3582 arity = INT2FIX(min_arity);
3584 else {
3585 sarity = FIX2INT(arity);
3586 if (rb_proc_lambda_p(self)) {
3587 rb_check_arity(sarity, min_arity, max_arity);
3591 return make_curry_proc(self, rb_ary_new(), arity);
3595 * call-seq:
3596 * meth.curry -> proc
3597 * meth.curry(arity) -> proc
3599 * Returns a curried proc based on the method. When the proc is called with a number of
3600 * arguments that is lower than the method's arity, then another curried proc is returned.
3601 * Only when enough arguments have been supplied to satisfy the method signature, will the
3602 * method actually be called.
3604 * The optional <i>arity</i> argument should be supplied when currying methods with
3605 * variable arguments to determine how many arguments are needed before the method is
3606 * called.
3608 * def foo(a,b,c)
3609 * [a, b, c]
3610 * end
3612 * proc = self.method(:foo).curry
3613 * proc2 = proc.call(1, 2) #=> #<Proc>
3614 * proc2.call(3) #=> [1,2,3]
3616 * def vararg(*args)
3617 * args
3618 * end
3620 * proc = self.method(:vararg).curry(4)
3621 * proc2 = proc.call(:x) #=> #<Proc>
3622 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3623 * proc3.call(:a) #=> [:x, :y, :z, :a]
3626 static VALUE
3627 rb_method_curry(int argc, const VALUE *argv, VALUE self)
3629 VALUE proc = method_to_proc(self);
3630 return proc_curry(argc, argv, proc);
3633 static VALUE
3634 compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3636 VALUE f, g, fargs;
3637 f = RARRAY_AREF(args, 0);
3638 g = RARRAY_AREF(args, 1);
3640 if (rb_obj_is_proc(g))
3641 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3642 else
3643 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3645 if (rb_obj_is_proc(f))
3646 return rb_proc_call(f, rb_ary_new3(1, fargs));
3647 else
3648 return rb_funcallv(f, idCall, 1, &fargs);
3651 static VALUE
3652 to_callable(VALUE f)
3654 VALUE mesg;
3656 if (rb_obj_is_proc(f)) return f;
3657 if (rb_obj_is_method(f)) return f;
3658 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
3659 mesg = rb_fstring_lit("callable object is expected");
3660 rb_exc_raise(rb_exc_new_str(rb_eTypeError, mesg));
3663 static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
3664 static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
3667 * call-seq:
3668 * prc << g -> a_proc
3670 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3671 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3672 * then calls this proc with the result.
3674 * f = proc {|x| x * x }
3675 * g = proc {|x| x + x }
3676 * p (f << g).call(2) #=> 16
3678 * See Proc#>> for detailed explanations.
3680 static VALUE
3681 proc_compose_to_left(VALUE self, VALUE g)
3683 return rb_proc_compose_to_left(self, to_callable(g));
3686 static VALUE
3687 rb_proc_compose_to_left(VALUE self, VALUE g)
3689 VALUE proc, args, procs[2];
3690 rb_proc_t *procp;
3691 int is_lambda;
3693 procs[0] = self;
3694 procs[1] = g;
3695 args = rb_ary_tmp_new_from_values(0, 2, procs);
3697 if (rb_obj_is_proc(g)) {
3698 GetProcPtr(g, procp);
3699 is_lambda = procp->is_lambda;
3701 else {
3702 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
3703 is_lambda = 1;
3706 proc = rb_proc_new(compose, args);
3707 GetProcPtr(proc, procp);
3708 procp->is_lambda = is_lambda;
3710 return proc;
3714 * call-seq:
3715 * prc >> g -> a_proc
3717 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3718 * The returned proc takes a variable number of arguments, calls this proc with them
3719 * then calls <i>g</i> with the result.
3721 * f = proc {|x| x * x }
3722 * g = proc {|x| x + x }
3723 * p (f >> g).call(2) #=> 8
3725 * <i>g</i> could be other Proc, or Method, or any other object responding to
3726 * +call+ method:
3728 * class Parser
3729 * def self.call(text)
3730 * # ...some complicated parsing logic...
3731 * end
3732 * end
3734 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3735 * pipeline.call('data.json')
3737 * See also Method#>> and Method#<<.
3739 static VALUE
3740 proc_compose_to_right(VALUE self, VALUE g)
3742 return rb_proc_compose_to_right(self, to_callable(g));
3745 static VALUE
3746 rb_proc_compose_to_right(VALUE self, VALUE g)
3748 VALUE proc, args, procs[2];
3749 rb_proc_t *procp;
3750 int is_lambda;
3752 procs[0] = g;
3753 procs[1] = self;
3754 args = rb_ary_tmp_new_from_values(0, 2, procs);
3756 GetProcPtr(self, procp);
3757 is_lambda = procp->is_lambda;
3759 proc = rb_proc_new(compose, args);
3760 GetProcPtr(proc, procp);
3761 procp->is_lambda = is_lambda;
3763 return proc;
3767 * call-seq:
3768 * meth << g -> a_proc
3770 * Returns a proc that is the composition of this method and the given <i>g</i>.
3771 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3772 * then calls this method with the result.
3774 * def f(x)
3775 * x * x
3776 * end
3778 * f = self.method(:f)
3779 * g = proc {|x| x + x }
3780 * p (f << g).call(2) #=> 16
3782 static VALUE
3783 rb_method_compose_to_left(VALUE self, VALUE g)
3785 g = to_callable(g);
3786 self = method_to_proc(self);
3787 return proc_compose_to_left(self, g);
3791 * call-seq:
3792 * meth >> g -> a_proc
3794 * Returns a proc that is the composition of this method and the given <i>g</i>.
3795 * The returned proc takes a variable number of arguments, calls this method
3796 * with them then calls <i>g</i> with the result.
3798 * def f(x)
3799 * x * x
3800 * end
3802 * f = self.method(:f)
3803 * g = proc {|x| x + x }
3804 * p (f >> g).call(2) #=> 8
3806 static VALUE
3807 rb_method_compose_to_right(VALUE self, VALUE g)
3809 g = to_callable(g);
3810 self = method_to_proc(self);
3811 return proc_compose_to_right(self, g);
3815 * call-seq:
3816 * proc.ruby2_keywords -> proc
3818 * Marks the proc as passing keywords through a normal argument splat.
3819 * This should only be called on procs that accept an argument splat
3820 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3821 * marks the proc such that if the proc is called with keyword arguments,
3822 * the final hash argument is marked with a special flag such that if it
3823 * is the final element of a normal argument splat to another method call,
3824 * and that method call does not include explicit keywords or a keyword
3825 * splat, the final element is interpreted as keywords. In other words,
3826 * keywords will be passed through the proc to other methods.
3828 * This should only be used for procs that delegate keywords to another
3829 * method, and only for backwards compatibility with Ruby versions before
3830 * 2.7.
3832 * This method will probably be removed at some point, as it exists only
3833 * for backwards compatibility. As it does not exist in Ruby versions
3834 * before 2.7, check that the proc responds to this method before calling
3835 * it. Also, be aware that if this method is removed, the behavior of the
3836 * proc will change so that it does not pass through keywords.
3838 * module Mod
3839 * foo = ->(meth, *args, &block) do
3840 * send(:"do_#{meth}", *args, &block)
3841 * end
3842 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3843 * end
3846 static VALUE
3847 proc_ruby2_keywords(VALUE procval)
3849 rb_proc_t *proc;
3850 GetProcPtr(procval, proc);
3852 rb_check_frozen(procval);
3854 if (proc->is_from_method) {
3855 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
3856 return procval;
3859 switch (proc->block.type) {
3860 case block_type_iseq:
3861 if (proc->block.as.captured.code.iseq->body->param.flags.has_rest &&
3862 !proc->block.as.captured.code.iseq->body->param.flags.has_kw &&
3863 !proc->block.as.captured.code.iseq->body->param.flags.has_kwrest) {
3864 proc->block.as.captured.code.iseq->body->param.flags.ruby2_keywords = 1;
3866 else {
3867 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
3869 break;
3870 default:
3871 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
3872 break;
3875 return procval;
3879 * Document-class: LocalJumpError
3881 * Raised when Ruby can't yield as requested.
3883 * A typical scenario is attempting to yield when no block is given:
3885 * def call_block
3886 * yield 42
3887 * end
3888 * call_block
3890 * <em>raises the exception:</em>
3892 * LocalJumpError: no block given (yield)
3894 * A more subtle example:
3896 * def get_me_a_return
3897 * Proc.new { return 42 }
3898 * end
3899 * get_me_a_return.call
3901 * <em>raises the exception:</em>
3903 * LocalJumpError: unexpected return
3907 * Document-class: SystemStackError
3909 * Raised in case of a stack overflow.
3911 * def me_myself_and_i
3912 * me_myself_and_i
3913 * end
3914 * me_myself_and_i
3916 * <em>raises the exception:</em>
3918 * SystemStackError: stack level too deep
3922 * Document-class: Proc
3924 * A +Proc+ object is an encapsulation of a block of code, which can be stored
3925 * in a local variable, passed to a method or another Proc, and can be called.
3926 * Proc is an essential concept in Ruby and a core of its functional
3927 * programming features.
3929 * square = Proc.new {|x| x**2 }
3931 * square.call(3) #=> 9
3932 * # shorthands:
3933 * square.(3) #=> 9
3934 * square[3] #=> 9
3936 * Proc objects are _closures_, meaning they remember and can use the entire
3937 * context in which they were created.
3939 * def gen_times(factor)
3940 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
3941 * end
3943 * times3 = gen_times(3)
3944 * times5 = gen_times(5)
3946 * times3.call(12) #=> 36
3947 * times5.call(5) #=> 25
3948 * times3.call(times5.call(4)) #=> 60
3950 * == Creation
3952 * There are several methods to create a Proc
3954 * * Use the Proc class constructor:
3956 * proc1 = Proc.new {|x| x**2 }
3958 * * Use the Kernel#proc method as a shorthand of Proc.new:
3960 * proc2 = proc {|x| x**2 }
3962 * * Receiving a block of code into proc argument (note the <code>&</code>):
3964 * def make_proc(&block)
3965 * block
3966 * end
3968 * proc3 = make_proc {|x| x**2 }
3970 * * Construct a proc with lambda semantics using the Kernel#lambda method
3971 * (see below for explanations about lambdas):
3973 * lambda1 = lambda {|x| x**2 }
3975 * * Use the {Lambda proc literal}[doc/syntax/literals_rdoc.html#label-Lambda+Proc+Literals] syntax
3976 * (also constructs a proc with lambda semantics):
3978 * lambda2 = ->(x) { x**2 }
3980 * == Lambda and non-lambda semantics
3982 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
3983 * Differences are:
3985 * * In lambdas, +return+ and +break+ means exit from this lambda;
3986 * * In non-lambda procs, +return+ means exit from embracing method
3987 * (and will throw +LocalJumpError+ if invoked outside the method);
3988 * * In non-lambda procs, +break+ means exit from the method which the block given for.
3989 * (and will throw +LocalJumpError+ if invoked after the method returns);
3990 * * In lambdas, arguments are treated in the same way as in methods: strict,
3991 * with +ArgumentError+ for mismatching argument number,
3992 * and no additional argument processing;
3993 * * Regular procs accept arguments more generously: missing arguments
3994 * are filled with +nil+, single Array arguments are deconstructed if the
3995 * proc has multiple arguments, and there is no error raised on extra
3996 * arguments.
3998 * Examples:
4000 * # +return+ in non-lambda proc, +b+, exits +m2+.
4001 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
4002 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
4003 * #=> []
4005 * # +break+ in non-lambda proc, +b+, exits +m1+.
4006 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
4007 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
4008 * #=> [:m2]
4010 * # +next+ in non-lambda proc, +b+, exits the block.
4011 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
4012 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
4013 * #=> [:m1, :m2]
4015 * # Using +proc+ method changes the behavior as follows because
4016 * # The block is given for +proc+ method and embraced by +m2+.
4017 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
4018 * #=> []
4019 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4020 * # break from proc-closure (LocalJumpError)
4021 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4022 * #=> [:m1, :m2]
4024 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4025 * # (+lambda+ method behaves same.)
4026 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4027 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4028 * #=> [:m1, :m2]
4029 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4030 * #=> [:m1, :m2]
4031 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
4032 * #=> [:m1, :m2]
4034 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4035 * p.call(1, 2) #=> "x=1, y=2"
4036 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4037 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4038 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4040 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4041 * l.call(1, 2) #=> "x=1, y=2"
4042 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4043 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4044 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4046 * def test_return
4047 * -> { return 3 }.call # just returns from lambda into method body
4048 * proc { return 4 }.call # returns from method
4049 * return 5
4050 * end
4052 * test_return # => 4, return from proc
4054 * Lambdas are useful as self-sufficient functions, in particular useful as
4055 * arguments to higher-order functions, behaving exactly like Ruby methods.
4057 * Procs are useful for implementing iterators:
4059 * def test
4060 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4061 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4062 * end
4064 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4065 * which means that the internal arrays will be deconstructed to pairs of
4066 * arguments, and +return+ will exit from the method +test+. That would
4067 * not be possible with a stricter lambda.
4069 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4071 * Lambda semantics is typically preserved during the proc lifetime, including
4072 * <code>&</code>-deconstruction to a block of code:
4074 * p = proc {|x, y| x }
4075 * l = lambda {|x, y| x }
4076 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4077 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4079 * The only exception is dynamic method definition: even if defined by
4080 * passing a non-lambda proc, methods still have normal semantics of argument
4081 * checking.
4083 * class C
4084 * define_method(:e, &proc {})
4085 * end
4086 * C.new.e(1,2) #=> ArgumentError
4087 * C.new.method(:e).to_proc.lambda? #=> true
4089 * This exception ensures that methods never have unusual argument passing
4090 * conventions, and makes it easy to have wrappers defining methods that
4091 * behave as usual.
4093 * class C
4094 * def self.def2(name, &body)
4095 * define_method(name, &body)
4096 * end
4098 * def2(:f) {}
4099 * end
4100 * C.new.f(1,2) #=> ArgumentError
4102 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4103 * yet defines a method which has normal semantics.
4105 * == Conversion of other objects to procs
4107 * Any object that implements the +to_proc+ method can be converted into
4108 * a proc by the <code>&</code> operator, and therefore can be
4109 * consumed by iterators.
4112 * class Greeter
4113 * def initialize(greeting)
4114 * @greeting = greeting
4115 * end
4117 * def to_proc
4118 * proc {|name| "#{@greeting}, #{name}!" }
4119 * end
4120 * end
4122 * hi = Greeter.new("Hi")
4123 * hey = Greeter.new("Hey")
4124 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4125 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4127 * Of the Ruby core classes, this method is implemented by Symbol,
4128 * Method, and Hash.
4130 * :to_s.to_proc.call(1) #=> "1"
4131 * [1, 2].map(&:to_s) #=> ["1", "2"]
4133 * method(:puts).to_proc.call(1) # prints 1
4134 * [1, 2].each(&method(:puts)) # prints 1, 2
4136 * {test: 1}.to_proc.call(:test) #=> 1
4137 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4139 * == Orphaned Proc
4141 * +return+ and +break+ in a block exit a method.
4142 * If a Proc object is generated from the block and the Proc object
4143 * survives until the method is returned, +return+ and +break+ cannot work.
4144 * In such case, +return+ and +break+ raises LocalJumpError.
4145 * A Proc object in such situation is called as orphaned Proc object.
4147 * Note that the method to exit is different for +return+ and +break+.
4148 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4150 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4151 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4153 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4154 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4156 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4157 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4159 * Since +return+ and +break+ exits the block itself in lambdas,
4160 * lambdas cannot be orphaned.
4162 * == Numbered parameters
4164 * Numbered parameters are implicitly defined block parameters intended to
4165 * simplify writing short blocks:
4167 * # Explicit parameter:
4168 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4169 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4171 * # Implicit parameter:
4172 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4173 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4175 * Parameter names from +_1+ to +_9+ are supported:
4177 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4178 * # => [120, 150, 180]
4180 * Though, it is advised to resort to them wisely, probably limiting
4181 * yourself to +_1+ and +_2+, and to one-line blocks.
4183 * Numbered parameters can't be used together with explicitly named
4184 * ones:
4186 * [10, 20, 30].map { |x| _1**2 }
4187 * # SyntaxError (ordinary parameter is defined)
4189 * To avoid conflicts, naming local variables or method
4190 * arguments +_1+, +_2+ and so on, causes a warning.
4192 * _1 = 'test'
4193 * # warning: `_1' is reserved as numbered parameter
4195 * Using implicit numbered parameters affects block's arity:
4197 * p = proc { _1 + _2 }
4198 * l = lambda { _1 + _2 }
4199 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4200 * p.arity # => 2
4201 * l.parameters # => [[:req, :_1], [:req, :_2]]
4202 * l.arity # => 2
4204 * Blocks with numbered parameters can't be nested:
4206 * %w[test me].each { _1.each_char { p _1 } }
4207 * # SyntaxError (numbered parameter is already used in outer block here)
4208 * # %w[test me].each { _1.each_char { p _1 } }
4209 * # ^~
4211 * Numbered parameters were introduced in Ruby 2.7.
4215 void
4216 Init_Proc(void)
4218 #undef rb_intern
4219 /* Proc */
4220 rb_cProc = rb_define_class("Proc", rb_cObject);
4221 rb_undef_alloc_func(rb_cProc);
4222 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
4224 rb_add_method_optimized(rb_cProc, idCall, OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4225 rb_add_method_optimized(rb_cProc, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4226 rb_add_method_optimized(rb_cProc, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4227 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4229 #if 0 /* for RDoc */
4230 rb_define_method(rb_cProc, "call", proc_call, -1);
4231 rb_define_method(rb_cProc, "[]", proc_call, -1);
4232 rb_define_method(rb_cProc, "===", proc_call, -1);
4233 rb_define_method(rb_cProc, "yield", proc_call, -1);
4234 #endif
4236 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
4237 rb_define_method(rb_cProc, "arity", proc_arity, 0);
4238 rb_define_method(rb_cProc, "clone", proc_clone, 0);
4239 rb_define_method(rb_cProc, "dup", rb_proc_dup, 0);
4240 rb_define_method(rb_cProc, "hash", proc_hash, 0);
4241 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
4242 rb_define_alias(rb_cProc, "inspect", "to_s");
4243 rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
4244 rb_define_method(rb_cProc, "binding", proc_binding, 0);
4245 rb_define_method(rb_cProc, "curry", proc_curry, -1);
4246 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
4247 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
4248 rb_define_method(rb_cProc, "==", proc_eq, 1);
4249 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
4250 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
4251 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, 0);
4252 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
4253 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4255 /* Exceptions */
4256 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
4257 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
4258 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
4260 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
4261 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
4263 /* utility functions */
4264 rb_define_global_function("proc", f_proc, 0);
4265 rb_define_global_function("lambda", f_lambda, 0);
4267 /* Method */
4268 rb_cMethod = rb_define_class("Method", rb_cObject);
4269 rb_undef_alloc_func(rb_cMethod);
4270 rb_undef_method(CLASS_OF(rb_cMethod), "new");
4271 rb_define_method(rb_cMethod, "==", method_eq, 1);
4272 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
4273 rb_define_method(rb_cMethod, "hash", method_hash, 0);
4274 rb_define_method(rb_cMethod, "clone", method_clone, 0);
4275 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
4276 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
4277 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
4278 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
4279 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
4280 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
4281 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
4282 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
4283 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
4284 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
4285 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
4286 rb_define_method(rb_cMethod, "name", method_name, 0);
4287 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
4288 rb_define_method(rb_cMethod, "owner", method_owner, 0);
4289 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
4290 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
4291 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
4292 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
4293 rb_define_method(rb_cMethod, "public?", method_public_p, 0);
4294 rb_define_method(rb_cMethod, "protected?", method_protected_p, 0);
4295 rb_define_method(rb_cMethod, "private?", method_private_p, 0);
4296 rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
4297 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
4298 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
4300 /* UnboundMethod */
4301 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
4302 rb_undef_alloc_func(rb_cUnboundMethod);
4303 rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
4304 rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
4305 rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
4306 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
4307 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
4308 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
4309 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
4310 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
4311 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
4312 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
4313 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
4314 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
4315 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
4316 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
4317 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
4318 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
4319 rb_define_method(rb_cUnboundMethod, "public?", method_public_p, 0);
4320 rb_define_method(rb_cUnboundMethod, "protected?", method_protected_p, 0);
4321 rb_define_method(rb_cUnboundMethod, "private?", method_private_p, 0);
4323 /* Module#*_method */
4324 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
4325 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
4326 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
4328 /* Kernel */
4329 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
4331 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
4332 "define_method", top_define_method, -1);
4336 * Objects of class Binding encapsulate the execution context at some
4337 * particular place in the code and retain this context for future
4338 * use. The variables, methods, value of <code>self</code>, and
4339 * possibly an iterator block that can be accessed in this context
4340 * are all retained. Binding objects can be created using
4341 * Kernel#binding, and are made available to the callback of
4342 * Kernel#set_trace_func and instances of TracePoint.
4344 * These binding objects can be passed as the second argument of the
4345 * Kernel#eval method, establishing an environment for the
4346 * evaluation.
4348 * class Demo
4349 * def initialize(n)
4350 * @secret = n
4351 * end
4352 * def get_binding
4353 * binding
4354 * end
4355 * end
4357 * k1 = Demo.new(99)
4358 * b1 = k1.get_binding
4359 * k2 = Demo.new(-3)
4360 * b2 = k2.get_binding
4362 * eval("@secret", b1) #=> 99
4363 * eval("@secret", b2) #=> -3
4364 * eval("@secret") #=> nil
4366 * Binding objects have no class-specific methods.
4370 void
4371 Init_Binding(void)
4373 rb_cBinding = rb_define_class("Binding", rb_cObject);
4374 rb_undef_alloc_func(rb_cBinding);
4375 rb_undef_method(CLASS_OF(rb_cBinding), "new");
4376 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
4377 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
4378 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
4379 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
4380 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
4381 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
4382 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
4383 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
4384 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
4385 rb_define_global_function("binding", rb_f_binding, 0);