[ruby/win32ole] Undefine allocator of WIN32OLE_VARIABLE to get rid of warning
[ruby-80x24.org.git] / proc.c
blobd075b7382e614a265bbebbb0a12f14080832906c
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 * */
45 VALUE rb_cUnboundMethod;
46 VALUE rb_cMethod;
47 VALUE rb_cBinding;
48 VALUE rb_cProc;
50 static rb_block_call_func bmcall;
51 static int method_arity(VALUE);
52 static int method_min_max_arity(VALUE, int *max);
53 static VALUE proc_binding(VALUE self);
55 #define attached id__attached__
57 /* Proc */
59 #define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
61 /* :FIXME: The way procs are cloned has been historically different from the
62 * way everything else are. @shyouhei is not sure for the intention though.
64 #undef CLONESETUP
65 static inline void
66 CLONESETUP(VALUE clone, VALUE obj)
68 RBIMPL_ASSERT_OR_ASSUME(! RB_SPECIAL_CONST_P(obj));
69 RBIMPL_ASSERT_OR_ASSUME(! RB_SPECIAL_CONST_P(clone));
71 const VALUE flags = RUBY_FL_PROMOTED0 | RUBY_FL_PROMOTED1 | RUBY_FL_FINALIZE;
72 rb_obj_setup(clone, rb_singleton_class_clone(obj),
73 RB_FL_TEST_RAW(obj, ~flags));
74 rb_singleton_class_attached(RBASIC_CLASS(clone), clone);
75 if (RB_FL_TEST(obj, RUBY_FL_EXIVAR)) rb_copy_generic_ivar(clone, obj);
78 static void
79 block_mark(const struct rb_block *block)
81 switch (vm_block_type(block)) {
82 case block_type_iseq:
83 case block_type_ifunc:
85 const struct rb_captured_block *captured = &block->as.captured;
86 RUBY_MARK_MOVABLE_UNLESS_NULL(captured->self);
87 RUBY_MARK_MOVABLE_UNLESS_NULL((VALUE)captured->code.val);
88 if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) {
89 rb_gc_mark(VM_ENV_ENVVAL(captured->ep));
92 break;
93 case block_type_symbol:
94 RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.symbol);
95 break;
96 case block_type_proc:
97 RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.proc);
98 break;
102 static void
103 block_compact(struct rb_block *block)
105 switch (block->type) {
106 case block_type_iseq:
107 case block_type_ifunc:
109 struct rb_captured_block *captured = &block->as.captured;
110 captured->self = rb_gc_location(captured->self);
111 captured->code.val = rb_gc_location(captured->code.val);
113 break;
114 case block_type_symbol:
115 block->as.symbol = rb_gc_location(block->as.symbol);
116 break;
117 case block_type_proc:
118 block->as.proc = rb_gc_location(block->as.proc);
119 break;
123 static void
124 proc_compact(void *ptr)
126 rb_proc_t *proc = ptr;
127 block_compact((struct rb_block *)&proc->block);
130 static void
131 proc_mark(void *ptr)
133 rb_proc_t *proc = ptr;
134 block_mark(&proc->block);
135 RUBY_MARK_LEAVE("proc");
138 typedef struct {
139 rb_proc_t basic;
140 VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
141 } cfunc_proc_t;
143 static size_t
144 proc_memsize(const void *ptr)
146 const rb_proc_t *proc = ptr;
147 if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1)
148 return sizeof(cfunc_proc_t);
149 return sizeof(rb_proc_t);
152 static const rb_data_type_t proc_data_type = {
153 "proc",
155 proc_mark,
156 RUBY_TYPED_DEFAULT_FREE,
157 proc_memsize,
158 proc_compact,
160 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
163 VALUE
164 rb_proc_alloc(VALUE klass)
166 rb_proc_t *proc;
167 return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
170 VALUE
171 rb_obj_is_proc(VALUE proc)
173 return RBOOL(rb_typeddata_is_kind_of(proc, &proc_data_type));
176 /* :nodoc: */
177 static VALUE
178 proc_clone(VALUE self)
180 VALUE procval = rb_proc_dup(self);
181 CLONESETUP(procval, self);
182 return procval;
186 * call-seq:
187 * prc.lambda? -> true or false
189 * Returns +true+ if a Proc object is lambda.
190 * +false+ if non-lambda.
192 * The lambda-ness affects argument handling and the behavior of +return+ and +break+.
194 * A Proc object generated by +proc+ ignores extra arguments.
196 * proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
198 * It provides +nil+ for missing arguments.
200 * proc {|a,b| [a,b] }.call(1) #=> [1,nil]
202 * It expands a single array argument.
204 * proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
206 * A Proc object generated by +lambda+ doesn't have such tricks.
208 * lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError
209 * lambda {|a,b| [a,b] }.call(1) #=> ArgumentError
210 * lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
212 * Proc#lambda? is a predicate for the tricks.
213 * It returns +true+ if no tricks apply.
215 * lambda {}.lambda? #=> true
216 * proc {}.lambda? #=> false
218 * Proc.new is the same as +proc+.
220 * Proc.new {}.lambda? #=> false
222 * +lambda+, +proc+ and Proc.new preserve the tricks of
223 * a Proc object given by <code>&</code> argument.
225 * lambda(&lambda {}).lambda? #=> true
226 * proc(&lambda {}).lambda? #=> true
227 * Proc.new(&lambda {}).lambda? #=> true
229 * lambda(&proc {}).lambda? #=> false
230 * proc(&proc {}).lambda? #=> false
231 * Proc.new(&proc {}).lambda? #=> false
233 * A Proc object generated by <code>&</code> argument has the tricks
235 * def n(&b) b.lambda? end
236 * n {} #=> false
238 * The <code>&</code> argument preserves the tricks if a Proc object
239 * is given by <code>&</code> argument.
241 * n(&lambda {}) #=> true
242 * n(&proc {}) #=> false
243 * n(&Proc.new {}) #=> false
245 * A Proc object converted from a method has no tricks.
247 * def m() end
248 * method(:m).to_proc.lambda? #=> true
250 * n(&method(:m)) #=> true
251 * n(&method(:m).to_proc) #=> true
253 * +define_method+ is treated the same as method definition.
254 * The defined method has no tricks.
256 * class C
257 * define_method(:d) {}
258 * end
259 * C.new.d(1,2) #=> ArgumentError
260 * C.new.method(:d).to_proc.lambda? #=> true
262 * +define_method+ always defines a method without the tricks,
263 * even if a non-lambda Proc object is given.
264 * This is the only exception for which the tricks are not preserved.
266 * class C
267 * define_method(:e, &proc {})
268 * end
269 * C.new.e(1,2) #=> ArgumentError
270 * C.new.method(:e).to_proc.lambda? #=> true
272 * This exception ensures that methods never have tricks
273 * and makes it easy to have wrappers to define methods that behave as usual.
275 * class C
276 * def self.def2(name, &body)
277 * define_method(name, &body)
278 * end
280 * def2(:f) {}
281 * end
282 * C.new.f(1,2) #=> ArgumentError
284 * The wrapper <i>def2</i> defines a method which has no tricks.
288 VALUE
289 rb_proc_lambda_p(VALUE procval)
291 rb_proc_t *proc;
292 GetProcPtr(procval, proc);
294 return RBOOL(proc->is_lambda);
297 /* Binding */
299 static void
300 binding_free(void *ptr)
302 RUBY_FREE_ENTER("binding");
303 ruby_xfree(ptr);
304 RUBY_FREE_LEAVE("binding");
307 static void
308 binding_mark(void *ptr)
310 rb_binding_t *bind = ptr;
312 RUBY_MARK_ENTER("binding");
313 block_mark(&bind->block);
314 rb_gc_mark_movable(bind->pathobj);
315 RUBY_MARK_LEAVE("binding");
318 static void
319 binding_compact(void *ptr)
321 rb_binding_t *bind = ptr;
323 block_compact((struct rb_block *)&bind->block);
324 UPDATE_REFERENCE(bind->pathobj);
327 static size_t
328 binding_memsize(const void *ptr)
330 return sizeof(rb_binding_t);
333 const rb_data_type_t ruby_binding_data_type = {
334 "binding",
336 binding_mark,
337 binding_free,
338 binding_memsize,
339 binding_compact,
341 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
344 VALUE
345 rb_binding_alloc(VALUE klass)
347 VALUE obj;
348 rb_binding_t *bind;
349 obj = TypedData_Make_Struct(klass, rb_binding_t, &ruby_binding_data_type, bind);
350 #if YJIT_STATS
351 rb_yjit_collect_binding_alloc();
352 #endif
353 return obj;
357 /* :nodoc: */
358 static VALUE
359 binding_dup(VALUE self)
361 VALUE bindval = rb_binding_alloc(rb_cBinding);
362 rb_binding_t *src, *dst;
363 GetBindingPtr(self, src);
364 GetBindingPtr(bindval, dst);
365 rb_vm_block_copy(bindval, &dst->block, &src->block);
366 RB_OBJ_WRITE(bindval, &dst->pathobj, src->pathobj);
367 dst->first_lineno = src->first_lineno;
368 return bindval;
371 /* :nodoc: */
372 static VALUE
373 binding_clone(VALUE self)
375 VALUE bindval = binding_dup(self);
376 CLONESETUP(bindval, self);
377 return bindval;
380 VALUE
381 rb_binding_new(void)
383 rb_execution_context_t *ec = GET_EC();
384 return rb_vm_make_binding(ec, ec->cfp);
388 * call-seq:
389 * binding -> a_binding
391 * Returns a +Binding+ object, describing the variable and
392 * method bindings at the point of call. This object can be used when
393 * calling +eval+ to execute the evaluated command in this
394 * environment. See also the description of class +Binding+.
396 * def get_binding(param)
397 * binding
398 * end
399 * b = get_binding("hello")
400 * eval("param", b) #=> "hello"
403 static VALUE
404 rb_f_binding(VALUE self)
406 return rb_binding_new();
410 * call-seq:
411 * binding.eval(string [, filename [,lineno]]) -> obj
413 * Evaluates the Ruby expression(s) in <em>string</em>, in the
414 * <em>binding</em>'s context. If the optional <em>filename</em> and
415 * <em>lineno</em> parameters are present, they will be used when
416 * reporting syntax errors.
418 * def get_binding(param)
419 * binding
420 * end
421 * b = get_binding("hello")
422 * b.eval("param") #=> "hello"
425 static VALUE
426 bind_eval(int argc, VALUE *argv, VALUE bindval)
428 VALUE args[4];
430 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
431 args[1] = bindval;
432 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
435 static const VALUE *
436 get_local_variable_ptr(const rb_env_t **envp, ID lid)
438 const rb_env_t *env = *envp;
439 do {
440 if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) {
441 if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) {
442 return NULL;
445 const rb_iseq_t *iseq = env->iseq;
446 unsigned int i;
448 VM_ASSERT(rb_obj_is_iseq((VALUE)iseq));
450 for (i=0; i<iseq->body->local_table_size; i++) {
451 if (iseq->body->local_table[i] == lid) {
452 if (iseq->body->local_iseq == iseq &&
453 iseq->body->param.flags.has_block &&
454 (unsigned int)iseq->body->param.block_start == i) {
455 const VALUE *ep = env->ep;
456 if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) {
457 RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep)));
458 VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM);
462 *envp = env;
463 return &env->env[i];
467 else {
468 *envp = NULL;
469 return NULL;
471 } while ((env = rb_vm_env_prev_env(env)) != NULL);
473 *envp = NULL;
474 return NULL;
478 * check local variable name.
479 * returns ID if it's an already interned symbol, or 0 with setting
480 * local name in String to *namep.
482 static ID
483 check_local_id(VALUE bindval, volatile VALUE *pname)
485 ID lid = rb_check_id(pname);
486 VALUE name = *pname;
488 if (lid) {
489 if (!rb_is_local_id(lid)) {
490 rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
491 bindval, ID2SYM(lid));
494 else {
495 if (!rb_is_local_name(name)) {
496 rb_name_err_raise("wrong local variable name `%1$s' for %2$s",
497 bindval, name);
499 return 0;
501 return lid;
505 * call-seq:
506 * binding.local_variables -> Array
508 * Returns the names of the binding's local variables as symbols.
510 * def foo
511 * a = 1
512 * 2.times do |n|
513 * binding.local_variables #=> [:a, :n]
514 * end
515 * end
517 * This method is the short version of the following code:
519 * binding.eval("local_variables")
522 static VALUE
523 bind_local_variables(VALUE bindval)
525 const rb_binding_t *bind;
526 const rb_env_t *env;
528 GetBindingPtr(bindval, bind);
529 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
530 return rb_vm_env_local_variables(env);
534 * call-seq:
535 * binding.local_variable_get(symbol) -> obj
537 * Returns the value of the local variable +symbol+.
539 * def foo
540 * a = 1
541 * binding.local_variable_get(:a) #=> 1
542 * binding.local_variable_get(:b) #=> NameError
543 * end
545 * This method is the short version of the following code:
547 * binding.eval("#{symbol}")
550 static VALUE
551 bind_local_variable_get(VALUE bindval, VALUE sym)
553 ID lid = check_local_id(bindval, &sym);
554 const rb_binding_t *bind;
555 const VALUE *ptr;
556 const rb_env_t *env;
558 if (!lid) goto undefined;
560 GetBindingPtr(bindval, bind);
562 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
563 if ((ptr = get_local_variable_ptr(&env, lid)) != NULL) {
564 return *ptr;
567 sym = ID2SYM(lid);
568 undefined:
569 rb_name_err_raise("local variable `%1$s' is not defined for %2$s",
570 bindval, sym);
571 UNREACHABLE_RETURN(Qundef);
575 * call-seq:
576 * binding.local_variable_set(symbol, obj) -> obj
578 * Set local variable named +symbol+ as +obj+.
580 * def foo
581 * a = 1
582 * bind = binding
583 * bind.local_variable_set(:a, 2) # set existing local variable `a'
584 * bind.local_variable_set(:b, 3) # create new local variable `b'
585 * # `b' exists only in binding
587 * p bind.local_variable_get(:a) #=> 2
588 * p bind.local_variable_get(:b) #=> 3
589 * p a #=> 2
590 * p b #=> NameError
591 * end
593 * This method behaves similarly to the following code:
595 * binding.eval("#{symbol} = #{obj}")
597 * if +obj+ can be dumped in Ruby code.
599 static VALUE
600 bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
602 ID lid = check_local_id(bindval, &sym);
603 rb_binding_t *bind;
604 const VALUE *ptr;
605 const rb_env_t *env;
607 if (!lid) lid = rb_intern_str(sym);
609 GetBindingPtr(bindval, bind);
610 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
611 if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) {
612 /* not found. create new env */
613 ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
614 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
617 #if YJIT_STATS
618 rb_yjit_collect_binding_set();
619 #endif
621 RB_OBJ_WRITE(env, ptr, val);
623 return val;
627 * call-seq:
628 * binding.local_variable_defined?(symbol) -> obj
630 * Returns +true+ if a local variable +symbol+ exists.
632 * def foo
633 * a = 1
634 * binding.local_variable_defined?(:a) #=> true
635 * binding.local_variable_defined?(:b) #=> false
636 * end
638 * This method is the short version of the following code:
640 * binding.eval("defined?(#{symbol}) == 'local-variable'")
643 static VALUE
644 bind_local_variable_defined_p(VALUE bindval, VALUE sym)
646 ID lid = check_local_id(bindval, &sym);
647 const rb_binding_t *bind;
648 const rb_env_t *env;
650 if (!lid) return Qfalse;
652 GetBindingPtr(bindval, bind);
653 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
654 return RBOOL(get_local_variable_ptr(&env, lid));
658 * call-seq:
659 * binding.receiver -> object
661 * Returns the bound receiver of the binding object.
663 static VALUE
664 bind_receiver(VALUE bindval)
666 const rb_binding_t *bind;
667 GetBindingPtr(bindval, bind);
668 return vm_block_self(&bind->block);
672 * call-seq:
673 * binding.source_location -> [String, Integer]
675 * Returns the Ruby source filename and line number of the binding object.
677 static VALUE
678 bind_location(VALUE bindval)
680 VALUE loc[2];
681 const rb_binding_t *bind;
682 GetBindingPtr(bindval, bind);
683 loc[0] = pathobj_path(bind->pathobj);
684 loc[1] = INT2FIX(bind->first_lineno);
686 return rb_ary_new4(2, loc);
689 static VALUE
690 cfunc_proc_new(VALUE klass, VALUE ifunc)
692 rb_proc_t *proc;
693 cfunc_proc_t *sproc;
694 VALUE procval = TypedData_Make_Struct(klass, cfunc_proc_t, &proc_data_type, sproc);
695 VALUE *ep;
697 proc = &sproc->basic;
698 vm_block_type_set(&proc->block, block_type_ifunc);
700 *(VALUE **)&proc->block.as.captured.ep = ep = sproc->env + VM_ENV_DATA_SIZE-1;
701 ep[VM_ENV_DATA_INDEX_FLAGS] = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL | VM_ENV_FLAG_ESCAPED;
702 ep[VM_ENV_DATA_INDEX_ME_CREF] = Qfalse;
703 ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
704 ep[VM_ENV_DATA_INDEX_ENV] = Qundef; /* envval */
706 /* self? */
707 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.ifunc, ifunc);
708 proc->is_lambda = TRUE;
709 return procval;
712 static VALUE
713 sym_proc_new(VALUE klass, VALUE sym)
715 VALUE procval = rb_proc_alloc(klass);
716 rb_proc_t *proc;
717 GetProcPtr(procval, proc);
719 vm_block_type_set(&proc->block, block_type_symbol);
720 proc->is_lambda = TRUE;
721 RB_OBJ_WRITE(procval, &proc->block.as.symbol, sym);
722 return procval;
725 struct vm_ifunc *
726 rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc)
728 union {
729 struct vm_ifunc_argc argc;
730 VALUE packed;
731 } arity;
733 if (min_argc < UNLIMITED_ARGUMENTS ||
734 #if SIZEOF_INT * 2 > SIZEOF_VALUE
735 min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
736 #endif
737 0) {
738 rb_raise(rb_eRangeError, "minimum argument number out of range: %d",
739 min_argc);
741 if (max_argc < UNLIMITED_ARGUMENTS ||
742 #if SIZEOF_INT * 2 > SIZEOF_VALUE
743 max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
744 #endif
745 0) {
746 rb_raise(rb_eRangeError, "maximum argument number out of range: %d",
747 max_argc);
749 arity.argc.min = min_argc;
750 arity.argc.max = max_argc;
751 VALUE ret = rb_imemo_new(imemo_ifunc, (VALUE)func, (VALUE)data, arity.packed, 0);
752 return (struct vm_ifunc *)ret;
755 MJIT_FUNC_EXPORTED VALUE
756 rb_func_proc_new(rb_block_call_func_t func, VALUE val)
758 struct vm_ifunc *ifunc = rb_vm_ifunc_proc_new(func, (void *)val);
759 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
762 MJIT_FUNC_EXPORTED VALUE
763 rb_func_lambda_new(rb_block_call_func_t func, VALUE val, int min_argc, int max_argc)
765 struct vm_ifunc *ifunc = rb_vm_ifunc_new(func, (void *)val, min_argc, max_argc);
766 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
769 static const char proc_without_block[] = "tried to create Proc object without a block";
771 static VALUE
772 proc_new(VALUE klass, int8_t is_lambda, int8_t kernel)
774 VALUE procval;
775 const rb_execution_context_t *ec = GET_EC();
776 rb_control_frame_t *cfp = ec->cfp;
777 VALUE block_handler;
779 if ((block_handler = rb_vm_frame_block_handler(cfp)) == VM_BLOCK_HANDLER_NONE) {
780 rb_raise(rb_eArgError, proc_without_block);
783 /* block is in cf */
784 switch (vm_block_handler_type(block_handler)) {
785 case block_handler_type_proc:
786 procval = VM_BH_TO_PROC(block_handler);
788 if (RBASIC_CLASS(procval) == klass) {
789 return procval;
791 else {
792 VALUE newprocval = rb_proc_dup(procval);
793 RBASIC_SET_CLASS(newprocval, klass);
794 return newprocval;
796 break;
798 case block_handler_type_symbol:
799 return (klass != rb_cProc) ?
800 sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) :
801 rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
802 break;
804 case block_handler_type_ifunc:
805 return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda);
806 case block_handler_type_iseq:
808 const struct rb_captured_block *captured = VM_BH_TO_CAPT_BLOCK(block_handler);
809 rb_control_frame_t *last_ruby_cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
810 if (is_lambda && last_ruby_cfp && vm_cfp_forwarded_bh_p(last_ruby_cfp, block_handler)) {
811 is_lambda = false;
813 return rb_vm_make_proc_lambda(ec, captured, klass, is_lambda);
816 VM_UNREACHABLE(proc_new);
817 return Qnil;
821 * call-seq:
822 * Proc.new {|...| block } -> a_proc
824 * Creates a new Proc object, bound to the current context.
826 * proc = Proc.new { "hello" }
827 * proc.call #=> "hello"
829 * Raises ArgumentError if called without a block.
831 * Proc.new #=> ArgumentError
834 static VALUE
835 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
837 VALUE block = proc_new(klass, FALSE, FALSE);
839 rb_obj_call_init_kw(block, argc, argv, RB_PASS_CALLED_KEYWORDS);
840 return block;
843 VALUE
844 rb_block_proc(void)
846 return proc_new(rb_cProc, FALSE, FALSE);
850 * call-seq:
851 * proc { |...| block } -> a_proc
853 * Equivalent to Proc.new.
856 static VALUE
857 f_proc(VALUE _)
859 return proc_new(rb_cProc, FALSE, TRUE);
862 VALUE
863 rb_block_lambda(void)
865 return proc_new(rb_cProc, TRUE, FALSE);
868 static void
869 f_lambda_warn(void)
871 rb_control_frame_t *cfp = GET_EC()->cfp;
872 VALUE block_handler = rb_vm_frame_block_handler(cfp);
874 if (block_handler != VM_BLOCK_HANDLER_NONE) {
875 switch (vm_block_handler_type(block_handler)) {
876 case block_handler_type_iseq:
877 if (RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)->ep == VM_BH_TO_ISEQ_BLOCK(block_handler)->ep) {
878 return;
880 break;
881 case block_handler_type_symbol:
882 return;
883 case block_handler_type_proc:
884 if (rb_proc_lambda_p(VM_BH_TO_PROC(block_handler))) {
885 return;
887 break;
888 case block_handler_type_ifunc:
889 break;
893 rb_warn_deprecated("lambda without a literal block", "the proc without lambda");
897 * call-seq:
898 * lambda { |...| block } -> a_proc
900 * Equivalent to Proc.new, except the resulting Proc objects check the
901 * number of parameters passed when called.
904 static VALUE
905 f_lambda(VALUE _)
907 f_lambda_warn();
908 return rb_block_lambda();
911 /* Document-method: Proc#===
913 * call-seq:
914 * proc === obj -> result_of_proc
916 * Invokes the block with +obj+ as the proc's parameter like Proc#call.
917 * This allows a proc object to be the target of a +when+ clause
918 * in a case statement.
921 /* CHECKME: are the argument checking semantics correct? */
924 * Document-method: Proc#[]
925 * Document-method: Proc#call
926 * Document-method: Proc#yield
928 * call-seq:
929 * prc.call(params,...) -> obj
930 * prc[params,...] -> obj
931 * prc.(params,...) -> obj
932 * prc.yield(params,...) -> obj
934 * Invokes the block, setting the block's parameters to the values in
935 * <i>params</i> using something close to method calling semantics.
936 * Returns the value of the last expression evaluated in the block.
938 * a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
939 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
940 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
941 * a_proc.(9, 1, 2, 3) #=> [9, 18, 27]
942 * a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
944 * Note that <code>prc.()</code> invokes <code>prc.call()</code> with
945 * the parameters given. It's syntactic sugar to hide "call".
947 * For procs created using #lambda or <code>->()</code> an error is
948 * generated if the wrong number of parameters are passed to the
949 * proc. For procs created using Proc.new or Kernel.proc, extra
950 * parameters are silently discarded and missing parameters are set
951 * to +nil+.
953 * a_proc = proc {|a,b| [a,b] }
954 * a_proc.call(1) #=> [1, nil]
956 * a_proc = lambda {|a,b| [a,b] }
957 * a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
959 * See also Proc#lambda?.
961 #if 0
962 static VALUE
963 proc_call(int argc, VALUE *argv, VALUE procval)
965 /* removed */
967 #endif
969 #if SIZEOF_LONG > SIZEOF_INT
970 static inline int
971 check_argc(long argc)
973 if (argc > INT_MAX || argc < 0) {
974 rb_raise(rb_eArgError, "too many arguments (%lu)",
975 (unsigned long)argc);
977 return (int)argc;
979 #else
980 #define check_argc(argc) (argc)
981 #endif
983 VALUE
984 rb_proc_call_kw(VALUE self, VALUE args, int kw_splat)
986 VALUE vret;
987 rb_proc_t *proc;
988 int argc = check_argc(RARRAY_LEN(args));
989 const VALUE *argv = RARRAY_CONST_PTR(args);
990 GetProcPtr(self, proc);
991 vret = rb_vm_invoke_proc(GET_EC(), proc, argc, argv,
992 kw_splat, VM_BLOCK_HANDLER_NONE);
993 RB_GC_GUARD(self);
994 RB_GC_GUARD(args);
995 return vret;
998 VALUE
999 rb_proc_call(VALUE self, VALUE args)
1001 return rb_proc_call_kw(self, args, RB_NO_KEYWORDS);
1004 static VALUE
1005 proc_to_block_handler(VALUE procval)
1007 return NIL_P(procval) ? VM_BLOCK_HANDLER_NONE : procval;
1010 VALUE
1011 rb_proc_call_with_block_kw(VALUE self, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
1013 rb_execution_context_t *ec = GET_EC();
1014 VALUE vret;
1015 rb_proc_t *proc;
1016 GetProcPtr(self, proc);
1017 vret = rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, proc_to_block_handler(passed_procval));
1018 RB_GC_GUARD(self);
1019 return vret;
1022 VALUE
1023 rb_proc_call_with_block(VALUE self, int argc, const VALUE *argv, VALUE passed_procval)
1025 return rb_proc_call_with_block_kw(self, argc, argv, passed_procval, RB_NO_KEYWORDS);
1030 * call-seq:
1031 * prc.arity -> integer
1033 * Returns the number of mandatory arguments. If the block
1034 * is declared to take no arguments, returns 0. If the block is known
1035 * to take exactly n arguments, returns n.
1036 * If the block has optional arguments, returns -n-1, where n is the
1037 * number of mandatory arguments, with the exception for blocks that
1038 * are not lambdas and have only a finite number of optional arguments;
1039 * in this latter case, returns n.
1040 * Keyword arguments will be considered as a single additional argument,
1041 * that argument being mandatory if any keyword argument is mandatory.
1042 * A #proc with no argument declarations is the same as a block
1043 * declaring <code>||</code> as its arguments.
1045 * proc {}.arity #=> 0
1046 * proc { || }.arity #=> 0
1047 * proc { |a| }.arity #=> 1
1048 * proc { |a, b| }.arity #=> 2
1049 * proc { |a, b, c| }.arity #=> 3
1050 * proc { |*a| }.arity #=> -1
1051 * proc { |a, *b| }.arity #=> -2
1052 * proc { |a, *b, c| }.arity #=> -3
1053 * proc { |x:, y:, z:0| }.arity #=> 1
1054 * proc { |*a, x:, y:0| }.arity #=> -2
1056 * proc { |a=0| }.arity #=> 0
1057 * lambda { |a=0| }.arity #=> -1
1058 * proc { |a=0, b| }.arity #=> 1
1059 * lambda { |a=0, b| }.arity #=> -2
1060 * proc { |a=0, b=0| }.arity #=> 0
1061 * lambda { |a=0, b=0| }.arity #=> -1
1062 * proc { |a, b=0| }.arity #=> 1
1063 * lambda { |a, b=0| }.arity #=> -2
1064 * proc { |(a, b), c=0| }.arity #=> 1
1065 * lambda { |(a, b), c=0| }.arity #=> -2
1066 * proc { |a, x:0, y:0| }.arity #=> 1
1067 * lambda { |a, x:0, y:0| }.arity #=> -2
1070 static VALUE
1071 proc_arity(VALUE self)
1073 int arity = rb_proc_arity(self);
1074 return INT2FIX(arity);
1077 static inline int
1078 rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
1080 *max = iseq->body->param.flags.has_rest == FALSE ?
1081 iseq->body->param.lead_num + iseq->body->param.opt_num + iseq->body->param.post_num +
1082 (iseq->body->param.flags.has_kw == TRUE || iseq->body->param.flags.has_kwrest == TRUE)
1083 : UNLIMITED_ARGUMENTS;
1084 return iseq->body->param.lead_num + iseq->body->param.post_num + (iseq->body->param.flags.has_kw && iseq->body->param.keyword->required_num > 0);
1087 static int
1088 rb_vm_block_min_max_arity(const struct rb_block *block, int *max)
1090 again:
1091 switch (vm_block_type(block)) {
1092 case block_type_iseq:
1093 return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max);
1094 case block_type_proc:
1095 block = vm_proc_block(block->as.proc);
1096 goto again;
1097 case block_type_ifunc:
1099 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1100 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1101 /* e.g. method(:foo).to_proc.arity */
1102 return method_min_max_arity((VALUE)ifunc->data, max);
1104 *max = ifunc->argc.max;
1105 return ifunc->argc.min;
1107 case block_type_symbol:
1108 *max = UNLIMITED_ARGUMENTS;
1109 return 1;
1111 *max = UNLIMITED_ARGUMENTS;
1112 return 0;
1116 * Returns the number of required parameters and stores the maximum
1117 * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
1118 * For non-lambda procs, the maximum is the number of non-ignored
1119 * parameters even though there is no actual limit to the number of parameters
1121 static int
1122 rb_proc_min_max_arity(VALUE self, int *max)
1124 rb_proc_t *proc;
1125 GetProcPtr(self, proc);
1126 return rb_vm_block_min_max_arity(&proc->block, max);
1130 rb_proc_arity(VALUE self)
1132 rb_proc_t *proc;
1133 int max, min;
1134 GetProcPtr(self, proc);
1135 min = rb_vm_block_min_max_arity(&proc->block, &max);
1136 return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1139 static void
1140 block_setup(struct rb_block *block, VALUE block_handler)
1142 switch (vm_block_handler_type(block_handler)) {
1143 case block_handler_type_iseq:
1144 block->type = block_type_iseq;
1145 block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler);
1146 break;
1147 case block_handler_type_ifunc:
1148 block->type = block_type_ifunc;
1149 block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler);
1150 break;
1151 case block_handler_type_symbol:
1152 block->type = block_type_symbol;
1153 block->as.symbol = VM_BH_TO_SYMBOL(block_handler);
1154 break;
1155 case block_handler_type_proc:
1156 block->type = block_type_proc;
1157 block->as.proc = VM_BH_TO_PROC(block_handler);
1162 rb_block_pair_yield_optimizable(void)
1164 int min, max;
1165 const rb_execution_context_t *ec = GET_EC();
1166 rb_control_frame_t *cfp = ec->cfp;
1167 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1168 struct rb_block block;
1170 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1171 rb_raise(rb_eArgError, "no block given");
1174 block_setup(&block, block_handler);
1175 min = rb_vm_block_min_max_arity(&block, &max);
1177 switch (vm_block_type(&block)) {
1178 case block_handler_type_symbol:
1179 return 0;
1181 case block_handler_type_proc:
1183 VALUE procval = block_handler;
1184 rb_proc_t *proc;
1185 GetProcPtr(procval, proc);
1186 if (proc->is_lambda) return 0;
1187 if (min != max) return 0;
1188 return min > 1;
1191 default:
1192 return min > 1;
1197 rb_block_arity(void)
1199 int min, max;
1200 const rb_execution_context_t *ec = GET_EC();
1201 rb_control_frame_t *cfp = ec->cfp;
1202 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1203 struct rb_block block;
1205 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1206 rb_raise(rb_eArgError, "no block given");
1209 block_setup(&block, block_handler);
1210 min = rb_vm_block_min_max_arity(&block, &max);
1212 switch (vm_block_type(&block)) {
1213 case block_handler_type_symbol:
1214 return -1;
1216 case block_handler_type_proc:
1218 VALUE procval = block_handler;
1219 rb_proc_t *proc;
1220 GetProcPtr(procval, proc);
1221 return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1224 default:
1225 return max != UNLIMITED_ARGUMENTS ? min : -min-1;
1230 rb_block_min_max_arity(int *max)
1232 const rb_execution_context_t *ec = GET_EC();
1233 rb_control_frame_t *cfp = ec->cfp;
1234 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1235 struct rb_block block;
1237 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1238 rb_raise(rb_eArgError, "no block given");
1241 block_setup(&block, block_handler);
1242 return rb_vm_block_min_max_arity(&block, max);
1245 const rb_iseq_t *
1246 rb_proc_get_iseq(VALUE self, int *is_proc)
1248 const rb_proc_t *proc;
1249 const struct rb_block *block;
1251 GetProcPtr(self, proc);
1252 block = &proc->block;
1253 if (is_proc) *is_proc = !proc->is_lambda;
1255 switch (vm_block_type(block)) {
1256 case block_type_iseq:
1257 return rb_iseq_check(block->as.captured.code.iseq);
1258 case block_type_proc:
1259 return rb_proc_get_iseq(block->as.proc, is_proc);
1260 case block_type_ifunc:
1262 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1263 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1264 /* method(:foo).to_proc */
1265 if (is_proc) *is_proc = 0;
1266 return rb_method_iseq((VALUE)ifunc->data);
1268 else {
1269 return NULL;
1272 case block_type_symbol:
1273 return NULL;
1276 VM_UNREACHABLE(rb_proc_get_iseq);
1277 return NULL;
1280 /* call-seq:
1281 * prc == other -> true or false
1282 * prc.eql?(other) -> true or false
1284 * Two procs are the same if, and only if, they were created from the same code block.
1286 * def return_block(&block)
1287 * block
1288 * end
1290 * def pass_block_twice(&block)
1291 * [return_block(&block), return_block(&block)]
1292 * end
1294 * block1, block2 = pass_block_twice { puts 'test' }
1295 * # Blocks might be instantiated into Proc's lazily, so they may, or may not,
1296 * # be the same object.
1297 * # But they are produced from the same code block, so they are equal
1298 * block1 == block2
1299 * #=> true
1301 * # Another Proc will never be equal, even if the code is the "same"
1302 * block1 == proc { puts 'test' }
1303 * #=> false
1306 static VALUE
1307 proc_eq(VALUE self, VALUE other)
1309 const rb_proc_t *self_proc, *other_proc;
1310 const struct rb_block *self_block, *other_block;
1312 if (rb_obj_class(self) != rb_obj_class(other)) {
1313 return Qfalse;
1316 GetProcPtr(self, self_proc);
1317 GetProcPtr(other, other_proc);
1319 if (self_proc->is_from_method != other_proc->is_from_method ||
1320 self_proc->is_lambda != other_proc->is_lambda) {
1321 return Qfalse;
1324 self_block = &self_proc->block;
1325 other_block = &other_proc->block;
1327 if (vm_block_type(self_block) != vm_block_type(other_block)) {
1328 return Qfalse;
1331 switch (vm_block_type(self_block)) {
1332 case block_type_iseq:
1333 if (self_block->as.captured.ep != \
1334 other_block->as.captured.ep ||
1335 self_block->as.captured.code.iseq != \
1336 other_block->as.captured.code.iseq) {
1337 return Qfalse;
1339 break;
1340 case block_type_ifunc:
1341 if (self_block->as.captured.ep != \
1342 other_block->as.captured.ep ||
1343 self_block->as.captured.code.ifunc != \
1344 other_block->as.captured.code.ifunc) {
1345 return Qfalse;
1347 break;
1348 case block_type_proc:
1349 if (self_block->as.proc != other_block->as.proc) {
1350 return Qfalse;
1352 break;
1353 case block_type_symbol:
1354 if (self_block->as.symbol != other_block->as.symbol) {
1355 return Qfalse;
1357 break;
1360 return Qtrue;
1363 static VALUE
1364 iseq_location(const rb_iseq_t *iseq)
1366 VALUE loc[2];
1368 if (!iseq) return Qnil;
1369 rb_iseq_check(iseq);
1370 loc[0] = rb_iseq_path(iseq);
1371 loc[1] = iseq->body->location.first_lineno;
1373 return rb_ary_new4(2, loc);
1376 MJIT_FUNC_EXPORTED VALUE
1377 rb_iseq_location(const rb_iseq_t *iseq)
1379 return iseq_location(iseq);
1383 * call-seq:
1384 * prc.source_location -> [String, Integer]
1386 * Returns the Ruby source filename and line number containing this proc
1387 * or +nil+ if this proc was not defined in Ruby (i.e. native).
1390 VALUE
1391 rb_proc_location(VALUE self)
1393 return iseq_location(rb_proc_get_iseq(self, 0));
1396 VALUE
1397 rb_unnamed_parameters(int arity)
1399 VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
1400 int n = (arity < 0) ? ~arity : arity;
1401 ID req, rest;
1402 CONST_ID(req, "req");
1403 a = rb_ary_new3(1, ID2SYM(req));
1404 OBJ_FREEZE(a);
1405 for (; n; --n) {
1406 rb_ary_push(param, a);
1408 if (arity < 0) {
1409 CONST_ID(rest, "rest");
1410 rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
1412 return param;
1416 * call-seq:
1417 * prc.parameters -> array
1419 * Returns the parameter information of this proc.
1421 * prc = lambda{|x, y=42, *other|}
1422 * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1425 static VALUE
1426 rb_proc_parameters(VALUE self)
1428 int is_proc;
1429 const rb_iseq_t *iseq = rb_proc_get_iseq(self, &is_proc);
1430 if (!iseq) {
1431 return rb_unnamed_parameters(rb_proc_arity(self));
1433 return rb_iseq_parameters(iseq, is_proc);
1436 st_index_t
1437 rb_hash_proc(st_index_t hash, VALUE prc)
1439 rb_proc_t *proc;
1440 GetProcPtr(prc, proc);
1441 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.code.val);
1442 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.self);
1443 return rb_hash_uint(hash, (st_index_t)proc->block.as.captured.ep);
1446 MJIT_FUNC_EXPORTED VALUE
1447 rb_sym_to_proc(VALUE sym)
1449 static VALUE sym_proc_cache = Qfalse;
1450 enum {SYM_PROC_CACHE_SIZE = 67};
1451 VALUE proc;
1452 long index;
1453 ID id;
1455 if (!sym_proc_cache) {
1456 sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2);
1457 rb_gc_register_mark_object(sym_proc_cache);
1458 rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil);
1461 id = SYM2ID(sym);
1462 index = (id % SYM_PROC_CACHE_SIZE) << 1;
1464 if (RARRAY_AREF(sym_proc_cache, index) == sym) {
1465 return RARRAY_AREF(sym_proc_cache, index + 1);
1467 else {
1468 proc = sym_proc_new(rb_cProc, ID2SYM(id));
1469 RARRAY_ASET(sym_proc_cache, index, sym);
1470 RARRAY_ASET(sym_proc_cache, index + 1, proc);
1471 return proc;
1476 * call-seq:
1477 * prc.hash -> integer
1479 * Returns a hash value corresponding to proc body.
1481 * See also Object#hash.
1484 static VALUE
1485 proc_hash(VALUE self)
1487 st_index_t hash;
1488 hash = rb_hash_start(0);
1489 hash = rb_hash_proc(hash, self);
1490 hash = rb_hash_end(hash);
1491 return ST2FIX(hash);
1494 VALUE
1495 rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
1497 VALUE cname = rb_obj_class(self);
1498 VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
1500 again:
1501 switch (vm_block_type(block)) {
1502 case block_type_proc:
1503 block = vm_proc_block(block->as.proc);
1504 goto again;
1505 case block_type_iseq:
1507 const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
1508 rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
1509 rb_iseq_path(iseq),
1510 FIX2INT(iseq->body->location.first_lineno));
1512 break;
1513 case block_type_symbol:
1514 rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
1515 break;
1516 case block_type_ifunc:
1517 rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
1518 break;
1521 if (additional_info) rb_str_cat_cstr(str, additional_info);
1522 rb_str_cat_cstr(str, ">");
1523 return str;
1527 * call-seq:
1528 * prc.to_s -> string
1530 * Returns the unique identifier for this proc, along with
1531 * an indication of where the proc was defined.
1534 static VALUE
1535 proc_to_s(VALUE self)
1537 const rb_proc_t *proc;
1538 GetProcPtr(self, proc);
1539 return rb_block_to_s(self, &proc->block, proc->is_lambda ? " (lambda)" : NULL);
1543 * call-seq:
1544 * prc.to_proc -> proc
1546 * Part of the protocol for converting objects to Proc objects.
1547 * Instances of class Proc simply return themselves.
1550 static VALUE
1551 proc_to_proc(VALUE self)
1553 return self;
1556 static void
1557 bm_mark(void *ptr)
1559 struct METHOD *data = ptr;
1560 rb_gc_mark_movable(data->recv);
1561 rb_gc_mark_movable(data->klass);
1562 rb_gc_mark_movable(data->iclass);
1563 rb_gc_mark_movable((VALUE)data->me);
1566 static void
1567 bm_compact(void *ptr)
1569 struct METHOD *data = ptr;
1570 UPDATE_REFERENCE(data->recv);
1571 UPDATE_REFERENCE(data->klass);
1572 UPDATE_REFERENCE(data->iclass);
1573 UPDATE_TYPED_REFERENCE(rb_method_entry_t *, data->me);
1576 static size_t
1577 bm_memsize(const void *ptr)
1579 return sizeof(struct METHOD);
1582 static const rb_data_type_t method_data_type = {
1583 "method",
1585 bm_mark,
1586 RUBY_TYPED_DEFAULT_FREE,
1587 bm_memsize,
1588 bm_compact,
1590 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1593 VALUE
1594 rb_obj_is_method(VALUE m)
1596 return RBOOL(rb_typeddata_is_kind_of(m, &method_data_type));
1599 static int
1600 respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
1602 /* TODO: merge with obj_respond_to() */
1603 ID rmiss = idRespond_to_missing;
1605 if (obj == Qundef) return 0;
1606 if (rb_method_basic_definition_p(klass, rmiss)) return 0;
1607 return RTEST(rb_funcall(obj, rmiss, 2, sym, scope ? Qfalse : Qtrue));
1611 static VALUE
1612 mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
1614 struct METHOD *data;
1615 VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1616 rb_method_entry_t *me;
1617 rb_method_definition_t *def;
1619 RB_OBJ_WRITE(method, &data->recv, obj);
1620 RB_OBJ_WRITE(method, &data->klass, klass);
1622 def = ZALLOC(rb_method_definition_t);
1623 def->type = VM_METHOD_TYPE_MISSING;
1624 def->original_id = id;
1626 me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
1628 RB_OBJ_WRITE(method, &data->me, me);
1630 return method;
1633 static VALUE
1634 mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
1636 VALUE vid = rb_str_intern(*name);
1637 *name = vid;
1638 if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
1639 return mnew_missing(klass, obj, SYM2ID(vid), mclass);
1642 static VALUE
1643 mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1644 VALUE obj, ID id, VALUE mclass, int scope, int error)
1646 struct METHOD *data;
1647 VALUE method;
1648 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
1650 again:
1651 if (UNDEFINED_METHOD_ENTRY_P(me)) {
1652 if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
1653 return mnew_missing(klass, obj, id, mclass);
1655 if (!error) return Qnil;
1656 rb_print_undef(klass, id, METHOD_VISI_UNDEF);
1658 if (visi == METHOD_VISI_UNDEF) {
1659 visi = METHOD_ENTRY_VISI(me);
1660 RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */
1661 if (scope && (visi != METHOD_VISI_PUBLIC)) {
1662 if (!error) return Qnil;
1663 rb_print_inaccessible(klass, id, visi);
1666 if (me->def->type == VM_METHOD_TYPE_ZSUPER) {
1667 if (me->defined_class) {
1668 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
1669 id = me->def->original_id;
1670 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1672 else {
1673 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner));
1674 id = me->def->original_id;
1675 me = rb_method_entry_without_refinements(klass, id, &iclass);
1677 goto again;
1680 method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1682 RB_OBJ_WRITE(method, &data->recv, obj);
1683 RB_OBJ_WRITE(method, &data->klass, klass);
1684 RB_OBJ_WRITE(method, &data->iclass, iclass);
1685 RB_OBJ_WRITE(method, &data->me, me);
1687 return method;
1690 static VALUE
1691 mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1692 VALUE obj, ID id, VALUE mclass, int scope)
1694 return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
1697 static VALUE
1698 mnew_callable(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
1700 const rb_method_entry_t *me;
1701 VALUE iclass = Qnil;
1703 ASSUME(obj != Qundef);
1704 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1705 return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
1708 static VALUE
1709 mnew_unbound(VALUE klass, ID id, VALUE mclass, int scope)
1711 const rb_method_entry_t *me;
1712 VALUE iclass = Qnil;
1714 me = rb_method_entry_with_refinements(klass, id, &iclass);
1715 return mnew_from_me(me, klass, iclass, Qundef, id, mclass, scope);
1718 static inline VALUE
1719 method_entry_defined_class(const rb_method_entry_t *me)
1721 VALUE defined_class = me->defined_class;
1722 return defined_class ? defined_class : me->owner;
1725 /**********************************************************************
1727 * Document-class: Method
1729 * Method objects are created by Object#method, and are associated
1730 * with a particular object (not just with a class). They may be
1731 * used to invoke the method within the object, and as a block
1732 * associated with an iterator. They may also be unbound from one
1733 * object (creating an UnboundMethod) and bound to another.
1735 * class Thing
1736 * def square(n)
1737 * n*n
1738 * end
1739 * end
1740 * thing = Thing.new
1741 * meth = thing.method(:square)
1743 * meth.call(9) #=> 81
1744 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1746 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
1748 * require 'date'
1749 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1750 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1754 * call-seq:
1755 * meth.eql?(other_meth) -> true or false
1756 * meth == other_meth -> true or false
1758 * Two method objects are equal if they are bound to the same
1759 * object and refer to the same method definition and the classes
1760 * defining the methods are the same class or module.
1763 static VALUE
1764 method_eq(VALUE method, VALUE other)
1766 struct METHOD *m1, *m2;
1767 VALUE klass1, klass2;
1769 if (!rb_obj_is_method(other))
1770 return Qfalse;
1771 if (CLASS_OF(method) != CLASS_OF(other))
1772 return Qfalse;
1774 Check_TypedStruct(method, &method_data_type);
1775 m1 = (struct METHOD *)DATA_PTR(method);
1776 m2 = (struct METHOD *)DATA_PTR(other);
1778 klass1 = method_entry_defined_class(m1->me);
1779 klass2 = method_entry_defined_class(m2->me);
1781 if (!rb_method_entry_eq(m1->me, m2->me) ||
1782 klass1 != klass2 ||
1783 m1->klass != m2->klass ||
1784 m1->recv != m2->recv) {
1785 return Qfalse;
1788 return Qtrue;
1792 * call-seq:
1793 * meth.hash -> integer
1795 * Returns a hash value corresponding to the method object.
1797 * See also Object#hash.
1800 static VALUE
1801 method_hash(VALUE method)
1803 struct METHOD *m;
1804 st_index_t hash;
1806 TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
1807 hash = rb_hash_start((st_index_t)m->recv);
1808 hash = rb_hash_method_entry(hash, m->me);
1809 hash = rb_hash_end(hash);
1811 return ST2FIX(hash);
1815 * call-seq:
1816 * meth.unbind -> unbound_method
1818 * Dissociates <i>meth</i> from its current receiver. The resulting
1819 * UnboundMethod can subsequently be bound to a new object of the
1820 * same class (see UnboundMethod).
1823 static VALUE
1824 method_unbind(VALUE obj)
1826 VALUE method;
1827 struct METHOD *orig, *data;
1829 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
1830 method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
1831 &method_data_type, data);
1832 RB_OBJ_WRITE(method, &data->recv, Qundef);
1833 RB_OBJ_WRITE(method, &data->klass, orig->klass);
1834 RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
1835 RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
1837 return method;
1841 * call-seq:
1842 * meth.receiver -> object
1844 * Returns the bound receiver of the method object.
1846 * (1..3).method(:map).receiver # => 1..3
1849 static VALUE
1850 method_receiver(VALUE obj)
1852 struct METHOD *data;
1854 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1855 return data->recv;
1859 * call-seq:
1860 * meth.name -> symbol
1862 * Returns the name of the method.
1865 static VALUE
1866 method_name(VALUE obj)
1868 struct METHOD *data;
1870 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1871 return ID2SYM(data->me->called_id);
1875 * call-seq:
1876 * meth.original_name -> symbol
1878 * Returns the original name of the method.
1880 * class C
1881 * def foo; end
1882 * alias bar foo
1883 * end
1884 * C.instance_method(:bar).original_name # => :foo
1887 static VALUE
1888 method_original_name(VALUE obj)
1890 struct METHOD *data;
1892 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1893 return ID2SYM(data->me->def->original_id);
1897 * call-seq:
1898 * meth.owner -> class_or_module
1900 * Returns the class or module that defines the method.
1901 * See also Method#receiver.
1903 * (1..3).method(:map).owner #=> Enumerable
1906 static VALUE
1907 method_owner(VALUE obj)
1909 struct METHOD *data;
1910 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1911 return data->me->owner;
1914 void
1915 rb_method_name_error(VALUE klass, VALUE str)
1917 #define MSG(s) rb_fstring_lit("undefined method `%1$s' for"s" `%2$s'")
1918 VALUE c = klass;
1919 VALUE s = Qundef;
1921 if (FL_TEST(c, FL_SINGLETON)) {
1922 VALUE obj = rb_ivar_get(klass, attached);
1924 switch (BUILTIN_TYPE(obj)) {
1925 case T_MODULE:
1926 case T_CLASS:
1927 c = obj;
1928 break;
1929 default:
1930 break;
1933 else if (RB_TYPE_P(c, T_MODULE)) {
1934 s = MSG(" module");
1936 if (s == Qundef) {
1937 s = MSG(" class");
1939 rb_name_err_raise_str(s, c, str);
1940 #undef MSG
1943 static VALUE
1944 obj_method(VALUE obj, VALUE vid, int scope)
1946 ID id = rb_check_id(&vid);
1947 const VALUE klass = CLASS_OF(obj);
1948 const VALUE mclass = rb_cMethod;
1950 if (!id) {
1951 VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
1952 if (m) return m;
1953 rb_method_name_error(klass, vid);
1955 return mnew_callable(klass, obj, id, mclass, scope);
1959 * call-seq:
1960 * obj.method(sym) -> method
1962 * Looks up the named method as a receiver in <i>obj</i>, returning a
1963 * Method object (or raising NameError). The Method object acts as a
1964 * closure in <i>obj</i>'s object instance, so instance variables and
1965 * the value of <code>self</code> remain available.
1967 * class Demo
1968 * def initialize(n)
1969 * @iv = n
1970 * end
1971 * def hello()
1972 * "Hello, @iv = #{@iv}"
1973 * end
1974 * end
1976 * k = Demo.new(99)
1977 * m = k.method(:hello)
1978 * m.call #=> "Hello, @iv = 99"
1980 * l = Demo.new('Fred')
1981 * m = l.method("hello")
1982 * m.call #=> "Hello, @iv = Fred"
1984 * Note that Method implements <code>to_proc</code> method, which
1985 * means it can be used with iterators.
1987 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
1989 * out = File.open('test.txt', 'w')
1990 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
1992 * require 'date'
1993 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1994 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1997 VALUE
1998 rb_obj_method(VALUE obj, VALUE vid)
2000 return obj_method(obj, vid, FALSE);
2004 * call-seq:
2005 * obj.public_method(sym) -> method
2007 * Similar to _method_, searches public method only.
2010 VALUE
2011 rb_obj_public_method(VALUE obj, VALUE vid)
2013 return obj_method(obj, vid, TRUE);
2017 * call-seq:
2018 * obj.singleton_method(sym) -> method
2020 * Similar to _method_, searches singleton method only.
2022 * class Demo
2023 * def initialize(n)
2024 * @iv = n
2025 * end
2026 * def hello()
2027 * "Hello, @iv = #{@iv}"
2028 * end
2029 * end
2031 * k = Demo.new(99)
2032 * def k.hi
2033 * "Hi, @iv = #{@iv}"
2034 * end
2035 * m = k.singleton_method(:hi)
2036 * m.call #=> "Hi, @iv = 99"
2037 * m = k.singleton_method(:hello) #=> NameError
2040 VALUE
2041 rb_obj_singleton_method(VALUE obj, VALUE vid)
2043 VALUE klass = rb_singleton_class_get(obj);
2044 ID id = rb_check_id(&vid);
2046 if (NIL_P(klass)) {
2047 /* goto undef; */
2049 else if (NIL_P(klass = RCLASS_ORIGIN(klass))) {
2050 /* goto undef; */
2052 else if (! id) {
2053 VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
2054 if (m) return m;
2055 /* else goto undef; */
2057 else {
2058 const rb_method_entry_t *me = rb_method_entry_at(klass, id);
2059 vid = ID2SYM(id);
2061 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2062 /* goto undef; */
2064 else if (UNDEFINED_REFINED_METHOD_P(me->def)) {
2065 /* goto undef; */
2067 else {
2068 return mnew_from_me(me, klass, klass, obj, id, rb_cMethod, FALSE);
2072 /* undef: */
2073 rb_name_err_raise("undefined singleton method `%1$s' for `%2$s'",
2074 obj, vid);
2075 UNREACHABLE_RETURN(Qundef);
2079 * call-seq:
2080 * mod.instance_method(symbol) -> unbound_method
2082 * Returns an +UnboundMethod+ representing the given
2083 * instance method in _mod_.
2085 * class Interpreter
2086 * def do_a() print "there, "; end
2087 * def do_d() print "Hello "; end
2088 * def do_e() print "!\n"; end
2089 * def do_v() print "Dave"; end
2090 * Dispatcher = {
2091 * "a" => instance_method(:do_a),
2092 * "d" => instance_method(:do_d),
2093 * "e" => instance_method(:do_e),
2094 * "v" => instance_method(:do_v)
2096 * def interpret(string)
2097 * string.each_char {|b| Dispatcher[b].bind(self).call }
2098 * end
2099 * end
2101 * interpreter = Interpreter.new
2102 * interpreter.interpret('dave')
2104 * <em>produces:</em>
2106 * Hello there, Dave!
2109 static VALUE
2110 rb_mod_instance_method(VALUE mod, VALUE vid)
2112 ID id = rb_check_id(&vid);
2113 if (!id) {
2114 rb_method_name_error(mod, vid);
2116 return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
2120 * call-seq:
2121 * mod.public_instance_method(symbol) -> unbound_method
2123 * Similar to _instance_method_, searches public method only.
2126 static VALUE
2127 rb_mod_public_instance_method(VALUE mod, VALUE vid)
2129 ID id = rb_check_id(&vid);
2130 if (!id) {
2131 rb_method_name_error(mod, vid);
2133 return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
2137 * call-seq:
2138 * define_method(symbol, method) -> symbol
2139 * define_method(symbol) { block } -> symbol
2141 * Defines an instance method in the receiver. The _method_
2142 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2143 * If a block is specified, it is used as the method body.
2144 * If a block or the _method_ parameter has parameters,
2145 * they're used as method parameters.
2146 * This block is evaluated using #instance_eval.
2148 * class A
2149 * def fred
2150 * puts "In Fred"
2151 * end
2152 * def create_method(name, &block)
2153 * self.class.define_method(name, &block)
2154 * end
2155 * define_method(:wilma) { puts "Charge it!" }
2156 * define_method(:flint) {|name| puts "I'm #{name}!"}
2157 * end
2158 * class B < A
2159 * define_method(:barney, instance_method(:fred))
2160 * end
2161 * a = B.new
2162 * a.barney
2163 * a.wilma
2164 * a.flint('Dino')
2165 * a.create_method(:betty) { p self }
2166 * a.betty
2168 * <em>produces:</em>
2170 * In Fred
2171 * Charge it!
2172 * I'm Dino!
2173 * #<B:0x401b39e8>
2176 static VALUE
2177 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
2179 ID id;
2180 VALUE body;
2181 VALUE name;
2182 const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
2183 const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2184 const rb_scope_visibility_t *scope_visi = &default_scope_visi;
2185 int is_method = FALSE;
2187 if (cref) {
2188 scope_visi = CREF_SCOPE_VISI(cref);
2191 rb_check_arity(argc, 1, 2);
2192 name = argv[0];
2193 id = rb_check_id(&name);
2194 if (argc == 1) {
2195 body = rb_block_lambda();
2197 else {
2198 body = argv[1];
2200 if (rb_obj_is_method(body)) {
2201 is_method = TRUE;
2203 else if (rb_obj_is_proc(body)) {
2204 is_method = FALSE;
2206 else {
2207 rb_raise(rb_eTypeError,
2208 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
2209 rb_obj_classname(body));
2212 if (!id) id = rb_to_id(name);
2214 if (is_method) {
2215 struct METHOD *method = (struct METHOD *)DATA_PTR(body);
2216 if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
2217 !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
2218 if (FL_TEST(method->me->owner, FL_SINGLETON)) {
2219 rb_raise(rb_eTypeError,
2220 "can't bind singleton method to a different class");
2222 else {
2223 rb_raise(rb_eTypeError,
2224 "bind argument must be a subclass of % "PRIsVALUE,
2225 method->me->owner);
2228 rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
2229 if (scope_visi->module_func) {
2230 rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
2232 RB_GC_GUARD(body);
2234 else {
2235 VALUE procval = rb_proc_dup(body);
2236 if (vm_proc_iseq(procval) != NULL) {
2237 rb_proc_t *proc;
2238 GetProcPtr(procval, proc);
2239 proc->is_lambda = TRUE;
2240 proc->is_from_method = TRUE;
2242 rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
2243 if (scope_visi->module_func) {
2244 rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
2248 return ID2SYM(id);
2252 * call-seq:
2253 * define_singleton_method(symbol, method) -> symbol
2254 * define_singleton_method(symbol) { block } -> symbol
2256 * Defines a singleton method in the receiver. The _method_
2257 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2258 * If a block is specified, it is used as the method body.
2259 * If a block or a method has parameters, they're used as method parameters.
2261 * class A
2262 * class << self
2263 * def class_name
2264 * to_s
2265 * end
2266 * end
2267 * end
2268 * A.define_singleton_method(:who_am_i) do
2269 * "I am: #{class_name}"
2270 * end
2271 * A.who_am_i # ==> "I am: A"
2273 * guy = "Bob"
2274 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
2275 * guy.hello #=> "Bob: Hello there!"
2277 * chris = "Chris"
2278 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
2279 * chris.greet("Hi") #=> "Hi, I'm Chris!"
2282 static VALUE
2283 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
2285 VALUE klass = rb_singleton_class(obj);
2287 return rb_mod_define_method(argc, argv, klass);
2291 * define_method(symbol, method) -> symbol
2292 * define_method(symbol) { block } -> symbol
2294 * Defines a global function by _method_ or the block.
2297 static VALUE
2298 top_define_method(int argc, VALUE *argv, VALUE obj)
2300 rb_thread_t *th = GET_THREAD();
2301 VALUE klass;
2303 klass = th->top_wrapper;
2304 if (klass) {
2305 rb_warning("main.define_method in the wrapped load is effective only in wrapper module");
2307 else {
2308 klass = rb_cObject;
2310 return rb_mod_define_method(argc, argv, klass);
2314 * call-seq:
2315 * method.clone -> new_method
2317 * Returns a clone of this method.
2319 * class A
2320 * def foo
2321 * return "bar"
2322 * end
2323 * end
2325 * m = A.new.method(:foo)
2326 * m.call # => "bar"
2327 * n = m.clone.call # => "bar"
2330 static VALUE
2331 method_clone(VALUE self)
2333 VALUE clone;
2334 struct METHOD *orig, *data;
2336 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2337 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2338 CLONESETUP(clone, self);
2339 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2340 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2341 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2342 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2343 return clone;
2346 /* Document-method: Method#===
2348 * call-seq:
2349 * method === obj -> result_of_method
2351 * Invokes the method with +obj+ as the parameter like #call.
2352 * This allows a method object to be the target of a +when+ clause
2353 * in a case statement.
2355 * require 'prime'
2357 * case 1373
2358 * when Prime.method(:prime?)
2359 * # ...
2360 * end
2364 /* Document-method: Method#[]
2366 * call-seq:
2367 * meth[args, ...] -> obj
2369 * Invokes the <i>meth</i> with the specified arguments, returning the
2370 * method's return value, like #call.
2372 * m = 12.method("+")
2373 * m[3] #=> 15
2374 * m[20] #=> 32
2378 * call-seq:
2379 * meth.call(args, ...) -> obj
2381 * Invokes the <i>meth</i> with the specified arguments, returning the
2382 * method's return value.
2384 * m = 12.method("+")
2385 * m.call(3) #=> 15
2386 * m.call(20) #=> 32
2389 static VALUE
2390 rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
2392 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2393 return rb_method_call_with_block_kw(argc, argv, method, procval, RB_PASS_CALLED_KEYWORDS);
2396 VALUE
2397 rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
2399 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2400 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
2403 VALUE
2404 rb_method_call(int argc, const VALUE *argv, VALUE method)
2406 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2407 return rb_method_call_with_block(argc, argv, method, procval);
2410 static const rb_callable_method_entry_t *
2411 method_callable_method_entry(const struct METHOD *data)
2413 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
2414 return (const rb_callable_method_entry_t *)data->me;
2417 static inline VALUE
2418 call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
2419 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
2421 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2422 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
2423 method_callable_method_entry(data), kw_splat);
2426 VALUE
2427 rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
2429 const struct METHOD *data;
2430 rb_execution_context_t *ec = GET_EC();
2432 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2433 if (data->recv == Qundef) {
2434 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
2436 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
2439 VALUE
2440 rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
2442 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
2445 /**********************************************************************
2447 * Document-class: UnboundMethod
2449 * Ruby supports two forms of objectified methods. Class Method is
2450 * used to represent methods that are associated with a particular
2451 * object: these method objects are bound to that object. Bound
2452 * method objects for an object can be created using Object#method.
2454 * Ruby also supports unbound methods; methods objects that are not
2455 * associated with a particular object. These can be created either
2456 * by calling Module#instance_method or by calling #unbind on a bound
2457 * method object. The result of both of these is an UnboundMethod
2458 * object.
2460 * Unbound methods can only be called after they are bound to an
2461 * object. That object must be a kind_of? the method's original
2462 * class.
2464 * class Square
2465 * def area
2466 * @side * @side
2467 * end
2468 * def initialize(side)
2469 * @side = side
2470 * end
2471 * end
2473 * area_un = Square.instance_method(:area)
2475 * s = Square.new(12)
2476 * area = area_un.bind(s)
2477 * area.call #=> 144
2479 * Unbound methods are a reference to the method at the time it was
2480 * objectified: subsequent changes to the underlying class will not
2481 * affect the unbound method.
2483 * class Test
2484 * def test
2485 * :original
2486 * end
2487 * end
2488 * um = Test.instance_method(:test)
2489 * class Test
2490 * def test
2491 * :modified
2492 * end
2493 * end
2494 * t = Test.new
2495 * t.test #=> :modified
2496 * um.bind(t).call #=> :original
2500 static void
2501 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)
2503 VALUE methclass = data->me->owner;
2504 VALUE iclass = data->me->defined_class;
2505 VALUE klass = CLASS_OF(recv);
2507 if (RB_TYPE_P(methclass, T_MODULE)) {
2508 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
2509 if (!NIL_P(refined_class)) methclass = refined_class;
2511 if (!RB_TYPE_P(methclass, T_MODULE) &&
2512 methclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, methclass)) {
2513 if (FL_TEST(methclass, FL_SINGLETON)) {
2514 rb_raise(rb_eTypeError,
2515 "singleton method called for a different object");
2517 else {
2518 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
2519 methclass);
2523 const rb_method_entry_t *me = rb_method_entry_clone(data->me);
2525 if (RB_TYPE_P(me->owner, T_MODULE)) {
2526 VALUE ic = rb_class_search_ancestor(klass, me->owner);
2527 if (ic) {
2528 klass = ic;
2529 iclass = ic;
2531 else {
2532 klass = rb_include_class_new(methclass, klass);
2534 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
2537 *methclass_out = methclass;
2538 *klass_out = klass;
2539 *iclass_out = iclass;
2540 *me_out = me;
2544 * call-seq:
2545 * umeth.bind(obj) -> method
2547 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2548 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2549 * be true.
2551 * class A
2552 * def test
2553 * puts "In test, class = #{self.class}"
2554 * end
2555 * end
2556 * class B < A
2557 * end
2558 * class C < B
2559 * end
2562 * um = B.instance_method(:test)
2563 * bm = um.bind(C.new)
2564 * bm.call
2565 * bm = um.bind(B.new)
2566 * bm.call
2567 * bm = um.bind(A.new)
2568 * bm.call
2570 * <em>produces:</em>
2572 * In test, class = C
2573 * In test, class = B
2574 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2575 * from prog.rb:16
2578 static VALUE
2579 umethod_bind(VALUE method, VALUE recv)
2581 VALUE methclass, klass, iclass;
2582 const rb_method_entry_t *me;
2583 const struct METHOD *data;
2584 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2585 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me);
2587 struct METHOD *bound;
2588 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
2589 RB_OBJ_WRITE(method, &bound->recv, recv);
2590 RB_OBJ_WRITE(method, &bound->klass, klass);
2591 RB_OBJ_WRITE(method, &bound->iclass, iclass);
2592 RB_OBJ_WRITE(method, &bound->me, me);
2594 return method;
2598 * call-seq:
2599 * umeth.bind_call(recv, args, ...) -> obj
2601 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2602 * specified arguments.
2603 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2605 static VALUE
2606 umethod_bind_call(int argc, VALUE *argv, VALUE method)
2608 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2609 VALUE recv = argv[0];
2610 argc--;
2611 argv++;
2613 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2614 rb_execution_context_t *ec = GET_EC();
2616 const struct METHOD *data;
2617 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2619 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
2620 if (data->me == (const rb_method_entry_t *)cme) {
2621 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2622 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
2624 else {
2625 VALUE methclass, klass, iclass;
2626 const rb_method_entry_t *me;
2627 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me);
2628 struct METHOD bound = { recv, klass, 0, me };
2630 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
2635 * Returns the number of required parameters and stores the maximum
2636 * number of parameters in max, or UNLIMITED_ARGUMENTS
2637 * if there is no maximum.
2639 static int
2640 method_def_min_max_arity(const rb_method_definition_t *def, int *max)
2642 again:
2643 if (!def) return *max = 0;
2644 switch (def->type) {
2645 case VM_METHOD_TYPE_CFUNC:
2646 if (def->body.cfunc.argc < 0) {
2647 *max = UNLIMITED_ARGUMENTS;
2648 return 0;
2650 return *max = check_argc(def->body.cfunc.argc);
2651 case VM_METHOD_TYPE_ZSUPER:
2652 *max = UNLIMITED_ARGUMENTS;
2653 return 0;
2654 case VM_METHOD_TYPE_ATTRSET:
2655 return *max = 1;
2656 case VM_METHOD_TYPE_IVAR:
2657 return *max = 0;
2658 case VM_METHOD_TYPE_ALIAS:
2659 def = def->body.alias.original_me->def;
2660 goto again;
2661 case VM_METHOD_TYPE_BMETHOD:
2662 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
2663 case VM_METHOD_TYPE_ISEQ:
2664 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
2665 case VM_METHOD_TYPE_UNDEF:
2666 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2667 return *max = 0;
2668 case VM_METHOD_TYPE_MISSING:
2669 *max = UNLIMITED_ARGUMENTS;
2670 return 0;
2671 case VM_METHOD_TYPE_OPTIMIZED: {
2672 switch (def->body.optimized.type) {
2673 case OPTIMIZED_METHOD_TYPE_SEND:
2674 *max = UNLIMITED_ARGUMENTS;
2675 return 0;
2676 case OPTIMIZED_METHOD_TYPE_CALL:
2677 *max = UNLIMITED_ARGUMENTS;
2678 return 0;
2679 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
2680 *max = UNLIMITED_ARGUMENTS;
2681 return 0;
2682 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
2683 *max = 0;
2684 return 0;
2685 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
2686 *max = 1;
2687 return 1;
2688 default:
2689 break;
2691 break;
2693 case VM_METHOD_TYPE_REFINED:
2694 *max = UNLIMITED_ARGUMENTS;
2695 return 0;
2697 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
2698 UNREACHABLE_RETURN(Qnil);
2701 static int
2702 method_def_arity(const rb_method_definition_t *def)
2704 int max, min = method_def_min_max_arity(def, &max);
2705 return min == max ? min : -min-1;
2709 rb_method_entry_arity(const rb_method_entry_t *me)
2711 return method_def_arity(me->def);
2715 * call-seq:
2716 * meth.arity -> integer
2718 * Returns an indication of the number of arguments accepted by a
2719 * method. Returns a nonnegative integer for methods that take a fixed
2720 * number of arguments. For Ruby methods that take a variable number of
2721 * arguments, returns -n-1, where n is the number of required arguments.
2722 * Keyword arguments will be considered as a single additional argument,
2723 * that argument being mandatory if any keyword argument is mandatory.
2724 * For methods written in C, returns -1 if the call takes a
2725 * variable number of arguments.
2727 * class C
2728 * def one; end
2729 * def two(a); end
2730 * def three(*a); end
2731 * def four(a, b); end
2732 * def five(a, b, *c); end
2733 * def six(a, b, *c, &d); end
2734 * def seven(a, b, x:0); end
2735 * def eight(x:, y:); end
2736 * def nine(x:, y:, **z); end
2737 * def ten(*a, x:, y:); end
2738 * end
2739 * c = C.new
2740 * c.method(:one).arity #=> 0
2741 * c.method(:two).arity #=> 1
2742 * c.method(:three).arity #=> -1
2743 * c.method(:four).arity #=> 2
2744 * c.method(:five).arity #=> -3
2745 * c.method(:six).arity #=> -3
2746 * c.method(:seven).arity #=> -3
2747 * c.method(:eight).arity #=> 1
2748 * c.method(:nine).arity #=> 1
2749 * c.method(:ten).arity #=> -2
2751 * "cat".method(:size).arity #=> 0
2752 * "cat".method(:replace).arity #=> 1
2753 * "cat".method(:squeeze).arity #=> -1
2754 * "cat".method(:count).arity #=> -1
2757 static VALUE
2758 method_arity_m(VALUE method)
2760 int n = method_arity(method);
2761 return INT2FIX(n);
2764 static int
2765 method_arity(VALUE method)
2767 struct METHOD *data;
2769 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2770 return rb_method_entry_arity(data->me);
2773 static const rb_method_entry_t *
2774 original_method_entry(VALUE mod, ID id)
2776 const rb_method_entry_t *me;
2778 while ((me = rb_method_entry(mod, id)) != 0) {
2779 const rb_method_definition_t *def = me->def;
2780 if (def->type != VM_METHOD_TYPE_ZSUPER) break;
2781 mod = RCLASS_SUPER(me->owner);
2782 id = def->original_id;
2784 return me;
2787 static int
2788 method_min_max_arity(VALUE method, int *max)
2790 const struct METHOD *data;
2792 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2793 return method_def_min_max_arity(data->me->def, max);
2797 rb_mod_method_arity(VALUE mod, ID id)
2799 const rb_method_entry_t *me = original_method_entry(mod, id);
2800 if (!me) return 0; /* should raise? */
2801 return rb_method_entry_arity(me);
2805 rb_obj_method_arity(VALUE obj, ID id)
2807 return rb_mod_method_arity(CLASS_OF(obj), id);
2810 VALUE
2811 rb_callable_receiver(VALUE callable)
2813 if (rb_obj_is_proc(callable)) {
2814 VALUE binding = proc_binding(callable);
2815 return rb_funcall(binding, rb_intern("receiver"), 0);
2817 else if (rb_obj_is_method(callable)) {
2818 return method_receiver(callable);
2820 else {
2821 return Qundef;
2825 const rb_method_definition_t *
2826 rb_method_def(VALUE method)
2828 const struct METHOD *data;
2830 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2831 return data->me->def;
2834 static const rb_iseq_t *
2835 method_def_iseq(const rb_method_definition_t *def)
2837 switch (def->type) {
2838 case VM_METHOD_TYPE_ISEQ:
2839 return rb_iseq_check(def->body.iseq.iseqptr);
2840 case VM_METHOD_TYPE_BMETHOD:
2841 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
2842 case VM_METHOD_TYPE_ALIAS:
2843 return method_def_iseq(def->body.alias.original_me->def);
2844 case VM_METHOD_TYPE_CFUNC:
2845 case VM_METHOD_TYPE_ATTRSET:
2846 case VM_METHOD_TYPE_IVAR:
2847 case VM_METHOD_TYPE_ZSUPER:
2848 case VM_METHOD_TYPE_UNDEF:
2849 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2850 case VM_METHOD_TYPE_OPTIMIZED:
2851 case VM_METHOD_TYPE_MISSING:
2852 case VM_METHOD_TYPE_REFINED:
2853 break;
2855 return NULL;
2858 const rb_iseq_t *
2859 rb_method_iseq(VALUE method)
2861 return method_def_iseq(rb_method_def(method));
2864 static const rb_cref_t *
2865 method_cref(VALUE method)
2867 const rb_method_definition_t *def = rb_method_def(method);
2869 again:
2870 switch (def->type) {
2871 case VM_METHOD_TYPE_ISEQ:
2872 return def->body.iseq.cref;
2873 case VM_METHOD_TYPE_ALIAS:
2874 def = def->body.alias.original_me->def;
2875 goto again;
2876 default:
2877 return NULL;
2881 static VALUE
2882 method_def_location(const rb_method_definition_t *def)
2884 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
2885 if (!def->body.attr.location)
2886 return Qnil;
2887 return rb_ary_dup(def->body.attr.location);
2889 return iseq_location(method_def_iseq(def));
2892 VALUE
2893 rb_method_entry_location(const rb_method_entry_t *me)
2895 if (!me) return Qnil;
2896 return method_def_location(me->def);
2900 * call-seq:
2901 * meth.source_location -> [String, Integer]
2903 * Returns the Ruby source filename and line number containing this method
2904 * or nil if this method was not defined in Ruby (i.e. native).
2907 VALUE
2908 rb_method_location(VALUE method)
2910 return method_def_location(rb_method_def(method));
2913 static const rb_method_definition_t *
2914 vm_proc_method_def(VALUE procval)
2916 const rb_proc_t *proc;
2917 const struct rb_block *block;
2918 const struct vm_ifunc *ifunc;
2920 GetProcPtr(procval, proc);
2921 block = &proc->block;
2923 if (vm_block_type(block) == block_type_ifunc &&
2924 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
2925 return rb_method_def((VALUE)ifunc->data);
2927 else {
2928 return NULL;
2932 static VALUE
2933 method_def_parameters(const rb_method_definition_t *def)
2935 const rb_iseq_t *iseq;
2936 const rb_method_definition_t *bmethod_def;
2938 switch (def->type) {
2939 case VM_METHOD_TYPE_ISEQ:
2940 iseq = method_def_iseq(def);
2941 return rb_iseq_parameters(iseq, 0);
2942 case VM_METHOD_TYPE_BMETHOD:
2943 if ((iseq = method_def_iseq(def)) != NULL) {
2944 return rb_iseq_parameters(iseq, 0);
2946 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
2947 return method_def_parameters(bmethod_def);
2949 break;
2951 case VM_METHOD_TYPE_ALIAS:
2952 return method_def_parameters(def->body.alias.original_me->def);
2954 case VM_METHOD_TYPE_OPTIMIZED:
2955 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
2956 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
2957 return rb_ary_new_from_args(1, param);
2959 break;
2961 case VM_METHOD_TYPE_CFUNC:
2962 case VM_METHOD_TYPE_ATTRSET:
2963 case VM_METHOD_TYPE_IVAR:
2964 case VM_METHOD_TYPE_ZSUPER:
2965 case VM_METHOD_TYPE_UNDEF:
2966 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2967 case VM_METHOD_TYPE_MISSING:
2968 case VM_METHOD_TYPE_REFINED:
2969 break;
2972 return rb_unnamed_parameters(method_def_arity(def));
2977 * call-seq:
2978 * meth.parameters -> array
2980 * Returns the parameter information of this method.
2982 * def foo(bar); end
2983 * method(:foo).parameters #=> [[:req, :bar]]
2985 * def foo(bar, baz, bat, &blk); end
2986 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
2988 * def foo(bar, *args); end
2989 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
2991 * def foo(bar, baz, *args, &blk); end
2992 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
2995 static VALUE
2996 rb_method_parameters(VALUE method)
2998 return method_def_parameters(rb_method_def(method));
3002 * call-seq:
3003 * meth.to_s -> string
3004 * meth.inspect -> string
3006 * Returns a human-readable description of the underlying method.
3008 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3009 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3011 * In the latter case, the method description includes the "owner" of the
3012 * original method (+Enumerable+ module, which is included into +Range+).
3014 * +inspect+ also provides, when possible, method argument names (call
3015 * sequence) and source location.
3017 * require 'net/http'
3018 * Net::HTTP.method(:get).inspect
3019 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3021 * <code>...</code> in argument definition means argument is optional (has
3022 * some default value).
3024 * For methods defined in C (language core and extensions), location and
3025 * argument names can't be extracted, and only generic information is provided
3026 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3027 * positional argument).
3029 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3030 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3034 static VALUE
3035 method_inspect(VALUE method)
3037 struct METHOD *data;
3038 VALUE str;
3039 const char *sharp = "#";
3040 VALUE mklass;
3041 VALUE defined_class;
3043 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3044 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
3046 mklass = data->iclass;
3047 if (!mklass) mklass = data->klass;
3049 if (RB_TYPE_P(mklass, T_ICLASS)) {
3050 /* TODO: I'm not sure why mklass is T_ICLASS.
3051 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3052 * but not sure it is needed.
3054 mklass = RBASIC_CLASS(mklass);
3057 if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
3058 defined_class = data->me->def->body.alias.original_me->owner;
3060 else {
3061 defined_class = method_entry_defined_class(data->me);
3064 if (RB_TYPE_P(defined_class, T_ICLASS)) {
3065 defined_class = RBASIC_CLASS(defined_class);
3068 if (FL_TEST(mklass, FL_SINGLETON)) {
3069 VALUE v = rb_ivar_get(mklass, attached);
3071 if (data->recv == Qundef) {
3072 rb_str_buf_append(str, rb_inspect(mklass));
3074 else if (data->recv == v) {
3075 rb_str_buf_append(str, rb_inspect(v));
3076 sharp = ".";
3078 else {
3079 rb_str_buf_append(str, rb_inspect(data->recv));
3080 rb_str_buf_cat2(str, "(");
3081 rb_str_buf_append(str, rb_inspect(v));
3082 rb_str_buf_cat2(str, ")");
3083 sharp = ".";
3086 else {
3087 mklass = data->klass;
3088 if (FL_TEST(mklass, FL_SINGLETON)) {
3089 VALUE v = rb_ivar_get(mklass, attached);
3090 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
3091 do {
3092 mklass = RCLASS_SUPER(mklass);
3093 } while (RB_TYPE_P(mklass, T_ICLASS));
3096 rb_str_buf_append(str, rb_inspect(mklass));
3097 if (defined_class != mklass) {
3098 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
3101 rb_str_buf_cat2(str, sharp);
3102 rb_str_append(str, rb_id2str(data->me->called_id));
3103 if (data->me->called_id != data->me->def->original_id) {
3104 rb_str_catf(str, "(%"PRIsVALUE")",
3105 rb_id2str(data->me->def->original_id));
3107 if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
3108 rb_str_buf_cat2(str, " (not-implemented)");
3111 // parameter information
3113 VALUE params = rb_method_parameters(method);
3114 VALUE pair, name, kind;
3115 const VALUE req = ID2SYM(rb_intern("req"));
3116 const VALUE opt = ID2SYM(rb_intern("opt"));
3117 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
3118 const VALUE key = ID2SYM(rb_intern("key"));
3119 const VALUE rest = ID2SYM(rb_intern("rest"));
3120 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
3121 const VALUE block = ID2SYM(rb_intern("block"));
3122 const VALUE nokey = ID2SYM(rb_intern("nokey"));
3123 int forwarding = 0;
3125 rb_str_buf_cat2(str, "(");
3127 for (int i = 0; i < RARRAY_LEN(params); i++) {
3128 pair = RARRAY_AREF(params, i);
3129 kind = RARRAY_AREF(pair, 0);
3130 name = RARRAY_AREF(pair, 1);
3131 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3132 if (NIL_P(name) || name == Qfalse) {
3133 // FIXME: can it be reduced to switch/case?
3134 if (kind == req || kind == opt) {
3135 name = rb_str_new2("_");
3137 else if (kind == rest || kind == keyrest) {
3138 name = rb_str_new2("");
3140 else if (kind == block) {
3141 name = rb_str_new2("block");
3143 else if (kind == nokey) {
3144 name = rb_str_new2("nil");
3148 if (kind == req) {
3149 rb_str_catf(str, "%"PRIsVALUE, name);
3151 else if (kind == opt) {
3152 rb_str_catf(str, "%"PRIsVALUE"=...", name);
3154 else if (kind == keyreq) {
3155 rb_str_catf(str, "%"PRIsVALUE":", name);
3157 else if (kind == key) {
3158 rb_str_catf(str, "%"PRIsVALUE": ...", name);
3160 else if (kind == rest) {
3161 if (name == ID2SYM('*')) {
3162 forwarding = 1;
3163 rb_str_cat_cstr(str, "...");
3165 else {
3166 rb_str_catf(str, "*%"PRIsVALUE, name);
3169 else if (kind == keyrest) {
3170 if (name != ID2SYM(idPow)) {
3171 rb_str_catf(str, "**%"PRIsVALUE, name);
3173 else if (i > 0) {
3174 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3177 else if (kind == block) {
3178 if (name == ID2SYM('&')) {
3179 if (forwarding) {
3180 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3182 else {
3183 rb_str_cat_cstr(str, "...");
3186 else {
3187 rb_str_catf(str, "&%"PRIsVALUE, name);
3190 else if (kind == nokey) {
3191 rb_str_buf_cat2(str, "**nil");
3194 if (i < RARRAY_LEN(params) - 1) {
3195 rb_str_buf_cat2(str, ", ");
3198 rb_str_buf_cat2(str, ")");
3201 { // source location
3202 VALUE loc = rb_method_location(method);
3203 if (!NIL_P(loc)) {
3204 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
3205 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
3209 rb_str_buf_cat2(str, ">");
3211 return str;
3214 static VALUE
3215 bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
3217 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
3220 VALUE
3221 rb_proc_new(
3222 rb_block_call_func_t func,
3223 VALUE val)
3225 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
3226 return procval;
3230 * call-seq:
3231 * meth.to_proc -> proc
3233 * Returns a Proc object corresponding to this method.
3236 static VALUE
3237 method_to_proc(VALUE method)
3239 VALUE procval;
3240 rb_proc_t *proc;
3243 * class Method
3244 * def to_proc
3245 * lambda{|*args|
3246 * self.call(*args)
3248 * end
3249 * end
3251 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
3252 GetProcPtr(procval, proc);
3253 proc->is_from_method = 1;
3254 return procval;
3257 extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
3260 * call-seq:
3261 * meth.super_method -> method
3263 * Returns a Method of superclass which would be called when super is used
3264 * or nil if there is no method on superclass.
3267 static VALUE
3268 method_super_method(VALUE method)
3270 const struct METHOD *data;
3271 VALUE super_class, iclass;
3272 ID mid;
3273 const rb_method_entry_t *me;
3275 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3276 iclass = data->iclass;
3277 if (!iclass) return Qnil;
3278 if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
3279 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
3280 data->me->def->body.alias.original_me->owner));
3281 mid = data->me->def->body.alias.original_me->def->original_id;
3283 else {
3284 super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
3285 mid = data->me->def->original_id;
3287 if (!super_class) return Qnil;
3288 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
3289 if (!me) return Qnil;
3290 return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
3294 * call-seq:
3295 * meth.public? -> true or false
3297 * Returns whether the method is public.
3300 static VALUE
3301 method_public_p(VALUE method)
3303 const struct METHOD *data;
3304 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3305 return RBOOL(METHOD_ENTRY_VISI(data->me) == METHOD_VISI_PUBLIC);
3309 * call-seq:
3310 * meth.protected? -> true or false
3312 * Returns whether the method is protected.
3315 static VALUE
3316 method_protected_p(VALUE method)
3318 const struct METHOD *data;
3319 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3320 return RBOOL(METHOD_ENTRY_VISI(data->me) == METHOD_VISI_PROTECTED);
3324 * call-seq:
3325 * meth.private? -> true or false
3327 * Returns whether the method is private.
3330 static VALUE
3331 method_private_p(VALUE method)
3333 const struct METHOD *data;
3334 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3335 return RBOOL(METHOD_ENTRY_VISI(data->me) == METHOD_VISI_PRIVATE);
3339 * call-seq:
3340 * local_jump_error.exit_value -> obj
3342 * Returns the exit value associated with this +LocalJumpError+.
3344 static VALUE
3345 localjump_xvalue(VALUE exc)
3347 return rb_iv_get(exc, "@exit_value");
3351 * call-seq:
3352 * local_jump_error.reason -> symbol
3354 * The reason this block was terminated:
3355 * :break, :redo, :retry, :next, :return, or :noreason.
3358 static VALUE
3359 localjump_reason(VALUE exc)
3361 return rb_iv_get(exc, "@reason");
3364 rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
3366 static const rb_env_t *
3367 env_clone(const rb_env_t *env, const rb_cref_t *cref)
3369 VALUE *new_ep;
3370 VALUE *new_body;
3371 const rb_env_t *new_env;
3373 VM_ASSERT(env->ep > env->env);
3374 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
3376 if (cref == NULL) {
3377 cref = rb_vm_cref_new_toplevel();
3380 new_body = ALLOC_N(VALUE, env->env_size);
3381 MEMCPY(new_body, env->env, VALUE, env->env_size);
3382 new_ep = &new_body[env->ep - env->env];
3383 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
3384 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
3385 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
3386 return new_env;
3390 * call-seq:
3391 * prc.binding -> binding
3393 * Returns the binding associated with <i>prc</i>.
3395 * def fred(param)
3396 * proc {}
3397 * end
3399 * b = fred(99)
3400 * eval("param", b.binding) #=> 99
3402 static VALUE
3403 proc_binding(VALUE self)
3405 VALUE bindval, binding_self = Qundef;
3406 rb_binding_t *bind;
3407 const rb_proc_t *proc;
3408 const rb_iseq_t *iseq = NULL;
3409 const struct rb_block *block;
3410 const rb_env_t *env = NULL;
3412 GetProcPtr(self, proc);
3413 block = &proc->block;
3415 if (proc->is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
3417 again:
3418 switch (vm_block_type(block)) {
3419 case block_type_iseq:
3420 iseq = block->as.captured.code.iseq;
3421 binding_self = block->as.captured.self;
3422 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3423 break;
3424 case block_type_proc:
3425 GetProcPtr(block->as.proc, proc);
3426 block = &proc->block;
3427 goto again;
3428 case block_type_ifunc:
3430 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
3431 if (IS_METHOD_PROC_IFUNC(ifunc)) {
3432 VALUE method = (VALUE)ifunc->data;
3433 VALUE name = rb_fstring_lit("<empty_iseq>");
3434 rb_iseq_t *empty;
3435 binding_self = method_receiver(method);
3436 iseq = rb_method_iseq(method);
3437 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3438 env = env_clone(env, method_cref(method));
3439 /* set empty iseq */
3440 empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP);
3441 RB_OBJ_WRITE(env, &env->iseq, empty);
3442 break;
3445 /* FALLTHROUGH */
3446 case block_type_symbol:
3447 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
3448 UNREACHABLE_RETURN(Qnil);
3451 bindval = rb_binding_alloc(rb_cBinding);
3452 GetBindingPtr(bindval, bind);
3453 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
3454 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
3455 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
3456 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
3458 if (iseq) {
3459 rb_iseq_check(iseq);
3460 RB_OBJ_WRITE(bindval, &bind->pathobj, iseq->body->location.pathobj);
3461 bind->first_lineno = FIX2INT(rb_iseq_first_lineno(iseq));
3463 else {
3464 RB_OBJ_WRITE(bindval, &bind->pathobj,
3465 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
3466 bind->first_lineno = 1;
3469 return bindval;
3472 static rb_block_call_func curry;
3474 static VALUE
3475 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
3477 VALUE args = rb_ary_new3(3, proc, passed, arity);
3478 rb_proc_t *procp;
3479 int is_lambda;
3481 GetProcPtr(proc, procp);
3482 is_lambda = procp->is_lambda;
3483 rb_ary_freeze(passed);
3484 rb_ary_freeze(args);
3485 proc = rb_proc_new(curry, args);
3486 GetProcPtr(proc, procp);
3487 procp->is_lambda = is_lambda;
3488 return proc;
3491 static VALUE
3492 curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3494 VALUE proc, passed, arity;
3495 proc = RARRAY_AREF(args, 0);
3496 passed = RARRAY_AREF(args, 1);
3497 arity = RARRAY_AREF(args, 2);
3499 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
3500 rb_ary_freeze(passed);
3502 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
3503 if (!NIL_P(blockarg)) {
3504 rb_warn("given block not used");
3506 arity = make_curry_proc(proc, passed, arity);
3507 return arity;
3509 else {
3510 return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
3515 * call-seq:
3516 * prc.curry -> a_proc
3517 * prc.curry(arity) -> a_proc
3519 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3520 * it determines the number of arguments.
3521 * A curried proc receives some arguments. If a sufficient number of
3522 * arguments are supplied, it passes the supplied arguments to the original
3523 * proc and returns the result. Otherwise, returns another curried proc that
3524 * takes the rest of arguments.
3526 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3527 * p b.curry[1][2][3] #=> 6
3528 * p b.curry[1, 2][3, 4] #=> 6
3529 * p b.curry(5)[1][2][3][4][5] #=> 6
3530 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3531 * p b.curry(1)[1] #=> 1
3533 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3534 * p b.curry[1][2][3] #=> 6
3535 * p b.curry[1, 2][3, 4] #=> 10
3536 * p b.curry(5)[1][2][3][4][5] #=> 15
3537 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3538 * p b.curry(1)[1] #=> 1
3540 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3541 * p b.curry[1][2][3] #=> 6
3542 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3543 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3544 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3546 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3547 * p b.curry[1][2][3] #=> 6
3548 * p b.curry[1, 2][3, 4] #=> 10
3549 * p b.curry(5)[1][2][3][4][5] #=> 15
3550 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3551 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3553 * b = proc { :foo }
3554 * p b.curry[] #=> :foo
3556 static VALUE
3557 proc_curry(int argc, const VALUE *argv, VALUE self)
3559 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
3560 VALUE arity;
3562 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
3563 arity = INT2FIX(min_arity);
3565 else {
3566 sarity = FIX2INT(arity);
3567 if (rb_proc_lambda_p(self)) {
3568 rb_check_arity(sarity, min_arity, max_arity);
3572 return make_curry_proc(self, rb_ary_new(), arity);
3576 * call-seq:
3577 * meth.curry -> proc
3578 * meth.curry(arity) -> proc
3580 * Returns a curried proc based on the method. When the proc is called with a number of
3581 * arguments that is lower than the method's arity, then another curried proc is returned.
3582 * Only when enough arguments have been supplied to satisfy the method signature, will the
3583 * method actually be called.
3585 * The optional <i>arity</i> argument should be supplied when currying methods with
3586 * variable arguments to determine how many arguments are needed before the method is
3587 * called.
3589 * def foo(a,b,c)
3590 * [a, b, c]
3591 * end
3593 * proc = self.method(:foo).curry
3594 * proc2 = proc.call(1, 2) #=> #<Proc>
3595 * proc2.call(3) #=> [1,2,3]
3597 * def vararg(*args)
3598 * args
3599 * end
3601 * proc = self.method(:vararg).curry(4)
3602 * proc2 = proc.call(:x) #=> #<Proc>
3603 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3604 * proc3.call(:a) #=> [:x, :y, :z, :a]
3607 static VALUE
3608 rb_method_curry(int argc, const VALUE *argv, VALUE self)
3610 VALUE proc = method_to_proc(self);
3611 return proc_curry(argc, argv, proc);
3614 static VALUE
3615 compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3617 VALUE f, g, fargs;
3618 f = RARRAY_AREF(args, 0);
3619 g = RARRAY_AREF(args, 1);
3621 if (rb_obj_is_proc(g))
3622 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3623 else
3624 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3626 if (rb_obj_is_proc(f))
3627 return rb_proc_call(f, rb_ary_new3(1, fargs));
3628 else
3629 return rb_funcallv(f, idCall, 1, &fargs);
3632 static VALUE
3633 to_callable(VALUE f)
3635 VALUE mesg;
3637 if (rb_obj_is_proc(f)) return f;
3638 if (rb_obj_is_method(f)) return f;
3639 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
3640 mesg = rb_fstring_lit("callable object is expected");
3641 rb_exc_raise(rb_exc_new_str(rb_eTypeError, mesg));
3644 static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
3645 static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
3648 * call-seq:
3649 * prc << g -> a_proc
3651 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3652 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3653 * then calls this proc with the result.
3655 * f = proc {|x| x * x }
3656 * g = proc {|x| x + x }
3657 * p (f << g).call(2) #=> 16
3659 * See Proc#>> for detailed explanations.
3661 static VALUE
3662 proc_compose_to_left(VALUE self, VALUE g)
3664 return rb_proc_compose_to_left(self, to_callable(g));
3667 static VALUE
3668 rb_proc_compose_to_left(VALUE self, VALUE g)
3670 VALUE proc, args, procs[2];
3671 rb_proc_t *procp;
3672 int is_lambda;
3674 procs[0] = self;
3675 procs[1] = g;
3676 args = rb_ary_tmp_new_from_values(0, 2, procs);
3678 if (rb_obj_is_proc(g)) {
3679 GetProcPtr(g, procp);
3680 is_lambda = procp->is_lambda;
3682 else {
3683 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
3684 is_lambda = 1;
3687 proc = rb_proc_new(compose, args);
3688 GetProcPtr(proc, procp);
3689 procp->is_lambda = is_lambda;
3691 return proc;
3695 * call-seq:
3696 * prc >> g -> a_proc
3698 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3699 * The returned proc takes a variable number of arguments, calls this proc with them
3700 * then calls <i>g</i> with the result.
3702 * f = proc {|x| x * x }
3703 * g = proc {|x| x + x }
3704 * p (f >> g).call(2) #=> 8
3706 * <i>g</i> could be other Proc, or Method, or any other object responding to
3707 * +call+ method:
3709 * class Parser
3710 * def self.call(text)
3711 * # ...some complicated parsing logic...
3712 * end
3713 * end
3715 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3716 * pipeline.call('data.json')
3718 * See also Method#>> and Method#<<.
3720 static VALUE
3721 proc_compose_to_right(VALUE self, VALUE g)
3723 return rb_proc_compose_to_right(self, to_callable(g));
3726 static VALUE
3727 rb_proc_compose_to_right(VALUE self, VALUE g)
3729 VALUE proc, args, procs[2];
3730 rb_proc_t *procp;
3731 int is_lambda;
3733 procs[0] = g;
3734 procs[1] = self;
3735 args = rb_ary_tmp_new_from_values(0, 2, procs);
3737 GetProcPtr(self, procp);
3738 is_lambda = procp->is_lambda;
3740 proc = rb_proc_new(compose, args);
3741 GetProcPtr(proc, procp);
3742 procp->is_lambda = is_lambda;
3744 return proc;
3748 * call-seq:
3749 * meth << g -> a_proc
3751 * Returns a proc that is the composition of this method and the given <i>g</i>.
3752 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3753 * then calls this method with the result.
3755 * def f(x)
3756 * x * x
3757 * end
3759 * f = self.method(:f)
3760 * g = proc {|x| x + x }
3761 * p (f << g).call(2) #=> 16
3763 static VALUE
3764 rb_method_compose_to_left(VALUE self, VALUE g)
3766 g = to_callable(g);
3767 self = method_to_proc(self);
3768 return proc_compose_to_left(self, g);
3772 * call-seq:
3773 * meth >> g -> a_proc
3775 * Returns a proc that is the composition of this method and the given <i>g</i>.
3776 * The returned proc takes a variable number of arguments, calls this method
3777 * with them then calls <i>g</i> with the result.
3779 * def f(x)
3780 * x * x
3781 * end
3783 * f = self.method(:f)
3784 * g = proc {|x| x + x }
3785 * p (f >> g).call(2) #=> 8
3787 static VALUE
3788 rb_method_compose_to_right(VALUE self, VALUE g)
3790 g = to_callable(g);
3791 self = method_to_proc(self);
3792 return proc_compose_to_right(self, g);
3796 * call-seq:
3797 * proc.ruby2_keywords -> proc
3799 * Marks the proc as passing keywords through a normal argument splat.
3800 * This should only be called on procs that accept an argument splat
3801 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3802 * marks the proc such that if the proc is called with keyword arguments,
3803 * the final hash argument is marked with a special flag such that if it
3804 * is the final element of a normal argument splat to another method call,
3805 * and that method call does not include explicit keywords or a keyword
3806 * splat, the final element is interpreted as keywords. In other words,
3807 * keywords will be passed through the proc to other methods.
3809 * This should only be used for procs that delegate keywords to another
3810 * method, and only for backwards compatibility with Ruby versions before
3811 * 2.7.
3813 * This method will probably be removed at some point, as it exists only
3814 * for backwards compatibility. As it does not exist in Ruby versions
3815 * before 2.7, check that the proc responds to this method before calling
3816 * it. Also, be aware that if this method is removed, the behavior of the
3817 * proc will change so that it does not pass through keywords.
3819 * module Mod
3820 * foo = ->(meth, *args, &block) do
3821 * send(:"do_#{meth}", *args, &block)
3822 * end
3823 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3824 * end
3827 static VALUE
3828 proc_ruby2_keywords(VALUE procval)
3830 rb_proc_t *proc;
3831 GetProcPtr(procval, proc);
3833 rb_check_frozen(procval);
3835 if (proc->is_from_method) {
3836 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
3837 return procval;
3840 switch (proc->block.type) {
3841 case block_type_iseq:
3842 if (proc->block.as.captured.code.iseq->body->param.flags.has_rest &&
3843 !proc->block.as.captured.code.iseq->body->param.flags.has_kw &&
3844 !proc->block.as.captured.code.iseq->body->param.flags.has_kwrest) {
3845 proc->block.as.captured.code.iseq->body->param.flags.ruby2_keywords = 1;
3847 else {
3848 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
3850 break;
3851 default:
3852 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
3853 break;
3856 return procval;
3860 * Document-class: LocalJumpError
3862 * Raised when Ruby can't yield as requested.
3864 * A typical scenario is attempting to yield when no block is given:
3866 * def call_block
3867 * yield 42
3868 * end
3869 * call_block
3871 * <em>raises the exception:</em>
3873 * LocalJumpError: no block given (yield)
3875 * A more subtle example:
3877 * def get_me_a_return
3878 * Proc.new { return 42 }
3879 * end
3880 * get_me_a_return.call
3882 * <em>raises the exception:</em>
3884 * LocalJumpError: unexpected return
3888 * Document-class: SystemStackError
3890 * Raised in case of a stack overflow.
3892 * def me_myself_and_i
3893 * me_myself_and_i
3894 * end
3895 * me_myself_and_i
3897 * <em>raises the exception:</em>
3899 * SystemStackError: stack level too deep
3903 * Document-class: Proc
3905 * A +Proc+ object is an encapsulation of a block of code, which can be stored
3906 * in a local variable, passed to a method or another Proc, and can be called.
3907 * Proc is an essential concept in Ruby and a core of its functional
3908 * programming features.
3910 * square = Proc.new {|x| x**2 }
3912 * square.call(3) #=> 9
3913 * # shorthands:
3914 * square.(3) #=> 9
3915 * square[3] #=> 9
3917 * Proc objects are _closures_, meaning they remember and can use the entire
3918 * context in which they were created.
3920 * def gen_times(factor)
3921 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
3922 * end
3924 * times3 = gen_times(3)
3925 * times5 = gen_times(5)
3927 * times3.call(12) #=> 36
3928 * times5.call(5) #=> 25
3929 * times3.call(times5.call(4)) #=> 60
3931 * == Creation
3933 * There are several methods to create a Proc
3935 * * Use the Proc class constructor:
3937 * proc1 = Proc.new {|x| x**2 }
3939 * * Use the Kernel#proc method as a shorthand of Proc.new:
3941 * proc2 = proc {|x| x**2 }
3943 * * Receiving a block of code into proc argument (note the <code>&</code>):
3945 * def make_proc(&block)
3946 * block
3947 * end
3949 * proc3 = make_proc {|x| x**2 }
3951 * * Construct a proc with lambda semantics using the Kernel#lambda method
3952 * (see below for explanations about lambdas):
3954 * lambda1 = lambda {|x| x**2 }
3956 * * Use the {Lambda proc literal}[doc/syntax/literals_rdoc.html#label-Lambda+Proc+Literals] syntax
3957 * (also constructs a proc with lambda semantics):
3959 * lambda2 = ->(x) { x**2 }
3961 * == Lambda and non-lambda semantics
3963 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
3964 * Differences are:
3966 * * In lambdas, +return+ and +break+ means exit from this lambda;
3967 * * In non-lambda procs, +return+ means exit from embracing method
3968 * (and will throw +LocalJumpError+ if invoked outside the method);
3969 * * In non-lambda procs, +break+ means exit from the method which the block given for.
3970 * (and will throw +LocalJumpError+ if invoked after the method returns);
3971 * * In lambdas, arguments are treated in the same way as in methods: strict,
3972 * with +ArgumentError+ for mismatching argument number,
3973 * and no additional argument processing;
3974 * * Regular procs accept arguments more generously: missing arguments
3975 * are filled with +nil+, single Array arguments are deconstructed if the
3976 * proc has multiple arguments, and there is no error raised on extra
3977 * arguments.
3979 * Examples:
3981 * # +return+ in non-lambda proc, +b+, exits +m2+.
3982 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
3983 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
3984 * #=> []
3986 * # +break+ in non-lambda proc, +b+, exits +m1+.
3987 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
3988 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
3989 * #=> [:m2]
3991 * # +next+ in non-lambda proc, +b+, exits the block.
3992 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
3993 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
3994 * #=> [:m1, :m2]
3996 * # Using +proc+ method changes the behavior as follows because
3997 * # The block is given for +proc+ method and embraced by +m2+.
3998 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
3999 * #=> []
4000 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4001 * # break from proc-closure (LocalJumpError)
4002 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4003 * #=> [:m1, :m2]
4005 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4006 * # (+lambda+ method behaves same.)
4007 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4008 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4009 * #=> [:m1, :m2]
4010 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4011 * #=> [:m1, :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 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4016 * p.call(1, 2) #=> "x=1, y=2"
4017 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4018 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4019 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4021 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4022 * l.call(1, 2) #=> "x=1, y=2"
4023 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4024 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4025 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4027 * def test_return
4028 * -> { return 3 }.call # just returns from lambda into method body
4029 * proc { return 4 }.call # returns from method
4030 * return 5
4031 * end
4033 * test_return # => 4, return from proc
4035 * Lambdas are useful as self-sufficient functions, in particular useful as
4036 * arguments to higher-order functions, behaving exactly like Ruby methods.
4038 * Procs are useful for implementing iterators:
4040 * def test
4041 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4042 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4043 * end
4045 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4046 * which means that the internal arrays will be deconstructed to pairs of
4047 * arguments, and +return+ will exit from the method +test+. That would
4048 * not be possible with a stricter lambda.
4050 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4052 * Lambda semantics is typically preserved during the proc lifetime, including
4053 * <code>&</code>-deconstruction to a block of code:
4055 * p = proc {|x, y| x }
4056 * l = lambda {|x, y| x }
4057 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4058 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4060 * The only exception is dynamic method definition: even if defined by
4061 * passing a non-lambda proc, methods still have normal semantics of argument
4062 * checking.
4064 * class C
4065 * define_method(:e, &proc {})
4066 * end
4067 * C.new.e(1,2) #=> ArgumentError
4068 * C.new.method(:e).to_proc.lambda? #=> true
4070 * This exception ensures that methods never have unusual argument passing
4071 * conventions, and makes it easy to have wrappers defining methods that
4072 * behave as usual.
4074 * class C
4075 * def self.def2(name, &body)
4076 * define_method(name, &body)
4077 * end
4079 * def2(:f) {}
4080 * end
4081 * C.new.f(1,2) #=> ArgumentError
4083 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4084 * yet defines a method which has normal semantics.
4086 * == Conversion of other objects to procs
4088 * Any object that implements the +to_proc+ method can be converted into
4089 * a proc by the <code>&</code> operator, and therefore can be
4090 * consumed by iterators.
4093 * class Greeter
4094 * def initialize(greeting)
4095 * @greeting = greeting
4096 * end
4098 * def to_proc
4099 * proc {|name| "#{@greeting}, #{name}!" }
4100 * end
4101 * end
4103 * hi = Greeter.new("Hi")
4104 * hey = Greeter.new("Hey")
4105 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4106 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4108 * Of the Ruby core classes, this method is implemented by Symbol,
4109 * Method, and Hash.
4111 * :to_s.to_proc.call(1) #=> "1"
4112 * [1, 2].map(&:to_s) #=> ["1", "2"]
4114 * method(:puts).to_proc.call(1) # prints 1
4115 * [1, 2].each(&method(:puts)) # prints 1, 2
4117 * {test: 1}.to_proc.call(:test) #=> 1
4118 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4120 * == Orphaned Proc
4122 * +return+ and +break+ in a block exit a method.
4123 * If a Proc object is generated from the block and the Proc object
4124 * survives until the method is returned, +return+ and +break+ cannot work.
4125 * In such case, +return+ and +break+ raises LocalJumpError.
4126 * A Proc object in such situation is called as orphaned Proc object.
4128 * Note that the method to exit is different for +return+ and +break+.
4129 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4131 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4132 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4134 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4135 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4137 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4138 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4140 * Since +return+ and +break+ exits the block itself in lambdas,
4141 * lambdas cannot be orphaned.
4143 * == Numbered parameters
4145 * Numbered parameters are implicitly defined block parameters intended to
4146 * simplify writing short blocks:
4148 * # Explicit parameter:
4149 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4150 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4152 * # Implicit parameter:
4153 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4154 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4156 * Parameter names from +_1+ to +_9+ are supported:
4158 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4159 * # => [120, 150, 180]
4161 * Though, it is advised to resort to them wisely, probably limiting
4162 * yourself to +_1+ and +_2+, and to one-line blocks.
4164 * Numbered parameters can't be used together with explicitly named
4165 * ones:
4167 * [10, 20, 30].map { |x| _1**2 }
4168 * # SyntaxError (ordinary parameter is defined)
4170 * To avoid conflicts, naming local variables or method
4171 * arguments +_1+, +_2+ and so on, causes a warning.
4173 * _1 = 'test'
4174 * # warning: `_1' is reserved as numbered parameter
4176 * Using implicit numbered parameters affects block's arity:
4178 * p = proc { _1 + _2 }
4179 * l = lambda { _1 + _2 }
4180 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4181 * p.arity # => 2
4182 * l.parameters # => [[:req, :_1], [:req, :_2]]
4183 * l.arity # => 2
4185 * Blocks with numbered parameters can't be nested:
4187 * %w[test me].each { _1.each_char { p _1 } }
4188 * # SyntaxError (numbered parameter is already used in outer block here)
4189 * # %w[test me].each { _1.each_char { p _1 } }
4190 * # ^~
4192 * Numbered parameters were introduced in Ruby 2.7.
4196 void
4197 Init_Proc(void)
4199 #undef rb_intern
4200 /* Proc */
4201 rb_cProc = rb_define_class("Proc", rb_cObject);
4202 rb_undef_alloc_func(rb_cProc);
4203 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
4205 rb_add_method_optimized(rb_cProc, idCall, OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4206 rb_add_method_optimized(rb_cProc, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4207 rb_add_method_optimized(rb_cProc, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4208 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4210 #if 0 /* for RDoc */
4211 rb_define_method(rb_cProc, "call", proc_call, -1);
4212 rb_define_method(rb_cProc, "[]", proc_call, -1);
4213 rb_define_method(rb_cProc, "===", proc_call, -1);
4214 rb_define_method(rb_cProc, "yield", proc_call, -1);
4215 #endif
4217 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
4218 rb_define_method(rb_cProc, "arity", proc_arity, 0);
4219 rb_define_method(rb_cProc, "clone", proc_clone, 0);
4220 rb_define_method(rb_cProc, "dup", rb_proc_dup, 0);
4221 rb_define_method(rb_cProc, "hash", proc_hash, 0);
4222 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
4223 rb_define_alias(rb_cProc, "inspect", "to_s");
4224 rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
4225 rb_define_method(rb_cProc, "binding", proc_binding, 0);
4226 rb_define_method(rb_cProc, "curry", proc_curry, -1);
4227 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
4228 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
4229 rb_define_method(rb_cProc, "==", proc_eq, 1);
4230 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
4231 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
4232 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, 0);
4233 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
4234 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4236 /* Exceptions */
4237 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
4238 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
4239 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
4241 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
4242 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
4244 /* utility functions */
4245 rb_define_global_function("proc", f_proc, 0);
4246 rb_define_global_function("lambda", f_lambda, 0);
4248 /* Method */
4249 rb_cMethod = rb_define_class("Method", rb_cObject);
4250 rb_undef_alloc_func(rb_cMethod);
4251 rb_undef_method(CLASS_OF(rb_cMethod), "new");
4252 rb_define_method(rb_cMethod, "==", method_eq, 1);
4253 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
4254 rb_define_method(rb_cMethod, "hash", method_hash, 0);
4255 rb_define_method(rb_cMethod, "clone", method_clone, 0);
4256 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
4257 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
4258 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
4259 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
4260 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
4261 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
4262 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
4263 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
4264 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
4265 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
4266 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
4267 rb_define_method(rb_cMethod, "name", method_name, 0);
4268 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
4269 rb_define_method(rb_cMethod, "owner", method_owner, 0);
4270 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
4271 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
4272 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
4273 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
4274 rb_define_method(rb_cMethod, "public?", method_public_p, 0);
4275 rb_define_method(rb_cMethod, "protected?", method_protected_p, 0);
4276 rb_define_method(rb_cMethod, "private?", method_private_p, 0);
4277 rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
4278 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
4279 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
4281 /* UnboundMethod */
4282 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
4283 rb_undef_alloc_func(rb_cUnboundMethod);
4284 rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
4285 rb_define_method(rb_cUnboundMethod, "==", method_eq, 1);
4286 rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1);
4287 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
4288 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
4289 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
4290 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
4291 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
4292 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
4293 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
4294 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
4295 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
4296 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
4297 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
4298 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
4299 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
4300 rb_define_method(rb_cUnboundMethod, "public?", method_public_p, 0);
4301 rb_define_method(rb_cUnboundMethod, "protected?", method_protected_p, 0);
4302 rb_define_method(rb_cUnboundMethod, "private?", method_private_p, 0);
4304 /* Module#*_method */
4305 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
4306 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
4307 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
4309 /* Kernel */
4310 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
4312 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
4313 "define_method", top_define_method, -1);
4317 * Objects of class Binding encapsulate the execution context at some
4318 * particular place in the code and retain this context for future
4319 * use. The variables, methods, value of <code>self</code>, and
4320 * possibly an iterator block that can be accessed in this context
4321 * are all retained. Binding objects can be created using
4322 * Kernel#binding, and are made available to the callback of
4323 * Kernel#set_trace_func and instances of TracePoint.
4325 * These binding objects can be passed as the second argument of the
4326 * Kernel#eval method, establishing an environment for the
4327 * evaluation.
4329 * class Demo
4330 * def initialize(n)
4331 * @secret = n
4332 * end
4333 * def get_binding
4334 * binding
4335 * end
4336 * end
4338 * k1 = Demo.new(99)
4339 * b1 = k1.get_binding
4340 * k2 = Demo.new(-3)
4341 * b2 = k2.get_binding
4343 * eval("@secret", b1) #=> 99
4344 * eval("@secret", b2) #=> -3
4345 * eval("@secret") #=> nil
4347 * Binding objects have no class-specific methods.
4351 void
4352 Init_Binding(void)
4354 rb_cBinding = rb_define_class("Binding", rb_cObject);
4355 rb_undef_alloc_func(rb_cBinding);
4356 rb_undef_method(CLASS_OF(rb_cBinding), "new");
4357 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
4358 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
4359 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
4360 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
4361 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
4362 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
4363 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
4364 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
4365 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
4366 rb_define_global_function("binding", rb_f_binding, 0);