Tempfile document updated.
[ruby.git] / proc.c
blob1a67a636632a90a92e3c3a08efc83b3ac3f08ed5
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 "internal.h"
14 #include "internal/class.h"
15 #include "internal/error.h"
16 #include "internal/eval.h"
17 #include "internal/gc.h"
18 #include "internal/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 const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
28 struct METHOD {
29 const VALUE recv;
30 const VALUE klass;
31 /* needed for #super_method */
32 const VALUE iclass;
33 /* Different than me->owner only for ZSUPER methods.
34 This is error-prone but unavoidable unless ZSUPER methods are removed. */
35 const VALUE owner;
36 const rb_method_entry_t * const me;
37 /* for bound methods, `me' should be rb_callable_method_entry_t * */
40 VALUE rb_cUnboundMethod;
41 VALUE rb_cMethod;
42 VALUE rb_cBinding;
43 VALUE rb_cProc;
45 static rb_block_call_func bmcall;
46 static int method_arity(VALUE);
47 static int method_min_max_arity(VALUE, int *max);
48 static VALUE proc_binding(VALUE self);
50 /* Proc */
52 #define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
54 static void
55 block_mark_and_move(struct rb_block *block)
57 switch (block->type) {
58 case block_type_iseq:
59 case block_type_ifunc:
61 struct rb_captured_block *captured = &block->as.captured;
62 rb_gc_mark_and_move(&captured->self);
63 rb_gc_mark_and_move(&captured->code.val);
64 if (captured->ep) {
65 rb_gc_mark_and_move((VALUE *)&captured->ep[VM_ENV_DATA_INDEX_ENV]);
68 break;
69 case block_type_symbol:
70 rb_gc_mark_and_move(&block->as.symbol);
71 break;
72 case block_type_proc:
73 rb_gc_mark_and_move(&block->as.proc);
74 break;
78 static void
79 proc_mark_and_move(void *ptr)
81 rb_proc_t *proc = ptr;
82 block_mark_and_move((struct rb_block *)&proc->block);
85 typedef struct {
86 rb_proc_t basic;
87 VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
88 } cfunc_proc_t;
90 static size_t
91 proc_memsize(const void *ptr)
93 const rb_proc_t *proc = ptr;
94 if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1)
95 return sizeof(cfunc_proc_t);
96 return sizeof(rb_proc_t);
99 static const rb_data_type_t proc_data_type = {
100 "proc",
102 proc_mark_and_move,
103 RUBY_TYPED_DEFAULT_FREE,
104 proc_memsize,
105 proc_mark_and_move,
107 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
110 VALUE
111 rb_proc_alloc(VALUE klass)
113 rb_proc_t *proc;
114 return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
117 VALUE
118 rb_obj_is_proc(VALUE proc)
120 return RBOOL(rb_typeddata_is_kind_of(proc, &proc_data_type));
123 /* :nodoc: */
124 static VALUE
125 proc_clone(VALUE self)
127 VALUE procval = rb_proc_dup(self);
128 return rb_obj_clone_setup(self, procval, Qnil);
131 /* :nodoc: */
132 static VALUE
133 proc_dup(VALUE self)
135 VALUE procval = rb_proc_dup(self);
136 return rb_obj_dup_setup(self, procval);
140 * call-seq:
141 * prc.lambda? -> true or false
143 * Returns +true+ if a Proc object is lambda.
144 * +false+ if non-lambda.
146 * The lambda-ness affects argument handling and the behavior of +return+ and +break+.
148 * A Proc object generated by +proc+ ignores extra arguments.
150 * proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
152 * It provides +nil+ for missing arguments.
154 * proc {|a,b| [a,b] }.call(1) #=> [1,nil]
156 * It expands a single array argument.
158 * proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
160 * A Proc object generated by +lambda+ doesn't have such tricks.
162 * lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError
163 * lambda {|a,b| [a,b] }.call(1) #=> ArgumentError
164 * lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
166 * Proc#lambda? is a predicate for the tricks.
167 * It returns +true+ if no tricks apply.
169 * lambda {}.lambda? #=> true
170 * proc {}.lambda? #=> false
172 * Proc.new is the same as +proc+.
174 * Proc.new {}.lambda? #=> false
176 * +lambda+, +proc+ and Proc.new preserve the tricks of
177 * a Proc object given by <code>&</code> argument.
179 * lambda(&lambda {}).lambda? #=> true
180 * proc(&lambda {}).lambda? #=> true
181 * Proc.new(&lambda {}).lambda? #=> true
183 * lambda(&proc {}).lambda? #=> false
184 * proc(&proc {}).lambda? #=> false
185 * Proc.new(&proc {}).lambda? #=> false
187 * A Proc object generated by <code>&</code> argument has the tricks
189 * def n(&b) b.lambda? end
190 * n {} #=> false
192 * The <code>&</code> argument preserves the tricks if a Proc object
193 * is given by <code>&</code> argument.
195 * n(&lambda {}) #=> true
196 * n(&proc {}) #=> false
197 * n(&Proc.new {}) #=> false
199 * A Proc object converted from a method has no tricks.
201 * def m() end
202 * method(:m).to_proc.lambda? #=> true
204 * n(&method(:m)) #=> true
205 * n(&method(:m).to_proc) #=> true
207 * +define_method+ is treated the same as method definition.
208 * The defined method has no tricks.
210 * class C
211 * define_method(:d) {}
212 * end
213 * C.new.d(1,2) #=> ArgumentError
214 * C.new.method(:d).to_proc.lambda? #=> true
216 * +define_method+ always defines a method without the tricks,
217 * even if a non-lambda Proc object is given.
218 * This is the only exception for which the tricks are not preserved.
220 * class C
221 * define_method(:e, &proc {})
222 * end
223 * C.new.e(1,2) #=> ArgumentError
224 * C.new.method(:e).to_proc.lambda? #=> true
226 * This exception ensures that methods never have tricks
227 * and makes it easy to have wrappers to define methods that behave as usual.
229 * class C
230 * def self.def2(name, &body)
231 * define_method(name, &body)
232 * end
234 * def2(:f) {}
235 * end
236 * C.new.f(1,2) #=> ArgumentError
238 * The wrapper <i>def2</i> defines a method which has no tricks.
242 VALUE
243 rb_proc_lambda_p(VALUE procval)
245 rb_proc_t *proc;
246 GetProcPtr(procval, proc);
248 return RBOOL(proc->is_lambda);
251 /* Binding */
253 static void
254 binding_free(void *ptr)
256 RUBY_FREE_ENTER("binding");
257 ruby_xfree(ptr);
258 RUBY_FREE_LEAVE("binding");
261 static void
262 binding_mark_and_move(void *ptr)
264 rb_binding_t *bind = ptr;
266 block_mark_and_move((struct rb_block *)&bind->block);
267 rb_gc_mark_and_move((VALUE *)&bind->pathobj);
270 static size_t
271 binding_memsize(const void *ptr)
273 return sizeof(rb_binding_t);
276 const rb_data_type_t ruby_binding_data_type = {
277 "binding",
279 binding_mark_and_move,
280 binding_free,
281 binding_memsize,
282 binding_mark_and_move,
284 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
287 VALUE
288 rb_binding_alloc(VALUE klass)
290 VALUE obj;
291 rb_binding_t *bind;
292 obj = TypedData_Make_Struct(klass, rb_binding_t, &ruby_binding_data_type, bind);
293 #if YJIT_STATS
294 rb_yjit_collect_binding_alloc();
295 #endif
296 return obj;
300 /* :nodoc: */
301 static VALUE
302 binding_dup(VALUE self)
304 VALUE bindval = rb_binding_alloc(rb_cBinding);
305 rb_binding_t *src, *dst;
306 GetBindingPtr(self, src);
307 GetBindingPtr(bindval, dst);
308 rb_vm_block_copy(bindval, &dst->block, &src->block);
309 RB_OBJ_WRITE(bindval, &dst->pathobj, src->pathobj);
310 dst->first_lineno = src->first_lineno;
311 return rb_obj_dup_setup(self, bindval);
314 /* :nodoc: */
315 static VALUE
316 binding_clone(VALUE self)
318 VALUE bindval = binding_dup(self);
319 return rb_obj_clone_setup(self, bindval, Qnil);
322 VALUE
323 rb_binding_new(void)
325 rb_execution_context_t *ec = GET_EC();
326 return rb_vm_make_binding(ec, ec->cfp);
330 * call-seq:
331 * binding -> a_binding
333 * Returns a Binding object, describing the variable and
334 * method bindings at the point of call. This object can be used when
335 * calling Binding#eval to execute the evaluated command in this
336 * environment, or extracting its local variables.
338 * class User
339 * def initialize(name, position)
340 * @name = name
341 * @position = position
342 * end
344 * def get_binding
345 * binding
346 * end
347 * end
349 * user = User.new('Joan', 'manager')
350 * template = '{name: @name, position: @position}'
352 * # evaluate template in context of the object
353 * eval(template, user.get_binding)
354 * #=> {:name=>"Joan", :position=>"manager"}
356 * Binding#local_variable_get can be used to access the variables
357 * whose names are reserved Ruby keywords:
359 * # This is valid parameter declaration, but `if` parameter can't
360 * # be accessed by name, because it is a reserved word.
361 * def validate(field, validation, if: nil)
362 * condition = binding.local_variable_get('if')
363 * return unless condition
365 * # ...Some implementation ...
366 * end
368 * validate(:name, :empty?, if: false) # skips validation
369 * validate(:name, :empty?, if: true) # performs validation
373 static VALUE
374 rb_f_binding(VALUE self)
376 return rb_binding_new();
380 * call-seq:
381 * binding.eval(string [, filename [,lineno]]) -> obj
383 * Evaluates the Ruby expression(s) in <em>string</em>, in the
384 * <em>binding</em>'s context. If the optional <em>filename</em> and
385 * <em>lineno</em> parameters are present, they will be used when
386 * reporting syntax errors.
388 * def get_binding(param)
389 * binding
390 * end
391 * b = get_binding("hello")
392 * b.eval("param") #=> "hello"
395 static VALUE
396 bind_eval(int argc, VALUE *argv, VALUE bindval)
398 VALUE args[4];
400 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
401 args[1] = bindval;
402 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
405 static const VALUE *
406 get_local_variable_ptr(const rb_env_t **envp, ID lid)
408 const rb_env_t *env = *envp;
409 do {
410 if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) {
411 if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) {
412 return NULL;
415 const rb_iseq_t *iseq = env->iseq;
416 unsigned int i;
418 VM_ASSERT(rb_obj_is_iseq((VALUE)iseq));
420 for (i=0; i<ISEQ_BODY(iseq)->local_table_size; i++) {
421 if (ISEQ_BODY(iseq)->local_table[i] == lid) {
422 if (ISEQ_BODY(iseq)->local_iseq == iseq &&
423 ISEQ_BODY(iseq)->param.flags.has_block &&
424 (unsigned int)ISEQ_BODY(iseq)->param.block_start == i) {
425 const VALUE *ep = env->ep;
426 if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) {
427 RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep)));
428 VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM);
432 *envp = env;
433 return &env->env[i];
437 else {
438 *envp = NULL;
439 return NULL;
441 } while ((env = rb_vm_env_prev_env(env)) != NULL);
443 *envp = NULL;
444 return NULL;
448 * check local variable name.
449 * returns ID if it's an already interned symbol, or 0 with setting
450 * local name in String to *namep.
452 static ID
453 check_local_id(VALUE bindval, volatile VALUE *pname)
455 ID lid = rb_check_id(pname);
456 VALUE name = *pname;
458 if (lid) {
459 if (!rb_is_local_id(lid)) {
460 rb_name_err_raise("wrong local variable name '%1$s' for %2$s",
461 bindval, ID2SYM(lid));
464 else {
465 if (!rb_is_local_name(name)) {
466 rb_name_err_raise("wrong local variable name '%1$s' for %2$s",
467 bindval, name);
469 return 0;
471 return lid;
475 * call-seq:
476 * binding.local_variables -> Array
478 * Returns the names of the binding's local variables as symbols.
480 * def foo
481 * a = 1
482 * 2.times do |n|
483 * binding.local_variables #=> [:a, :n]
484 * end
485 * end
487 * This method is the short version of the following code:
489 * binding.eval("local_variables")
492 static VALUE
493 bind_local_variables(VALUE bindval)
495 const rb_binding_t *bind;
496 const rb_env_t *env;
498 GetBindingPtr(bindval, bind);
499 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
500 return rb_vm_env_local_variables(env);
504 * call-seq:
505 * binding.local_variable_get(symbol) -> obj
507 * Returns the value of the local variable +symbol+.
509 * def foo
510 * a = 1
511 * binding.local_variable_get(:a) #=> 1
512 * binding.local_variable_get(:b) #=> NameError
513 * end
515 * This method is the short version of the following code:
517 * binding.eval("#{symbol}")
520 static VALUE
521 bind_local_variable_get(VALUE bindval, VALUE sym)
523 ID lid = check_local_id(bindval, &sym);
524 const rb_binding_t *bind;
525 const VALUE *ptr;
526 const rb_env_t *env;
528 if (!lid) goto undefined;
530 GetBindingPtr(bindval, bind);
532 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
533 if ((ptr = get_local_variable_ptr(&env, lid)) != NULL) {
534 return *ptr;
537 sym = ID2SYM(lid);
538 undefined:
539 rb_name_err_raise("local variable '%1$s' is not defined for %2$s",
540 bindval, sym);
541 UNREACHABLE_RETURN(Qundef);
545 * call-seq:
546 * binding.local_variable_set(symbol, obj) -> obj
548 * Set local variable named +symbol+ as +obj+.
550 * def foo
551 * a = 1
552 * bind = binding
553 * bind.local_variable_set(:a, 2) # set existing local variable `a'
554 * bind.local_variable_set(:b, 3) # create new local variable `b'
555 * # `b' exists only in binding
557 * p bind.local_variable_get(:a) #=> 2
558 * p bind.local_variable_get(:b) #=> 3
559 * p a #=> 2
560 * p b #=> NameError
561 * end
563 * This method behaves similarly to the following code:
565 * binding.eval("#{symbol} = #{obj}")
567 * if +obj+ can be dumped in Ruby code.
569 static VALUE
570 bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
572 ID lid = check_local_id(bindval, &sym);
573 rb_binding_t *bind;
574 const VALUE *ptr;
575 const rb_env_t *env;
577 if (!lid) lid = rb_intern_str(sym);
579 GetBindingPtr(bindval, bind);
580 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
581 if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) {
582 /* not found. create new env */
583 ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
584 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
587 #if YJIT_STATS
588 rb_yjit_collect_binding_set();
589 #endif
591 RB_OBJ_WRITE(env, ptr, val);
593 return val;
597 * call-seq:
598 * binding.local_variable_defined?(symbol) -> obj
600 * Returns +true+ if a local variable +symbol+ exists.
602 * def foo
603 * a = 1
604 * binding.local_variable_defined?(:a) #=> true
605 * binding.local_variable_defined?(:b) #=> false
606 * end
608 * This method is the short version of the following code:
610 * binding.eval("defined?(#{symbol}) == 'local-variable'")
613 static VALUE
614 bind_local_variable_defined_p(VALUE bindval, VALUE sym)
616 ID lid = check_local_id(bindval, &sym);
617 const rb_binding_t *bind;
618 const rb_env_t *env;
620 if (!lid) return Qfalse;
622 GetBindingPtr(bindval, bind);
623 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
624 return RBOOL(get_local_variable_ptr(&env, lid));
628 * call-seq:
629 * binding.receiver -> object
631 * Returns the bound receiver of the binding object.
633 static VALUE
634 bind_receiver(VALUE bindval)
636 const rb_binding_t *bind;
637 GetBindingPtr(bindval, bind);
638 return vm_block_self(&bind->block);
642 * call-seq:
643 * binding.source_location -> [String, Integer]
645 * Returns the Ruby source filename and line number of the binding object.
647 static VALUE
648 bind_location(VALUE bindval)
650 VALUE loc[2];
651 const rb_binding_t *bind;
652 GetBindingPtr(bindval, bind);
653 loc[0] = pathobj_path(bind->pathobj);
654 loc[1] = INT2FIX(bind->first_lineno);
656 return rb_ary_new4(2, loc);
659 static VALUE
660 cfunc_proc_new(VALUE klass, VALUE ifunc)
662 rb_proc_t *proc;
663 cfunc_proc_t *sproc;
664 VALUE procval = TypedData_Make_Struct(klass, cfunc_proc_t, &proc_data_type, sproc);
665 VALUE *ep;
667 proc = &sproc->basic;
668 vm_block_type_set(&proc->block, block_type_ifunc);
670 *(VALUE **)&proc->block.as.captured.ep = ep = sproc->env + VM_ENV_DATA_SIZE-1;
671 ep[VM_ENV_DATA_INDEX_FLAGS] = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL | VM_ENV_FLAG_ESCAPED;
672 ep[VM_ENV_DATA_INDEX_ME_CREF] = Qfalse;
673 ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
674 ep[VM_ENV_DATA_INDEX_ENV] = Qundef; /* envval */
676 /* self? */
677 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.ifunc, ifunc);
678 proc->is_lambda = TRUE;
679 return procval;
682 static VALUE
683 sym_proc_new(VALUE klass, VALUE sym)
685 VALUE procval = rb_proc_alloc(klass);
686 rb_proc_t *proc;
687 GetProcPtr(procval, proc);
689 vm_block_type_set(&proc->block, block_type_symbol);
690 proc->is_lambda = TRUE;
691 RB_OBJ_WRITE(procval, &proc->block.as.symbol, sym);
692 return procval;
695 struct vm_ifunc *
696 rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc)
698 union {
699 struct vm_ifunc_argc argc;
700 VALUE packed;
701 } arity;
703 if (min_argc < UNLIMITED_ARGUMENTS ||
704 #if SIZEOF_INT * 2 > SIZEOF_VALUE
705 min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
706 #endif
707 0) {
708 rb_raise(rb_eRangeError, "minimum argument number out of range: %d",
709 min_argc);
711 if (max_argc < UNLIMITED_ARGUMENTS ||
712 #if SIZEOF_INT * 2 > SIZEOF_VALUE
713 max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
714 #endif
715 0) {
716 rb_raise(rb_eRangeError, "maximum argument number out of range: %d",
717 max_argc);
719 arity.argc.min = min_argc;
720 arity.argc.max = max_argc;
721 rb_execution_context_t *ec = GET_EC();
723 struct vm_ifunc *ifunc = IMEMO_NEW(struct vm_ifunc, imemo_ifunc, (VALUE)rb_vm_svar_lep(ec, ec->cfp));
724 ifunc->func = func;
725 ifunc->data = data;
726 ifunc->argc = arity.argc;
728 return ifunc;
731 VALUE
732 rb_func_proc_new(rb_block_call_func_t func, VALUE val)
734 struct vm_ifunc *ifunc = rb_vm_ifunc_proc_new(func, (void *)val);
735 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
738 VALUE
739 rb_func_lambda_new(rb_block_call_func_t func, VALUE val, int min_argc, int max_argc)
741 struct vm_ifunc *ifunc = rb_vm_ifunc_new(func, (void *)val, min_argc, max_argc);
742 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
745 static const char proc_without_block[] = "tried to create Proc object without a block";
747 static VALUE
748 proc_new(VALUE klass, int8_t is_lambda)
750 VALUE procval;
751 const rb_execution_context_t *ec = GET_EC();
752 rb_control_frame_t *cfp = ec->cfp;
753 VALUE block_handler;
755 if ((block_handler = rb_vm_frame_block_handler(cfp)) == VM_BLOCK_HANDLER_NONE) {
756 rb_raise(rb_eArgError, proc_without_block);
759 /* block is in cf */
760 switch (vm_block_handler_type(block_handler)) {
761 case block_handler_type_proc:
762 procval = VM_BH_TO_PROC(block_handler);
764 if (RBASIC_CLASS(procval) == klass) {
765 return procval;
767 else {
768 VALUE newprocval = rb_proc_dup(procval);
769 RBASIC_SET_CLASS(newprocval, klass);
770 return newprocval;
772 break;
774 case block_handler_type_symbol:
775 return (klass != rb_cProc) ?
776 sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) :
777 rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
778 break;
780 case block_handler_type_ifunc:
781 case block_handler_type_iseq:
782 return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda);
784 VM_UNREACHABLE(proc_new);
785 return Qnil;
789 * call-seq:
790 * Proc.new {|...| block } -> a_proc
792 * Creates a new Proc object, bound to the current context.
794 * proc = Proc.new { "hello" }
795 * proc.call #=> "hello"
797 * Raises ArgumentError if called without a block.
799 * Proc.new #=> ArgumentError
802 static VALUE
803 rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
805 VALUE block = proc_new(klass, FALSE);
807 rb_obj_call_init_kw(block, argc, argv, RB_PASS_CALLED_KEYWORDS);
808 return block;
811 VALUE
812 rb_block_proc(void)
814 return proc_new(rb_cProc, FALSE);
818 * call-seq:
819 * proc { |...| block } -> a_proc
821 * Equivalent to Proc.new.
824 static VALUE
825 f_proc(VALUE _)
827 return proc_new(rb_cProc, FALSE);
830 VALUE
831 rb_block_lambda(void)
833 return proc_new(rb_cProc, TRUE);
836 static void
837 f_lambda_filter_non_literal(void)
839 rb_control_frame_t *cfp = GET_EC()->cfp;
840 VALUE block_handler = rb_vm_frame_block_handler(cfp);
842 if (block_handler == VM_BLOCK_HANDLER_NONE) {
843 // no block erorr raised else where
844 return;
847 switch (vm_block_handler_type(block_handler)) {
848 case block_handler_type_iseq:
849 if (RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)->ep == VM_BH_TO_ISEQ_BLOCK(block_handler)->ep) {
850 return;
852 break;
853 case block_handler_type_symbol:
854 return;
855 case block_handler_type_proc:
856 if (rb_proc_lambda_p(VM_BH_TO_PROC(block_handler))) {
857 return;
859 break;
860 case block_handler_type_ifunc:
861 break;
864 rb_raise(rb_eArgError, "the lambda method requires a literal block");
868 * call-seq:
869 * lambda { |...| block } -> a_proc
871 * Equivalent to Proc.new, except the resulting Proc objects check the
872 * number of parameters passed when called.
875 static VALUE
876 f_lambda(VALUE _)
878 f_lambda_filter_non_literal();
879 return rb_block_lambda();
882 /* Document-method: Proc#===
884 * call-seq:
885 * proc === obj -> result_of_proc
887 * Invokes the block with +obj+ as the proc's parameter like Proc#call.
888 * This allows a proc object to be the target of a +when+ clause
889 * in a case statement.
892 /* CHECKME: are the argument checking semantics correct? */
895 * Document-method: Proc#[]
896 * Document-method: Proc#call
897 * Document-method: Proc#yield
899 * call-seq:
900 * prc.call(params,...) -> obj
901 * prc[params,...] -> obj
902 * prc.(params,...) -> obj
903 * prc.yield(params,...) -> obj
905 * Invokes the block, setting the block's parameters to the values in
906 * <i>params</i> using something close to method calling semantics.
907 * Returns the value of the last expression evaluated in the block.
909 * a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
910 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
911 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
912 * a_proc.(9, 1, 2, 3) #=> [9, 18, 27]
913 * a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
915 * Note that <code>prc.()</code> invokes <code>prc.call()</code> with
916 * the parameters given. It's syntactic sugar to hide "call".
918 * For procs created using #lambda or <code>->()</code> an error is
919 * generated if the wrong number of parameters are passed to the
920 * proc. For procs created using Proc.new or Kernel.proc, extra
921 * parameters are silently discarded and missing parameters are set
922 * to +nil+.
924 * a_proc = proc {|a,b| [a,b] }
925 * a_proc.call(1) #=> [1, nil]
927 * a_proc = lambda {|a,b| [a,b] }
928 * a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
930 * See also Proc#lambda?.
932 #if 0
933 static VALUE
934 proc_call(int argc, VALUE *argv, VALUE procval)
936 /* removed */
938 #endif
940 #if SIZEOF_LONG > SIZEOF_INT
941 static inline int
942 check_argc(long argc)
944 if (argc > INT_MAX || argc < 0) {
945 rb_raise(rb_eArgError, "too many arguments (%lu)",
946 (unsigned long)argc);
948 return (int)argc;
950 #else
951 #define check_argc(argc) (argc)
952 #endif
954 VALUE
955 rb_proc_call_kw(VALUE self, VALUE args, int kw_splat)
957 VALUE vret;
958 rb_proc_t *proc;
959 int argc = check_argc(RARRAY_LEN(args));
960 const VALUE *argv = RARRAY_CONST_PTR(args);
961 GetProcPtr(self, proc);
962 vret = rb_vm_invoke_proc(GET_EC(), proc, argc, argv,
963 kw_splat, VM_BLOCK_HANDLER_NONE);
964 RB_GC_GUARD(self);
965 RB_GC_GUARD(args);
966 return vret;
969 VALUE
970 rb_proc_call(VALUE self, VALUE args)
972 return rb_proc_call_kw(self, args, RB_NO_KEYWORDS);
975 static VALUE
976 proc_to_block_handler(VALUE procval)
978 return NIL_P(procval) ? VM_BLOCK_HANDLER_NONE : procval;
981 VALUE
982 rb_proc_call_with_block_kw(VALUE self, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
984 rb_execution_context_t *ec = GET_EC();
985 VALUE vret;
986 rb_proc_t *proc;
987 GetProcPtr(self, proc);
988 vret = rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, proc_to_block_handler(passed_procval));
989 RB_GC_GUARD(self);
990 return vret;
993 VALUE
994 rb_proc_call_with_block(VALUE self, int argc, const VALUE *argv, VALUE passed_procval)
996 return rb_proc_call_with_block_kw(self, argc, argv, passed_procval, RB_NO_KEYWORDS);
1001 * call-seq:
1002 * prc.arity -> integer
1004 * Returns the number of mandatory arguments. If the block
1005 * is declared to take no arguments, returns 0. If the block is known
1006 * to take exactly n arguments, returns n.
1007 * If the block has optional arguments, returns -n-1, where n is the
1008 * number of mandatory arguments, with the exception for blocks that
1009 * are not lambdas and have only a finite number of optional arguments;
1010 * in this latter case, returns n.
1011 * Keyword arguments will be considered as a single additional argument,
1012 * that argument being mandatory if any keyword argument is mandatory.
1013 * A #proc with no argument declarations is the same as a block
1014 * declaring <code>||</code> as its arguments.
1016 * proc {}.arity #=> 0
1017 * proc { || }.arity #=> 0
1018 * proc { |a| }.arity #=> 1
1019 * proc { |a, b| }.arity #=> 2
1020 * proc { |a, b, c| }.arity #=> 3
1021 * proc { |*a| }.arity #=> -1
1022 * proc { |a, *b| }.arity #=> -2
1023 * proc { |a, *b, c| }.arity #=> -3
1024 * proc { |x:, y:, z:0| }.arity #=> 1
1025 * proc { |*a, x:, y:0| }.arity #=> -2
1027 * proc { |a=0| }.arity #=> 0
1028 * lambda { |a=0| }.arity #=> -1
1029 * proc { |a=0, b| }.arity #=> 1
1030 * lambda { |a=0, b| }.arity #=> -2
1031 * proc { |a=0, b=0| }.arity #=> 0
1032 * lambda { |a=0, b=0| }.arity #=> -1
1033 * proc { |a, b=0| }.arity #=> 1
1034 * lambda { |a, b=0| }.arity #=> -2
1035 * proc { |(a, b), c=0| }.arity #=> 1
1036 * lambda { |(a, b), c=0| }.arity #=> -2
1037 * proc { |a, x:0, y:0| }.arity #=> 1
1038 * lambda { |a, x:0, y:0| }.arity #=> -2
1041 static VALUE
1042 proc_arity(VALUE self)
1044 int arity = rb_proc_arity(self);
1045 return INT2FIX(arity);
1048 static inline int
1049 rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
1051 *max = ISEQ_BODY(iseq)->param.flags.has_rest == FALSE ?
1052 ISEQ_BODY(iseq)->param.lead_num + ISEQ_BODY(iseq)->param.opt_num + ISEQ_BODY(iseq)->param.post_num +
1053 (ISEQ_BODY(iseq)->param.flags.has_kw == TRUE || ISEQ_BODY(iseq)->param.flags.has_kwrest == TRUE)
1054 : UNLIMITED_ARGUMENTS;
1055 return ISEQ_BODY(iseq)->param.lead_num + ISEQ_BODY(iseq)->param.post_num + (ISEQ_BODY(iseq)->param.flags.has_kw && ISEQ_BODY(iseq)->param.keyword->required_num > 0);
1058 static int
1059 rb_vm_block_min_max_arity(const struct rb_block *block, int *max)
1061 again:
1062 switch (vm_block_type(block)) {
1063 case block_type_iseq:
1064 return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max);
1065 case block_type_proc:
1066 block = vm_proc_block(block->as.proc);
1067 goto again;
1068 case block_type_ifunc:
1070 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1071 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1072 /* e.g. method(:foo).to_proc.arity */
1073 return method_min_max_arity((VALUE)ifunc->data, max);
1075 *max = ifunc->argc.max;
1076 return ifunc->argc.min;
1078 case block_type_symbol:
1079 *max = UNLIMITED_ARGUMENTS;
1080 return 1;
1082 *max = UNLIMITED_ARGUMENTS;
1083 return 0;
1087 * Returns the number of required parameters and stores the maximum
1088 * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
1089 * For non-lambda procs, the maximum is the number of non-ignored
1090 * parameters even though there is no actual limit to the number of parameters
1092 static int
1093 rb_proc_min_max_arity(VALUE self, int *max)
1095 rb_proc_t *proc;
1096 GetProcPtr(self, proc);
1097 return rb_vm_block_min_max_arity(&proc->block, max);
1101 rb_proc_arity(VALUE self)
1103 rb_proc_t *proc;
1104 int max, min;
1105 GetProcPtr(self, proc);
1106 min = rb_vm_block_min_max_arity(&proc->block, &max);
1107 return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1110 static void
1111 block_setup(struct rb_block *block, VALUE block_handler)
1113 switch (vm_block_handler_type(block_handler)) {
1114 case block_handler_type_iseq:
1115 block->type = block_type_iseq;
1116 block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler);
1117 break;
1118 case block_handler_type_ifunc:
1119 block->type = block_type_ifunc;
1120 block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler);
1121 break;
1122 case block_handler_type_symbol:
1123 block->type = block_type_symbol;
1124 block->as.symbol = VM_BH_TO_SYMBOL(block_handler);
1125 break;
1126 case block_handler_type_proc:
1127 block->type = block_type_proc;
1128 block->as.proc = VM_BH_TO_PROC(block_handler);
1133 rb_block_pair_yield_optimizable(void)
1135 int min, max;
1136 const rb_execution_context_t *ec = GET_EC();
1137 rb_control_frame_t *cfp = ec->cfp;
1138 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1139 struct rb_block block;
1141 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1142 rb_raise(rb_eArgError, "no block given");
1145 block_setup(&block, block_handler);
1146 min = rb_vm_block_min_max_arity(&block, &max);
1148 switch (vm_block_type(&block)) {
1149 case block_handler_type_symbol:
1150 return 0;
1152 case block_handler_type_proc:
1154 VALUE procval = block_handler;
1155 rb_proc_t *proc;
1156 GetProcPtr(procval, proc);
1157 if (proc->is_lambda) return 0;
1158 if (min != max) return 0;
1159 return min > 1;
1162 default:
1163 return min > 1;
1168 rb_block_arity(void)
1170 int min, max;
1171 const rb_execution_context_t *ec = GET_EC();
1172 rb_control_frame_t *cfp = ec->cfp;
1173 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1174 struct rb_block block;
1176 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1177 rb_raise(rb_eArgError, "no block given");
1180 block_setup(&block, block_handler);
1182 switch (vm_block_type(&block)) {
1183 case block_handler_type_symbol:
1184 return -1;
1186 case block_handler_type_proc:
1187 return rb_proc_arity(block_handler);
1189 default:
1190 min = rb_vm_block_min_max_arity(&block, &max);
1191 return max != UNLIMITED_ARGUMENTS ? min : -min-1;
1196 rb_block_min_max_arity(int *max)
1198 const rb_execution_context_t *ec = GET_EC();
1199 rb_control_frame_t *cfp = ec->cfp;
1200 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1201 struct rb_block block;
1203 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1204 rb_raise(rb_eArgError, "no block given");
1207 block_setup(&block, block_handler);
1208 return rb_vm_block_min_max_arity(&block, max);
1211 const rb_iseq_t *
1212 rb_proc_get_iseq(VALUE self, int *is_proc)
1214 const rb_proc_t *proc;
1215 const struct rb_block *block;
1217 GetProcPtr(self, proc);
1218 block = &proc->block;
1219 if (is_proc) *is_proc = !proc->is_lambda;
1221 switch (vm_block_type(block)) {
1222 case block_type_iseq:
1223 return rb_iseq_check(block->as.captured.code.iseq);
1224 case block_type_proc:
1225 return rb_proc_get_iseq(block->as.proc, is_proc);
1226 case block_type_ifunc:
1228 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1229 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1230 /* method(:foo).to_proc */
1231 if (is_proc) *is_proc = 0;
1232 return rb_method_iseq((VALUE)ifunc->data);
1234 else {
1235 return NULL;
1238 case block_type_symbol:
1239 return NULL;
1242 VM_UNREACHABLE(rb_proc_get_iseq);
1243 return NULL;
1246 /* call-seq:
1247 * prc == other -> true or false
1248 * prc.eql?(other) -> true or false
1250 * Two procs are the same if, and only if, they were created from the same code block.
1252 * def return_block(&block)
1253 * block
1254 * end
1256 * def pass_block_twice(&block)
1257 * [return_block(&block), return_block(&block)]
1258 * end
1260 * block1, block2 = pass_block_twice { puts 'test' }
1261 * # Blocks might be instantiated into Proc's lazily, so they may, or may not,
1262 * # be the same object.
1263 * # But they are produced from the same code block, so they are equal
1264 * block1 == block2
1265 * #=> true
1267 * # Another Proc will never be equal, even if the code is the "same"
1268 * block1 == proc { puts 'test' }
1269 * #=> false
1272 static VALUE
1273 proc_eq(VALUE self, VALUE other)
1275 const rb_proc_t *self_proc, *other_proc;
1276 const struct rb_block *self_block, *other_block;
1278 if (rb_obj_class(self) != rb_obj_class(other)) {
1279 return Qfalse;
1282 GetProcPtr(self, self_proc);
1283 GetProcPtr(other, other_proc);
1285 if (self_proc->is_from_method != other_proc->is_from_method ||
1286 self_proc->is_lambda != other_proc->is_lambda) {
1287 return Qfalse;
1290 self_block = &self_proc->block;
1291 other_block = &other_proc->block;
1293 if (vm_block_type(self_block) != vm_block_type(other_block)) {
1294 return Qfalse;
1297 switch (vm_block_type(self_block)) {
1298 case block_type_iseq:
1299 if (self_block->as.captured.ep != \
1300 other_block->as.captured.ep ||
1301 self_block->as.captured.code.iseq != \
1302 other_block->as.captured.code.iseq) {
1303 return Qfalse;
1305 break;
1306 case block_type_ifunc:
1307 if (self_block->as.captured.ep != \
1308 other_block->as.captured.ep ||
1309 self_block->as.captured.code.ifunc != \
1310 other_block->as.captured.code.ifunc) {
1311 return Qfalse;
1313 break;
1314 case block_type_proc:
1315 if (self_block->as.proc != other_block->as.proc) {
1316 return Qfalse;
1318 break;
1319 case block_type_symbol:
1320 if (self_block->as.symbol != other_block->as.symbol) {
1321 return Qfalse;
1323 break;
1326 return Qtrue;
1329 static VALUE
1330 iseq_location(const rb_iseq_t *iseq)
1332 VALUE loc[2];
1334 if (!iseq) return Qnil;
1335 rb_iseq_check(iseq);
1336 loc[0] = rb_iseq_path(iseq);
1337 loc[1] = RB_INT2NUM(ISEQ_BODY(iseq)->location.first_lineno);
1339 return rb_ary_new4(2, loc);
1342 VALUE
1343 rb_iseq_location(const rb_iseq_t *iseq)
1345 return iseq_location(iseq);
1349 * call-seq:
1350 * prc.source_location -> [String, Integer]
1352 * Returns the Ruby source filename and line number containing this proc
1353 * or +nil+ if this proc was not defined in Ruby (i.e. native).
1356 VALUE
1357 rb_proc_location(VALUE self)
1359 return iseq_location(rb_proc_get_iseq(self, 0));
1362 VALUE
1363 rb_unnamed_parameters(int arity)
1365 VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
1366 int n = (arity < 0) ? ~arity : arity;
1367 ID req, rest;
1368 CONST_ID(req, "req");
1369 a = rb_ary_new3(1, ID2SYM(req));
1370 OBJ_FREEZE(a);
1371 for (; n; --n) {
1372 rb_ary_push(param, a);
1374 if (arity < 0) {
1375 CONST_ID(rest, "rest");
1376 rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
1378 return param;
1382 * call-seq:
1383 * prc.parameters(lambda: nil) -> array
1385 * Returns the parameter information of this proc. If the lambda
1386 * keyword is provided and not nil, treats the proc as a lambda if
1387 * true and as a non-lambda if false.
1389 * prc = proc{|x, y=42, *other|}
1390 * prc.parameters #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
1391 * prc = lambda{|x, y=42, *other|}
1392 * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1393 * prc = proc{|x, y=42, *other|}
1394 * prc.parameters(lambda: true) #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1395 * prc = lambda{|x, y=42, *other|}
1396 * prc.parameters(lambda: false) #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
1399 static VALUE
1400 rb_proc_parameters(int argc, VALUE *argv, VALUE self)
1402 static ID keyword_ids[1];
1403 VALUE opt, lambda;
1404 VALUE kwargs[1];
1405 int is_proc ;
1406 const rb_iseq_t *iseq;
1408 iseq = rb_proc_get_iseq(self, &is_proc);
1410 if (!keyword_ids[0]) {
1411 CONST_ID(keyword_ids[0], "lambda");
1414 rb_scan_args(argc, argv, "0:", &opt);
1415 if (!NIL_P(opt)) {
1416 rb_get_kwargs(opt, keyword_ids, 0, 1, kwargs);
1417 lambda = kwargs[0];
1418 if (!NIL_P(lambda)) {
1419 is_proc = !RTEST(lambda);
1423 if (!iseq) {
1424 return rb_unnamed_parameters(rb_proc_arity(self));
1426 return rb_iseq_parameters(iseq, is_proc);
1429 st_index_t
1430 rb_hash_proc(st_index_t hash, VALUE prc)
1432 rb_proc_t *proc;
1433 GetProcPtr(prc, proc);
1434 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.code.val);
1435 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.self);
1436 return rb_hash_uint(hash, (st_index_t)proc->block.as.captured.ep);
1441 * call-seq:
1442 * to_proc
1444 * Returns a Proc object which calls the method with name of +self+
1445 * on the first parameter and passes the remaining parameters to the method.
1447 * proc = :to_s.to_proc # => #<Proc:0x000001afe0e48680(&:to_s) (lambda)>
1448 * proc.call(1000) # => "1000"
1449 * proc.call(1000, 16) # => "3e8"
1450 * (1..3).collect(&:to_s) # => ["1", "2", "3"]
1454 VALUE
1455 rb_sym_to_proc(VALUE sym)
1457 static VALUE sym_proc_cache = Qfalse;
1458 enum {SYM_PROC_CACHE_SIZE = 67};
1459 VALUE proc;
1460 long index;
1461 ID id;
1463 if (!sym_proc_cache) {
1464 sym_proc_cache = rb_ary_hidden_new(SYM_PROC_CACHE_SIZE * 2);
1465 rb_vm_register_global_object(sym_proc_cache);
1466 rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil);
1469 id = SYM2ID(sym);
1470 index = (id % SYM_PROC_CACHE_SIZE) << 1;
1472 if (RARRAY_AREF(sym_proc_cache, index) == sym) {
1473 return RARRAY_AREF(sym_proc_cache, index + 1);
1475 else {
1476 proc = sym_proc_new(rb_cProc, ID2SYM(id));
1477 RARRAY_ASET(sym_proc_cache, index, sym);
1478 RARRAY_ASET(sym_proc_cache, index + 1, proc);
1479 return proc;
1484 * call-seq:
1485 * prc.hash -> integer
1487 * Returns a hash value corresponding to proc body.
1489 * See also Object#hash.
1492 static VALUE
1493 proc_hash(VALUE self)
1495 st_index_t hash;
1496 hash = rb_hash_start(0);
1497 hash = rb_hash_proc(hash, self);
1498 hash = rb_hash_end(hash);
1499 return ST2FIX(hash);
1502 VALUE
1503 rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
1505 VALUE cname = rb_obj_class(self);
1506 VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
1508 again:
1509 switch (vm_block_type(block)) {
1510 case block_type_proc:
1511 block = vm_proc_block(block->as.proc);
1512 goto again;
1513 case block_type_iseq:
1515 const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
1516 rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
1517 rb_iseq_path(iseq),
1518 ISEQ_BODY(iseq)->location.first_lineno);
1520 break;
1521 case block_type_symbol:
1522 rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
1523 break;
1524 case block_type_ifunc:
1525 rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
1526 break;
1529 if (additional_info) rb_str_cat_cstr(str, additional_info);
1530 rb_str_cat_cstr(str, ">");
1531 return str;
1535 * call-seq:
1536 * prc.to_s -> string
1538 * Returns the unique identifier for this proc, along with
1539 * an indication of where the proc was defined.
1542 static VALUE
1543 proc_to_s(VALUE self)
1545 const rb_proc_t *proc;
1546 GetProcPtr(self, proc);
1547 return rb_block_to_s(self, &proc->block, proc->is_lambda ? " (lambda)" : NULL);
1551 * call-seq:
1552 * prc.to_proc -> proc
1554 * Part of the protocol for converting objects to Proc objects.
1555 * Instances of class Proc simply return themselves.
1558 static VALUE
1559 proc_to_proc(VALUE self)
1561 return self;
1564 static void
1565 bm_mark_and_move(void *ptr)
1567 struct METHOD *data = ptr;
1568 rb_gc_mark_and_move((VALUE *)&data->recv);
1569 rb_gc_mark_and_move((VALUE *)&data->klass);
1570 rb_gc_mark_and_move((VALUE *)&data->iclass);
1571 rb_gc_mark_and_move((VALUE *)&data->owner);
1572 rb_gc_mark_and_move_ptr((rb_method_entry_t **)&data->me);
1575 static const rb_data_type_t method_data_type = {
1576 "method",
1578 bm_mark_and_move,
1579 RUBY_TYPED_DEFAULT_FREE,
1580 NULL, // No external memory to report,
1581 bm_mark_and_move,
1583 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1586 VALUE
1587 rb_obj_is_method(VALUE m)
1589 return RBOOL(rb_typeddata_is_kind_of(m, &method_data_type));
1592 static int
1593 respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
1595 /* TODO: merge with obj_respond_to() */
1596 ID rmiss = idRespond_to_missing;
1598 if (UNDEF_P(obj)) return 0;
1599 if (rb_method_basic_definition_p(klass, rmiss)) return 0;
1600 return RTEST(rb_funcall(obj, rmiss, 2, sym, RBOOL(!scope)));
1604 static VALUE
1605 mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
1607 struct METHOD *data;
1608 VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1609 rb_method_entry_t *me;
1610 rb_method_definition_t *def;
1612 RB_OBJ_WRITE(method, &data->recv, obj);
1613 RB_OBJ_WRITE(method, &data->klass, klass);
1614 RB_OBJ_WRITE(method, &data->owner, klass);
1616 def = ZALLOC(rb_method_definition_t);
1617 def->type = VM_METHOD_TYPE_MISSING;
1618 def->original_id = id;
1620 me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
1622 RB_OBJ_WRITE(method, &data->me, me);
1624 return method;
1627 static VALUE
1628 mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
1630 VALUE vid = rb_str_intern(*name);
1631 *name = vid;
1632 if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
1633 return mnew_missing(klass, obj, SYM2ID(vid), mclass);
1636 static VALUE
1637 mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1638 VALUE obj, ID id, VALUE mclass, int scope, int error)
1640 struct METHOD *data;
1641 VALUE method;
1642 const rb_method_entry_t *original_me = me;
1643 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
1645 again:
1646 if (UNDEFINED_METHOD_ENTRY_P(me)) {
1647 if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
1648 return mnew_missing(klass, obj, id, mclass);
1650 if (!error) return Qnil;
1651 rb_print_undef(klass, id, METHOD_VISI_UNDEF);
1653 if (visi == METHOD_VISI_UNDEF) {
1654 visi = METHOD_ENTRY_VISI(me);
1655 RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */
1656 if (scope && (visi != METHOD_VISI_PUBLIC)) {
1657 if (!error) return Qnil;
1658 rb_print_inaccessible(klass, id, visi);
1661 if (me->def->type == VM_METHOD_TYPE_ZSUPER) {
1662 if (me->defined_class) {
1663 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
1664 id = me->def->original_id;
1665 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1667 else {
1668 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner));
1669 id = me->def->original_id;
1670 me = rb_method_entry_without_refinements(klass, id, &iclass);
1672 goto again;
1675 method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1677 if (UNDEF_P(obj)) {
1678 RB_OBJ_WRITE(method, &data->recv, Qundef);
1679 RB_OBJ_WRITE(method, &data->klass, Qundef);
1681 else {
1682 RB_OBJ_WRITE(method, &data->recv, obj);
1683 RB_OBJ_WRITE(method, &data->klass, klass);
1685 RB_OBJ_WRITE(method, &data->iclass, iclass);
1686 RB_OBJ_WRITE(method, &data->owner, original_me->owner);
1687 RB_OBJ_WRITE(method, &data->me, me);
1689 return method;
1692 static VALUE
1693 mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1694 VALUE obj, ID id, VALUE mclass, int scope)
1696 return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
1699 static VALUE
1700 mnew_callable(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
1702 const rb_method_entry_t *me;
1703 VALUE iclass = Qnil;
1705 ASSUME(!UNDEF_P(obj));
1706 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1707 return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
1710 static VALUE
1711 mnew_unbound(VALUE klass, ID id, VALUE mclass, int scope)
1713 const rb_method_entry_t *me;
1714 VALUE iclass = Qnil;
1716 me = rb_method_entry_with_refinements(klass, id, &iclass);
1717 return mnew_from_me(me, klass, iclass, Qundef, id, mclass, scope);
1720 static inline VALUE
1721 method_entry_defined_class(const rb_method_entry_t *me)
1723 VALUE defined_class = me->defined_class;
1724 return defined_class ? defined_class : me->owner;
1727 /**********************************************************************
1729 * Document-class: Method
1731 * Method objects are created by Object#method, and are associated
1732 * with a particular object (not just with a class). They may be
1733 * used to invoke the method within the object, and as a block
1734 * associated with an iterator. They may also be unbound from one
1735 * object (creating an UnboundMethod) and bound to another.
1737 * class Thing
1738 * def square(n)
1739 * n*n
1740 * end
1741 * end
1742 * thing = Thing.new
1743 * meth = thing.method(:square)
1745 * meth.call(9) #=> 81
1746 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1748 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
1750 * require 'date'
1751 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1752 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1756 * call-seq:
1757 * meth.eql?(other_meth) -> true or false
1758 * meth == other_meth -> true or false
1760 * Two method objects are equal if they are bound to the same
1761 * object and refer to the same method definition and the classes
1762 * defining the methods are the same class or module.
1765 static VALUE
1766 method_eq(VALUE method, VALUE other)
1768 struct METHOD *m1, *m2;
1769 VALUE klass1, klass2;
1771 if (!rb_obj_is_method(other))
1772 return Qfalse;
1773 if (CLASS_OF(method) != CLASS_OF(other))
1774 return Qfalse;
1776 Check_TypedStruct(method, &method_data_type);
1777 m1 = (struct METHOD *)RTYPEDDATA_GET_DATA(method);
1778 m2 = (struct METHOD *)RTYPEDDATA_GET_DATA(other);
1780 klass1 = method_entry_defined_class(m1->me);
1781 klass2 = method_entry_defined_class(m2->me);
1783 if (!rb_method_entry_eq(m1->me, m2->me) ||
1784 klass1 != klass2 ||
1785 m1->klass != m2->klass ||
1786 m1->recv != m2->recv) {
1787 return Qfalse;
1790 return Qtrue;
1794 * call-seq:
1795 * meth.eql?(other_meth) -> true or false
1796 * meth == other_meth -> true or false
1798 * Two unbound method objects are equal if they refer to the same
1799 * method definition.
1801 * Array.instance_method(:each_slice) == Enumerable.instance_method(:each_slice)
1802 * #=> true
1804 * Array.instance_method(:sum) == Enumerable.instance_method(:sum)
1805 * #=> false, Array redefines the method for efficiency
1807 #define unbound_method_eq method_eq
1810 * call-seq:
1811 * meth.hash -> integer
1813 * Returns a hash value corresponding to the method object.
1815 * See also Object#hash.
1818 static VALUE
1819 method_hash(VALUE method)
1821 struct METHOD *m;
1822 st_index_t hash;
1824 TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
1825 hash = rb_hash_start((st_index_t)m->recv);
1826 hash = rb_hash_method_entry(hash, m->me);
1827 hash = rb_hash_end(hash);
1829 return ST2FIX(hash);
1833 * call-seq:
1834 * meth.unbind -> unbound_method
1836 * Dissociates <i>meth</i> from its current receiver. The resulting
1837 * UnboundMethod can subsequently be bound to a new object of the
1838 * same class (see UnboundMethod).
1841 static VALUE
1842 method_unbind(VALUE obj)
1844 VALUE method;
1845 struct METHOD *orig, *data;
1847 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
1848 method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
1849 &method_data_type, data);
1850 RB_OBJ_WRITE(method, &data->recv, Qundef);
1851 RB_OBJ_WRITE(method, &data->klass, Qundef);
1852 RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
1853 RB_OBJ_WRITE(method, &data->owner, orig->me->owner);
1854 RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
1856 return method;
1860 * call-seq:
1861 * meth.receiver -> object
1863 * Returns the bound receiver of the method object.
1865 * (1..3).method(:map).receiver # => 1..3
1868 static VALUE
1869 method_receiver(VALUE obj)
1871 struct METHOD *data;
1873 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1874 return data->recv;
1878 * call-seq:
1879 * meth.name -> symbol
1881 * Returns the name of the method.
1884 static VALUE
1885 method_name(VALUE obj)
1887 struct METHOD *data;
1889 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1890 return ID2SYM(data->me->called_id);
1894 * call-seq:
1895 * meth.original_name -> symbol
1897 * Returns the original name of the method.
1899 * class C
1900 * def foo; end
1901 * alias bar foo
1902 * end
1903 * C.instance_method(:bar).original_name # => :foo
1906 static VALUE
1907 method_original_name(VALUE obj)
1909 struct METHOD *data;
1911 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1912 return ID2SYM(data->me->def->original_id);
1916 * call-seq:
1917 * meth.owner -> class_or_module
1919 * Returns the class or module on which this method is defined.
1920 * In other words,
1922 * meth.owner.instance_methods(false).include?(meth.name) # => true
1924 * holds as long as the method is not removed/undefined/replaced,
1925 * (with private_instance_methods instead of instance_methods if the method
1926 * is private).
1928 * See also Method#receiver.
1930 * (1..3).method(:map).owner #=> Enumerable
1933 static VALUE
1934 method_owner(VALUE obj)
1936 struct METHOD *data;
1937 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1938 return data->owner;
1941 void
1942 rb_method_name_error(VALUE klass, VALUE str)
1944 #define MSG(s) rb_fstring_lit("undefined method '%1$s' for"s" '%2$s'")
1945 VALUE c = klass;
1946 VALUE s = Qundef;
1948 if (RCLASS_SINGLETON_P(c)) {
1949 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
1951 switch (BUILTIN_TYPE(obj)) {
1952 case T_MODULE:
1953 case T_CLASS:
1954 c = obj;
1955 break;
1956 default:
1957 break;
1960 else if (RB_TYPE_P(c, T_MODULE)) {
1961 s = MSG(" module");
1963 if (UNDEF_P(s)) {
1964 s = MSG(" class");
1966 rb_name_err_raise_str(s, c, str);
1967 #undef MSG
1970 static VALUE
1971 obj_method(VALUE obj, VALUE vid, int scope)
1973 ID id = rb_check_id(&vid);
1974 const VALUE klass = CLASS_OF(obj);
1975 const VALUE mclass = rb_cMethod;
1977 if (!id) {
1978 VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
1979 if (m) return m;
1980 rb_method_name_error(klass, vid);
1982 return mnew_callable(klass, obj, id, mclass, scope);
1986 * call-seq:
1987 * obj.method(sym) -> method
1989 * Looks up the named method as a receiver in <i>obj</i>, returning a
1990 * Method object (or raising NameError). The Method object acts as a
1991 * closure in <i>obj</i>'s object instance, so instance variables and
1992 * the value of <code>self</code> remain available.
1994 * class Demo
1995 * def initialize(n)
1996 * @iv = n
1997 * end
1998 * def hello()
1999 * "Hello, @iv = #{@iv}"
2000 * end
2001 * end
2003 * k = Demo.new(99)
2004 * m = k.method(:hello)
2005 * m.call #=> "Hello, @iv = 99"
2007 * l = Demo.new('Fred')
2008 * m = l.method("hello")
2009 * m.call #=> "Hello, @iv = Fred"
2011 * Note that Method implements <code>to_proc</code> method, which
2012 * means it can be used with iterators.
2014 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
2016 * out = File.open('test.txt', 'w')
2017 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
2019 * require 'date'
2020 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
2021 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2024 VALUE
2025 rb_obj_method(VALUE obj, VALUE vid)
2027 return obj_method(obj, vid, FALSE);
2031 * call-seq:
2032 * obj.public_method(sym) -> method
2034 * Similar to _method_, searches public method only.
2037 VALUE
2038 rb_obj_public_method(VALUE obj, VALUE vid)
2040 return obj_method(obj, vid, TRUE);
2044 * call-seq:
2045 * obj.singleton_method(sym) -> method
2047 * Similar to _method_, searches singleton method only.
2049 * class Demo
2050 * def initialize(n)
2051 * @iv = n
2052 * end
2053 * def hello()
2054 * "Hello, @iv = #{@iv}"
2055 * end
2056 * end
2058 * k = Demo.new(99)
2059 * def k.hi
2060 * "Hi, @iv = #{@iv}"
2061 * end
2062 * m = k.singleton_method(:hi)
2063 * m.call #=> "Hi, @iv = 99"
2064 * m = k.singleton_method(:hello) #=> NameError
2067 VALUE
2068 rb_obj_singleton_method(VALUE obj, VALUE vid)
2070 VALUE klass = rb_singleton_class_get(obj);
2071 ID id = rb_check_id(&vid);
2073 if (NIL_P(klass) ||
2074 NIL_P(klass = RCLASS_ORIGIN(klass)) ||
2075 !NIL_P(rb_special_singleton_class(obj))) {
2076 /* goto undef; */
2078 else if (! id) {
2079 VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
2080 if (m) return m;
2081 /* else goto undef; */
2083 else {
2084 const rb_method_entry_t *me = rb_method_entry_at(klass, id);
2085 vid = ID2SYM(id);
2087 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2088 /* goto undef; */
2090 else if (UNDEFINED_REFINED_METHOD_P(me->def)) {
2091 /* goto undef; */
2093 else {
2094 return mnew_from_me(me, klass, klass, obj, id, rb_cMethod, FALSE);
2098 /* undef: */
2099 rb_name_err_raise("undefined singleton method '%1$s' for '%2$s'",
2100 obj, vid);
2101 UNREACHABLE_RETURN(Qundef);
2105 * call-seq:
2106 * mod.instance_method(symbol) -> unbound_method
2108 * Returns an +UnboundMethod+ representing the given
2109 * instance method in _mod_.
2111 * class Interpreter
2112 * def do_a() print "there, "; end
2113 * def do_d() print "Hello "; end
2114 * def do_e() print "!\n"; end
2115 * def do_v() print "Dave"; end
2116 * Dispatcher = {
2117 * "a" => instance_method(:do_a),
2118 * "d" => instance_method(:do_d),
2119 * "e" => instance_method(:do_e),
2120 * "v" => instance_method(:do_v)
2122 * def interpret(string)
2123 * string.each_char {|b| Dispatcher[b].bind(self).call }
2124 * end
2125 * end
2127 * interpreter = Interpreter.new
2128 * interpreter.interpret('dave')
2130 * <em>produces:</em>
2132 * Hello there, Dave!
2135 static VALUE
2136 rb_mod_instance_method(VALUE mod, VALUE vid)
2138 ID id = rb_check_id(&vid);
2139 if (!id) {
2140 rb_method_name_error(mod, vid);
2142 return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
2146 * call-seq:
2147 * mod.public_instance_method(symbol) -> unbound_method
2149 * Similar to _instance_method_, searches public method only.
2152 static VALUE
2153 rb_mod_public_instance_method(VALUE mod, VALUE vid)
2155 ID id = rb_check_id(&vid);
2156 if (!id) {
2157 rb_method_name_error(mod, vid);
2159 return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
2162 static VALUE
2163 rb_mod_define_method_with_visibility(int argc, VALUE *argv, VALUE mod, const struct rb_scope_visi_struct* scope_visi)
2165 ID id;
2166 VALUE body;
2167 VALUE name;
2168 int is_method = FALSE;
2170 rb_check_arity(argc, 1, 2);
2171 name = argv[0];
2172 id = rb_check_id(&name);
2173 if (argc == 1) {
2174 body = rb_block_lambda();
2176 else {
2177 body = argv[1];
2179 if (rb_obj_is_method(body)) {
2180 is_method = TRUE;
2182 else if (rb_obj_is_proc(body)) {
2183 is_method = FALSE;
2185 else {
2186 rb_raise(rb_eTypeError,
2187 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
2188 rb_obj_classname(body));
2191 if (!id) id = rb_to_id(name);
2193 if (is_method) {
2194 struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(body);
2195 if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
2196 !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
2197 if (RCLASS_SINGLETON_P(method->me->owner)) {
2198 rb_raise(rb_eTypeError,
2199 "can't bind singleton method to a different class");
2201 else {
2202 rb_raise(rb_eTypeError,
2203 "bind argument must be a subclass of % "PRIsVALUE,
2204 method->me->owner);
2207 rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
2208 if (scope_visi->module_func) {
2209 rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
2211 RB_GC_GUARD(body);
2213 else {
2214 VALUE procval = rb_proc_dup(body);
2215 if (vm_proc_iseq(procval) != NULL) {
2216 rb_proc_t *proc;
2217 GetProcPtr(procval, proc);
2218 proc->is_lambda = TRUE;
2219 proc->is_from_method = TRUE;
2221 rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
2222 if (scope_visi->module_func) {
2223 rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
2227 return ID2SYM(id);
2231 * call-seq:
2232 * define_method(symbol, method) -> symbol
2233 * define_method(symbol) { block } -> symbol
2235 * Defines an instance method in the receiver. The _method_
2236 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2237 * If a block is specified, it is used as the method body.
2238 * If a block or the _method_ parameter has parameters,
2239 * they're used as method parameters.
2240 * This block is evaluated using #instance_eval.
2242 * class A
2243 * def fred
2244 * puts "In Fred"
2245 * end
2246 * def create_method(name, &block)
2247 * self.class.define_method(name, &block)
2248 * end
2249 * define_method(:wilma) { puts "Charge it!" }
2250 * define_method(:flint) {|name| puts "I'm #{name}!"}
2251 * end
2252 * class B < A
2253 * define_method(:barney, instance_method(:fred))
2254 * end
2255 * a = B.new
2256 * a.barney
2257 * a.wilma
2258 * a.flint('Dino')
2259 * a.create_method(:betty) { p self }
2260 * a.betty
2262 * <em>produces:</em>
2264 * In Fred
2265 * Charge it!
2266 * I'm Dino!
2267 * #<B:0x401b39e8>
2270 static VALUE
2271 rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
2273 const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
2274 const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2275 const rb_scope_visibility_t *scope_visi = &default_scope_visi;
2277 if (cref) {
2278 scope_visi = CREF_SCOPE_VISI(cref);
2281 return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
2285 * call-seq:
2286 * define_singleton_method(symbol, method) -> symbol
2287 * define_singleton_method(symbol) { block } -> symbol
2289 * Defines a public singleton method in the receiver. The _method_
2290 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2291 * If a block is specified, it is used as the method body.
2292 * If a block or a method has parameters, they're used as method parameters.
2294 * class A
2295 * class << self
2296 * def class_name
2297 * to_s
2298 * end
2299 * end
2300 * end
2301 * A.define_singleton_method(:who_am_i) do
2302 * "I am: #{class_name}"
2303 * end
2304 * A.who_am_i # ==> "I am: A"
2306 * guy = "Bob"
2307 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
2308 * guy.hello #=> "Bob: Hello there!"
2310 * chris = "Chris"
2311 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
2312 * chris.greet("Hi") #=> "Hi, I'm Chris!"
2315 static VALUE
2316 rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
2318 VALUE klass = rb_singleton_class(obj);
2319 const rb_scope_visibility_t scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2321 return rb_mod_define_method_with_visibility(argc, argv, klass, &scope_visi);
2325 * define_method(symbol, method) -> symbol
2326 * define_method(symbol) { block } -> symbol
2328 * Defines a global function by _method_ or the block.
2331 static VALUE
2332 top_define_method(int argc, VALUE *argv, VALUE obj)
2334 return rb_mod_define_method(argc, argv, rb_top_main_class("define_method"));
2338 * call-seq:
2339 * method.clone -> new_method
2341 * Returns a clone of this method.
2343 * class A
2344 * def foo
2345 * return "bar"
2346 * end
2347 * end
2349 * m = A.new.method(:foo)
2350 * m.call # => "bar"
2351 * n = m.clone.call # => "bar"
2354 static VALUE
2355 method_clone(VALUE self)
2357 VALUE clone;
2358 struct METHOD *orig, *data;
2360 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2361 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2362 rb_obj_clone_setup(self, clone, Qnil);
2363 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2364 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2365 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2366 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
2367 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2368 return clone;
2371 /* :nodoc: */
2372 static VALUE
2373 method_dup(VALUE self)
2375 VALUE clone;
2376 struct METHOD *orig, *data;
2378 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2379 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2380 rb_obj_dup_setup(self, clone);
2381 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2382 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2383 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2384 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
2385 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2386 return clone;
2389 /* Document-method: Method#===
2391 * call-seq:
2392 * method === obj -> result_of_method
2394 * Invokes the method with +obj+ as the parameter like #call.
2395 * This allows a method object to be the target of a +when+ clause
2396 * in a case statement.
2398 * require 'prime'
2400 * case 1373
2401 * when Prime.method(:prime?)
2402 * # ...
2403 * end
2407 /* Document-method: Method#[]
2409 * call-seq:
2410 * meth[args, ...] -> obj
2412 * Invokes the <i>meth</i> with the specified arguments, returning the
2413 * method's return value, like #call.
2415 * m = 12.method("+")
2416 * m[3] #=> 15
2417 * m[20] #=> 32
2421 * call-seq:
2422 * meth.call(args, ...) -> obj
2424 * Invokes the <i>meth</i> with the specified arguments, returning the
2425 * method's return value.
2427 * m = 12.method("+")
2428 * m.call(3) #=> 15
2429 * m.call(20) #=> 32
2432 static VALUE
2433 rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
2435 return rb_method_call_kw(argc, argv, method, RB_PASS_CALLED_KEYWORDS);
2438 VALUE
2439 rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
2441 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2442 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
2445 VALUE
2446 rb_method_call(int argc, const VALUE *argv, VALUE method)
2448 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2449 return rb_method_call_with_block(argc, argv, method, procval);
2452 static const rb_callable_method_entry_t *
2453 method_callable_method_entry(const struct METHOD *data)
2455 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
2456 return (const rb_callable_method_entry_t *)data->me;
2459 static inline VALUE
2460 call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
2461 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
2463 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2464 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
2465 method_callable_method_entry(data), kw_splat);
2468 VALUE
2469 rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
2471 const struct METHOD *data;
2472 rb_execution_context_t *ec = GET_EC();
2474 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2475 if (UNDEF_P(data->recv)) {
2476 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
2478 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
2481 VALUE
2482 rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
2484 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
2487 /**********************************************************************
2489 * Document-class: UnboundMethod
2491 * Ruby supports two forms of objectified methods. Class Method is
2492 * used to represent methods that are associated with a particular
2493 * object: these method objects are bound to that object. Bound
2494 * method objects for an object can be created using Object#method.
2496 * Ruby also supports unbound methods; methods objects that are not
2497 * associated with a particular object. These can be created either
2498 * by calling Module#instance_method or by calling #unbind on a bound
2499 * method object. The result of both of these is an UnboundMethod
2500 * object.
2502 * Unbound methods can only be called after they are bound to an
2503 * object. That object must be a kind_of? the method's original
2504 * class.
2506 * class Square
2507 * def area
2508 * @side * @side
2509 * end
2510 * def initialize(side)
2511 * @side = side
2512 * end
2513 * end
2515 * area_un = Square.instance_method(:area)
2517 * s = Square.new(12)
2518 * area = area_un.bind(s)
2519 * area.call #=> 144
2521 * Unbound methods are a reference to the method at the time it was
2522 * objectified: subsequent changes to the underlying class will not
2523 * affect the unbound method.
2525 * class Test
2526 * def test
2527 * :original
2528 * end
2529 * end
2530 * um = Test.instance_method(:test)
2531 * class Test
2532 * def test
2533 * :modified
2534 * end
2535 * end
2536 * t = Test.new
2537 * t.test #=> :modified
2538 * um.bind(t).call #=> :original
2542 static void
2543 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, const bool clone)
2545 VALUE methclass = data->owner;
2546 VALUE iclass = data->me->defined_class;
2547 VALUE klass = CLASS_OF(recv);
2549 if (RB_TYPE_P(methclass, T_MODULE)) {
2550 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
2551 if (!NIL_P(refined_class)) methclass = refined_class;
2553 if (!RB_TYPE_P(methclass, T_MODULE) && !RTEST(rb_obj_is_kind_of(recv, methclass))) {
2554 if (RCLASS_SINGLETON_P(methclass)) {
2555 rb_raise(rb_eTypeError,
2556 "singleton method called for a different object");
2558 else {
2559 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
2560 methclass);
2564 const rb_method_entry_t *me;
2565 if (clone) {
2566 me = rb_method_entry_clone(data->me);
2568 else {
2569 me = data->me;
2572 if (RB_TYPE_P(me->owner, T_MODULE)) {
2573 if (!clone) {
2574 // if we didn't previously clone the method entry, then we need to clone it now
2575 // because this branch manipulates it in rb_method_entry_complement_defined_class
2576 me = rb_method_entry_clone(me);
2578 VALUE ic = rb_class_search_ancestor(klass, me->owner);
2579 if (ic) {
2580 klass = ic;
2581 iclass = ic;
2583 else {
2584 klass = rb_include_class_new(methclass, klass);
2586 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
2589 *methclass_out = methclass;
2590 *klass_out = klass;
2591 *iclass_out = iclass;
2592 *me_out = me;
2596 * call-seq:
2597 * umeth.bind(obj) -> method
2599 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2600 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2601 * be true.
2603 * class A
2604 * def test
2605 * puts "In test, class = #{self.class}"
2606 * end
2607 * end
2608 * class B < A
2609 * end
2610 * class C < B
2611 * end
2614 * um = B.instance_method(:test)
2615 * bm = um.bind(C.new)
2616 * bm.call
2617 * bm = um.bind(B.new)
2618 * bm.call
2619 * bm = um.bind(A.new)
2620 * bm.call
2622 * <em>produces:</em>
2624 * In test, class = C
2625 * In test, class = B
2626 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2627 * from prog.rb:16
2630 static VALUE
2631 umethod_bind(VALUE method, VALUE recv)
2633 VALUE methclass, klass, iclass;
2634 const rb_method_entry_t *me;
2635 const struct METHOD *data;
2636 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2637 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, true);
2639 struct METHOD *bound;
2640 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
2641 RB_OBJ_WRITE(method, &bound->recv, recv);
2642 RB_OBJ_WRITE(method, &bound->klass, klass);
2643 RB_OBJ_WRITE(method, &bound->iclass, iclass);
2644 RB_OBJ_WRITE(method, &bound->owner, methclass);
2645 RB_OBJ_WRITE(method, &bound->me, me);
2647 return method;
2651 * call-seq:
2652 * umeth.bind_call(recv, args, ...) -> obj
2654 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2655 * specified arguments.
2656 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2658 static VALUE
2659 umethod_bind_call(int argc, VALUE *argv, VALUE method)
2661 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2662 VALUE recv = argv[0];
2663 argc--;
2664 argv++;
2666 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2667 rb_execution_context_t *ec = GET_EC();
2669 const struct METHOD *data;
2670 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2672 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
2673 if (data->me == (const rb_method_entry_t *)cme) {
2674 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2675 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
2677 else {
2678 VALUE methclass, klass, iclass;
2679 const rb_method_entry_t *me;
2680 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, false);
2681 struct METHOD bound = { recv, klass, 0, methclass, me };
2683 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
2688 * Returns the number of required parameters and stores the maximum
2689 * number of parameters in max, or UNLIMITED_ARGUMENTS
2690 * if there is no maximum.
2692 static int
2693 method_def_min_max_arity(const rb_method_definition_t *def, int *max)
2695 again:
2696 if (!def) return *max = 0;
2697 switch (def->type) {
2698 case VM_METHOD_TYPE_CFUNC:
2699 if (def->body.cfunc.argc < 0) {
2700 *max = UNLIMITED_ARGUMENTS;
2701 return 0;
2703 return *max = check_argc(def->body.cfunc.argc);
2704 case VM_METHOD_TYPE_ZSUPER:
2705 *max = UNLIMITED_ARGUMENTS;
2706 return 0;
2707 case VM_METHOD_TYPE_ATTRSET:
2708 return *max = 1;
2709 case VM_METHOD_TYPE_IVAR:
2710 return *max = 0;
2711 case VM_METHOD_TYPE_ALIAS:
2712 def = def->body.alias.original_me->def;
2713 goto again;
2714 case VM_METHOD_TYPE_BMETHOD:
2715 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
2716 case VM_METHOD_TYPE_ISEQ:
2717 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
2718 case VM_METHOD_TYPE_UNDEF:
2719 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2720 return *max = 0;
2721 case VM_METHOD_TYPE_MISSING:
2722 *max = UNLIMITED_ARGUMENTS;
2723 return 0;
2724 case VM_METHOD_TYPE_OPTIMIZED: {
2725 switch (def->body.optimized.type) {
2726 case OPTIMIZED_METHOD_TYPE_SEND:
2727 *max = UNLIMITED_ARGUMENTS;
2728 return 0;
2729 case OPTIMIZED_METHOD_TYPE_CALL:
2730 *max = UNLIMITED_ARGUMENTS;
2731 return 0;
2732 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
2733 *max = UNLIMITED_ARGUMENTS;
2734 return 0;
2735 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
2736 *max = 0;
2737 return 0;
2738 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
2739 *max = 1;
2740 return 1;
2741 default:
2742 break;
2744 break;
2746 case VM_METHOD_TYPE_REFINED:
2747 *max = UNLIMITED_ARGUMENTS;
2748 return 0;
2750 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
2751 UNREACHABLE_RETURN(Qnil);
2754 static int
2755 method_def_arity(const rb_method_definition_t *def)
2757 int max, min = method_def_min_max_arity(def, &max);
2758 return min == max ? min : -min-1;
2762 rb_method_entry_arity(const rb_method_entry_t *me)
2764 return method_def_arity(me->def);
2768 * call-seq:
2769 * meth.arity -> integer
2771 * Returns an indication of the number of arguments accepted by a
2772 * method. Returns a nonnegative integer for methods that take a fixed
2773 * number of arguments. For Ruby methods that take a variable number of
2774 * arguments, returns -n-1, where n is the number of required arguments.
2775 * Keyword arguments will be considered as a single additional argument,
2776 * that argument being mandatory if any keyword argument is mandatory.
2777 * For methods written in C, returns -1 if the call takes a
2778 * variable number of arguments.
2780 * class C
2781 * def one; end
2782 * def two(a); end
2783 * def three(*a); end
2784 * def four(a, b); end
2785 * def five(a, b, *c); end
2786 * def six(a, b, *c, &d); end
2787 * def seven(a, b, x:0); end
2788 * def eight(x:, y:); end
2789 * def nine(x:, y:, **z); end
2790 * def ten(*a, x:, y:); end
2791 * end
2792 * c = C.new
2793 * c.method(:one).arity #=> 0
2794 * c.method(:two).arity #=> 1
2795 * c.method(:three).arity #=> -1
2796 * c.method(:four).arity #=> 2
2797 * c.method(:five).arity #=> -3
2798 * c.method(:six).arity #=> -3
2799 * c.method(:seven).arity #=> -3
2800 * c.method(:eight).arity #=> 1
2801 * c.method(:nine).arity #=> 1
2802 * c.method(:ten).arity #=> -2
2804 * "cat".method(:size).arity #=> 0
2805 * "cat".method(:replace).arity #=> 1
2806 * "cat".method(:squeeze).arity #=> -1
2807 * "cat".method(:count).arity #=> -1
2810 static VALUE
2811 method_arity_m(VALUE method)
2813 int n = method_arity(method);
2814 return INT2FIX(n);
2817 static int
2818 method_arity(VALUE method)
2820 struct METHOD *data;
2822 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2823 return rb_method_entry_arity(data->me);
2826 static const rb_method_entry_t *
2827 original_method_entry(VALUE mod, ID id)
2829 const rb_method_entry_t *me;
2831 while ((me = rb_method_entry(mod, id)) != 0) {
2832 const rb_method_definition_t *def = me->def;
2833 if (def->type != VM_METHOD_TYPE_ZSUPER) break;
2834 mod = RCLASS_SUPER(me->owner);
2835 id = def->original_id;
2837 return me;
2840 static int
2841 method_min_max_arity(VALUE method, int *max)
2843 const struct METHOD *data;
2845 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2846 return method_def_min_max_arity(data->me->def, max);
2850 rb_mod_method_arity(VALUE mod, ID id)
2852 const rb_method_entry_t *me = original_method_entry(mod, id);
2853 if (!me) return 0; /* should raise? */
2854 return rb_method_entry_arity(me);
2858 rb_obj_method_arity(VALUE obj, ID id)
2860 return rb_mod_method_arity(CLASS_OF(obj), id);
2863 VALUE
2864 rb_callable_receiver(VALUE callable)
2866 if (rb_obj_is_proc(callable)) {
2867 VALUE binding = proc_binding(callable);
2868 return rb_funcall(binding, rb_intern("receiver"), 0);
2870 else if (rb_obj_is_method(callable)) {
2871 return method_receiver(callable);
2873 else {
2874 return Qundef;
2878 const rb_method_definition_t *
2879 rb_method_def(VALUE method)
2881 const struct METHOD *data;
2883 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2884 return data->me->def;
2887 static const rb_iseq_t *
2888 method_def_iseq(const rb_method_definition_t *def)
2890 switch (def->type) {
2891 case VM_METHOD_TYPE_ISEQ:
2892 return rb_iseq_check(def->body.iseq.iseqptr);
2893 case VM_METHOD_TYPE_BMETHOD:
2894 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
2895 case VM_METHOD_TYPE_ALIAS:
2896 return method_def_iseq(def->body.alias.original_me->def);
2897 case VM_METHOD_TYPE_CFUNC:
2898 case VM_METHOD_TYPE_ATTRSET:
2899 case VM_METHOD_TYPE_IVAR:
2900 case VM_METHOD_TYPE_ZSUPER:
2901 case VM_METHOD_TYPE_UNDEF:
2902 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2903 case VM_METHOD_TYPE_OPTIMIZED:
2904 case VM_METHOD_TYPE_MISSING:
2905 case VM_METHOD_TYPE_REFINED:
2906 break;
2908 return NULL;
2911 const rb_iseq_t *
2912 rb_method_iseq(VALUE method)
2914 return method_def_iseq(rb_method_def(method));
2917 static const rb_cref_t *
2918 method_cref(VALUE method)
2920 const rb_method_definition_t *def = rb_method_def(method);
2922 again:
2923 switch (def->type) {
2924 case VM_METHOD_TYPE_ISEQ:
2925 return def->body.iseq.cref;
2926 case VM_METHOD_TYPE_ALIAS:
2927 def = def->body.alias.original_me->def;
2928 goto again;
2929 default:
2930 return NULL;
2934 static VALUE
2935 method_def_location(const rb_method_definition_t *def)
2937 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
2938 if (!def->body.attr.location)
2939 return Qnil;
2940 return rb_ary_dup(def->body.attr.location);
2942 return iseq_location(method_def_iseq(def));
2945 VALUE
2946 rb_method_entry_location(const rb_method_entry_t *me)
2948 if (!me) return Qnil;
2949 return method_def_location(me->def);
2953 * call-seq:
2954 * meth.source_location -> [String, Integer]
2956 * Returns the Ruby source filename and line number containing this method
2957 * or nil if this method was not defined in Ruby (i.e. native).
2960 VALUE
2961 rb_method_location(VALUE method)
2963 return method_def_location(rb_method_def(method));
2966 static const rb_method_definition_t *
2967 vm_proc_method_def(VALUE procval)
2969 const rb_proc_t *proc;
2970 const struct rb_block *block;
2971 const struct vm_ifunc *ifunc;
2973 GetProcPtr(procval, proc);
2974 block = &proc->block;
2976 if (vm_block_type(block) == block_type_ifunc &&
2977 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
2978 return rb_method_def((VALUE)ifunc->data);
2980 else {
2981 return NULL;
2985 static VALUE
2986 method_def_parameters(const rb_method_definition_t *def)
2988 const rb_iseq_t *iseq;
2989 const rb_method_definition_t *bmethod_def;
2991 switch (def->type) {
2992 case VM_METHOD_TYPE_ISEQ:
2993 iseq = method_def_iseq(def);
2994 return rb_iseq_parameters(iseq, 0);
2995 case VM_METHOD_TYPE_BMETHOD:
2996 if ((iseq = method_def_iseq(def)) != NULL) {
2997 return rb_iseq_parameters(iseq, 0);
2999 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
3000 return method_def_parameters(bmethod_def);
3002 break;
3004 case VM_METHOD_TYPE_ALIAS:
3005 return method_def_parameters(def->body.alias.original_me->def);
3007 case VM_METHOD_TYPE_OPTIMIZED:
3008 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
3009 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
3010 return rb_ary_new_from_args(1, param);
3012 break;
3014 case VM_METHOD_TYPE_CFUNC:
3015 case VM_METHOD_TYPE_ATTRSET:
3016 case VM_METHOD_TYPE_IVAR:
3017 case VM_METHOD_TYPE_ZSUPER:
3018 case VM_METHOD_TYPE_UNDEF:
3019 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3020 case VM_METHOD_TYPE_MISSING:
3021 case VM_METHOD_TYPE_REFINED:
3022 break;
3025 return rb_unnamed_parameters(method_def_arity(def));
3030 * call-seq:
3031 * meth.parameters -> array
3033 * Returns the parameter information of this method.
3035 * def foo(bar); end
3036 * method(:foo).parameters #=> [[:req, :bar]]
3038 * def foo(bar, baz, bat, &blk); end
3039 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
3041 * def foo(bar, *args); end
3042 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
3044 * def foo(bar, baz, *args, &blk); end
3045 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
3048 static VALUE
3049 rb_method_parameters(VALUE method)
3051 return method_def_parameters(rb_method_def(method));
3055 * call-seq:
3056 * meth.to_s -> string
3057 * meth.inspect -> string
3059 * Returns a human-readable description of the underlying method.
3061 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3062 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3064 * In the latter case, the method description includes the "owner" of the
3065 * original method (+Enumerable+ module, which is included into +Range+).
3067 * +inspect+ also provides, when possible, method argument names (call
3068 * sequence) and source location.
3070 * require 'net/http'
3071 * Net::HTTP.method(:get).inspect
3072 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3074 * <code>...</code> in argument definition means argument is optional (has
3075 * some default value).
3077 * For methods defined in C (language core and extensions), location and
3078 * argument names can't be extracted, and only generic information is provided
3079 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3080 * positional argument).
3082 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3083 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3087 static VALUE
3088 method_inspect(VALUE method)
3090 struct METHOD *data;
3091 VALUE str;
3092 const char *sharp = "#";
3093 VALUE mklass;
3094 VALUE defined_class;
3096 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3097 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
3099 mklass = data->iclass;
3100 if (!mklass) mklass = data->klass;
3102 if (RB_TYPE_P(mklass, T_ICLASS)) {
3103 /* TODO: I'm not sure why mklass is T_ICLASS.
3104 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3105 * but not sure it is needed.
3107 mklass = RBASIC_CLASS(mklass);
3110 if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
3111 defined_class = data->me->def->body.alias.original_me->owner;
3113 else {
3114 defined_class = method_entry_defined_class(data->me);
3117 if (RB_TYPE_P(defined_class, T_ICLASS)) {
3118 defined_class = RBASIC_CLASS(defined_class);
3121 if (UNDEF_P(data->recv)) {
3122 // UnboundMethod
3123 rb_str_buf_append(str, rb_inspect(defined_class));
3125 else if (RCLASS_SINGLETON_P(mklass)) {
3126 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
3128 if (UNDEF_P(data->recv)) {
3129 rb_str_buf_append(str, rb_inspect(mklass));
3131 else if (data->recv == v) {
3132 rb_str_buf_append(str, rb_inspect(v));
3133 sharp = ".";
3135 else {
3136 rb_str_buf_append(str, rb_inspect(data->recv));
3137 rb_str_buf_cat2(str, "(");
3138 rb_str_buf_append(str, rb_inspect(v));
3139 rb_str_buf_cat2(str, ")");
3140 sharp = ".";
3143 else {
3144 mklass = data->klass;
3145 if (RCLASS_SINGLETON_P(mklass)) {
3146 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
3147 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
3148 do {
3149 mklass = RCLASS_SUPER(mklass);
3150 } while (RB_TYPE_P(mklass, T_ICLASS));
3153 rb_str_buf_append(str, rb_inspect(mklass));
3154 if (defined_class != mklass) {
3155 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
3158 rb_str_buf_cat2(str, sharp);
3159 rb_str_append(str, rb_id2str(data->me->called_id));
3160 if (data->me->called_id != data->me->def->original_id) {
3161 rb_str_catf(str, "(%"PRIsVALUE")",
3162 rb_id2str(data->me->def->original_id));
3164 if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
3165 rb_str_buf_cat2(str, " (not-implemented)");
3168 // parameter information
3170 VALUE params = rb_method_parameters(method);
3171 VALUE pair, name, kind;
3172 const VALUE req = ID2SYM(rb_intern("req"));
3173 const VALUE opt = ID2SYM(rb_intern("opt"));
3174 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
3175 const VALUE key = ID2SYM(rb_intern("key"));
3176 const VALUE rest = ID2SYM(rb_intern("rest"));
3177 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
3178 const VALUE block = ID2SYM(rb_intern("block"));
3179 const VALUE nokey = ID2SYM(rb_intern("nokey"));
3180 int forwarding = 0;
3182 rb_str_buf_cat2(str, "(");
3184 if (RARRAY_LEN(params) == 3 &&
3185 RARRAY_AREF(RARRAY_AREF(params, 0), 0) == rest &&
3186 RARRAY_AREF(RARRAY_AREF(params, 0), 1) == ID2SYM('*') &&
3187 RARRAY_AREF(RARRAY_AREF(params, 1), 0) == keyrest &&
3188 RARRAY_AREF(RARRAY_AREF(params, 1), 1) == ID2SYM(idPow) &&
3189 RARRAY_AREF(RARRAY_AREF(params, 2), 0) == block &&
3190 RARRAY_AREF(RARRAY_AREF(params, 2), 1) == ID2SYM('&')) {
3191 forwarding = 1;
3194 for (int i = 0; i < RARRAY_LEN(params); i++) {
3195 pair = RARRAY_AREF(params, i);
3196 kind = RARRAY_AREF(pair, 0);
3197 name = RARRAY_AREF(pair, 1);
3198 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3199 if (NIL_P(name) || name == Qfalse) {
3200 // FIXME: can it be reduced to switch/case?
3201 if (kind == req || kind == opt) {
3202 name = rb_str_new2("_");
3204 else if (kind == rest || kind == keyrest) {
3205 name = rb_str_new2("");
3207 else if (kind == block) {
3208 name = rb_str_new2("block");
3210 else if (kind == nokey) {
3211 name = rb_str_new2("nil");
3215 if (kind == req) {
3216 rb_str_catf(str, "%"PRIsVALUE, name);
3218 else if (kind == opt) {
3219 rb_str_catf(str, "%"PRIsVALUE"=...", name);
3221 else if (kind == keyreq) {
3222 rb_str_catf(str, "%"PRIsVALUE":", name);
3224 else if (kind == key) {
3225 rb_str_catf(str, "%"PRIsVALUE": ...", name);
3227 else if (kind == rest) {
3228 if (name == ID2SYM('*')) {
3229 rb_str_cat_cstr(str, forwarding ? "..." : "*");
3231 else {
3232 rb_str_catf(str, "*%"PRIsVALUE, name);
3235 else if (kind == keyrest) {
3236 if (name != ID2SYM(idPow)) {
3237 rb_str_catf(str, "**%"PRIsVALUE, name);
3239 else if (i > 0) {
3240 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3242 else {
3243 rb_str_cat_cstr(str, "**");
3246 else if (kind == block) {
3247 if (name == ID2SYM('&')) {
3248 if (forwarding) {
3249 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3251 else {
3252 rb_str_cat_cstr(str, "...");
3255 else {
3256 rb_str_catf(str, "&%"PRIsVALUE, name);
3259 else if (kind == nokey) {
3260 rb_str_buf_cat2(str, "**nil");
3263 if (i < RARRAY_LEN(params) - 1) {
3264 rb_str_buf_cat2(str, ", ");
3267 rb_str_buf_cat2(str, ")");
3270 { // source location
3271 VALUE loc = rb_method_location(method);
3272 if (!NIL_P(loc)) {
3273 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
3274 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
3278 rb_str_buf_cat2(str, ">");
3280 return str;
3283 static VALUE
3284 bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
3286 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
3289 VALUE
3290 rb_proc_new(
3291 rb_block_call_func_t func,
3292 VALUE val)
3294 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
3295 return procval;
3299 * call-seq:
3300 * meth.to_proc -> proc
3302 * Returns a Proc object corresponding to this method.
3305 static VALUE
3306 method_to_proc(VALUE method)
3308 VALUE procval;
3309 rb_proc_t *proc;
3312 * class Method
3313 * def to_proc
3314 * lambda{|*args|
3315 * self.call(*args)
3317 * end
3318 * end
3320 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
3321 GetProcPtr(procval, proc);
3322 proc->is_from_method = 1;
3323 return procval;
3326 extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
3329 * call-seq:
3330 * meth.super_method -> method
3332 * Returns a Method of superclass which would be called when super is used
3333 * or nil if there is no method on superclass.
3336 static VALUE
3337 method_super_method(VALUE method)
3339 const struct METHOD *data;
3340 VALUE super_class, iclass;
3341 ID mid;
3342 const rb_method_entry_t *me;
3344 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3345 iclass = data->iclass;
3346 if (!iclass) return Qnil;
3347 if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
3348 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
3349 data->me->def->body.alias.original_me->owner));
3350 mid = data->me->def->body.alias.original_me->def->original_id;
3352 else {
3353 super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
3354 mid = data->me->def->original_id;
3356 if (!super_class) return Qnil;
3357 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
3358 if (!me) return Qnil;
3359 return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
3363 * call-seq:
3364 * local_jump_error.exit_value -> obj
3366 * Returns the exit value associated with this +LocalJumpError+.
3368 static VALUE
3369 localjump_xvalue(VALUE exc)
3371 return rb_iv_get(exc, "@exit_value");
3375 * call-seq:
3376 * local_jump_error.reason -> symbol
3378 * The reason this block was terminated:
3379 * :break, :redo, :retry, :next, :return, or :noreason.
3382 static VALUE
3383 localjump_reason(VALUE exc)
3385 return rb_iv_get(exc, "@reason");
3388 rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
3390 static const rb_env_t *
3391 env_clone(const rb_env_t *env, const rb_cref_t *cref)
3393 VALUE *new_ep;
3394 VALUE *new_body;
3395 const rb_env_t *new_env;
3397 VM_ASSERT(env->ep > env->env);
3398 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
3400 if (cref == NULL) {
3401 cref = rb_vm_cref_new_toplevel();
3404 new_body = ALLOC_N(VALUE, env->env_size);
3405 new_ep = &new_body[env->ep - env->env];
3406 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
3408 /* The memcpy has to happen after the vm_env_new because it can trigger a
3409 * GC compaction which can move the objects in the env. */
3410 MEMCPY(new_body, env->env, VALUE, env->env_size);
3411 /* VM_ENV_DATA_INDEX_ENV is set in vm_env_new but will get overwritten
3412 * by the memcpy above. */
3413 new_ep[VM_ENV_DATA_INDEX_ENV] = (VALUE)new_env;
3414 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
3415 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
3416 return new_env;
3420 * call-seq:
3421 * prc.binding -> binding
3423 * Returns the binding associated with <i>prc</i>.
3425 * def fred(param)
3426 * proc {}
3427 * end
3429 * b = fred(99)
3430 * eval("param", b.binding) #=> 99
3432 static VALUE
3433 proc_binding(VALUE self)
3435 VALUE bindval, binding_self = Qundef;
3436 rb_binding_t *bind;
3437 const rb_proc_t *proc;
3438 const rb_iseq_t *iseq = NULL;
3439 const struct rb_block *block;
3440 const rb_env_t *env = NULL;
3442 GetProcPtr(self, proc);
3443 block = &proc->block;
3445 if (proc->is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
3447 again:
3448 switch (vm_block_type(block)) {
3449 case block_type_iseq:
3450 iseq = block->as.captured.code.iseq;
3451 binding_self = block->as.captured.self;
3452 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3453 break;
3454 case block_type_proc:
3455 GetProcPtr(block->as.proc, proc);
3456 block = &proc->block;
3457 goto again;
3458 case block_type_ifunc:
3460 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
3461 if (IS_METHOD_PROC_IFUNC(ifunc)) {
3462 VALUE method = (VALUE)ifunc->data;
3463 VALUE name = rb_fstring_lit("<empty_iseq>");
3464 rb_iseq_t *empty;
3465 binding_self = method_receiver(method);
3466 iseq = rb_method_iseq(method);
3467 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3468 env = env_clone(env, method_cref(method));
3469 /* set empty iseq */
3470 empty = rb_iseq_new(Qnil, name, name, Qnil, 0, ISEQ_TYPE_TOP);
3471 RB_OBJ_WRITE(env, &env->iseq, empty);
3472 break;
3475 /* FALLTHROUGH */
3476 case block_type_symbol:
3477 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
3478 UNREACHABLE_RETURN(Qnil);
3481 bindval = rb_binding_alloc(rb_cBinding);
3482 GetBindingPtr(bindval, bind);
3483 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
3484 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
3485 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
3486 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
3488 if (iseq) {
3489 rb_iseq_check(iseq);
3490 RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(iseq)->location.pathobj);
3491 bind->first_lineno = ISEQ_BODY(iseq)->location.first_lineno;
3493 else {
3494 RB_OBJ_WRITE(bindval, &bind->pathobj,
3495 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
3496 bind->first_lineno = 1;
3499 return bindval;
3502 static rb_block_call_func curry;
3504 static VALUE
3505 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
3507 VALUE args = rb_ary_new3(3, proc, passed, arity);
3508 rb_proc_t *procp;
3509 int is_lambda;
3511 GetProcPtr(proc, procp);
3512 is_lambda = procp->is_lambda;
3513 rb_ary_freeze(passed);
3514 rb_ary_freeze(args);
3515 proc = rb_proc_new(curry, args);
3516 GetProcPtr(proc, procp);
3517 procp->is_lambda = is_lambda;
3518 return proc;
3521 static VALUE
3522 curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3524 VALUE proc, passed, arity;
3525 proc = RARRAY_AREF(args, 0);
3526 passed = RARRAY_AREF(args, 1);
3527 arity = RARRAY_AREF(args, 2);
3529 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
3530 rb_ary_freeze(passed);
3532 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
3533 if (!NIL_P(blockarg)) {
3534 rb_warn("given block not used");
3536 arity = make_curry_proc(proc, passed, arity);
3537 return arity;
3539 else {
3540 return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
3545 * call-seq:
3546 * prc.curry -> a_proc
3547 * prc.curry(arity) -> a_proc
3549 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3550 * it determines the number of arguments.
3551 * A curried proc receives some arguments. If a sufficient number of
3552 * arguments are supplied, it passes the supplied arguments to the original
3553 * proc and returns the result. Otherwise, returns another curried proc that
3554 * takes the rest of arguments.
3556 * The optional <i>arity</i> argument should be supplied when currying procs with
3557 * variable arguments to determine how many arguments are needed before the proc is
3558 * called.
3560 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3561 * p b.curry[1][2][3] #=> 6
3562 * p b.curry[1, 2][3, 4] #=> 6
3563 * p b.curry(5)[1][2][3][4][5] #=> 6
3564 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3565 * p b.curry(1)[1] #=> 1
3567 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3568 * p b.curry[1][2][3] #=> 6
3569 * p b.curry[1, 2][3, 4] #=> 10
3570 * p b.curry(5)[1][2][3][4][5] #=> 15
3571 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3572 * p b.curry(1)[1] #=> 1
3574 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3575 * p b.curry[1][2][3] #=> 6
3576 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3577 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3578 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3580 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3581 * p b.curry[1][2][3] #=> 6
3582 * p b.curry[1, 2][3, 4] #=> 10
3583 * p b.curry(5)[1][2][3][4][5] #=> 15
3584 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3585 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3587 * b = proc { :foo }
3588 * p b.curry[] #=> :foo
3590 static VALUE
3591 proc_curry(int argc, const VALUE *argv, VALUE self)
3593 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
3594 VALUE arity;
3596 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
3597 arity = INT2FIX(min_arity);
3599 else {
3600 sarity = FIX2INT(arity);
3601 if (rb_proc_lambda_p(self)) {
3602 rb_check_arity(sarity, min_arity, max_arity);
3606 return make_curry_proc(self, rb_ary_new(), arity);
3610 * call-seq:
3611 * meth.curry -> proc
3612 * meth.curry(arity) -> proc
3614 * Returns a curried proc based on the method. When the proc is called with a number of
3615 * arguments that is lower than the method's arity, then another curried proc is returned.
3616 * Only when enough arguments have been supplied to satisfy the method signature, will the
3617 * method actually be called.
3619 * The optional <i>arity</i> argument should be supplied when currying methods with
3620 * variable arguments to determine how many arguments are needed before the method is
3621 * called.
3623 * def foo(a,b,c)
3624 * [a, b, c]
3625 * end
3627 * proc = self.method(:foo).curry
3628 * proc2 = proc.call(1, 2) #=> #<Proc>
3629 * proc2.call(3) #=> [1,2,3]
3631 * def vararg(*args)
3632 * args
3633 * end
3635 * proc = self.method(:vararg).curry(4)
3636 * proc2 = proc.call(:x) #=> #<Proc>
3637 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3638 * proc3.call(:a) #=> [:x, :y, :z, :a]
3641 static VALUE
3642 rb_method_curry(int argc, const VALUE *argv, VALUE self)
3644 VALUE proc = method_to_proc(self);
3645 return proc_curry(argc, argv, proc);
3648 static VALUE
3649 compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3651 VALUE f, g, fargs;
3652 f = RARRAY_AREF(args, 0);
3653 g = RARRAY_AREF(args, 1);
3655 if (rb_obj_is_proc(g))
3656 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3657 else
3658 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3660 if (rb_obj_is_proc(f))
3661 return rb_proc_call(f, rb_ary_new3(1, fargs));
3662 else
3663 return rb_funcallv(f, idCall, 1, &fargs);
3666 static VALUE
3667 to_callable(VALUE f)
3669 VALUE mesg;
3671 if (rb_obj_is_proc(f)) return f;
3672 if (rb_obj_is_method(f)) return f;
3673 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
3674 mesg = rb_fstring_lit("callable object is expected");
3675 rb_exc_raise(rb_exc_new_str(rb_eTypeError, mesg));
3678 static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
3679 static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
3682 * call-seq:
3683 * prc << g -> a_proc
3685 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3686 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3687 * then calls this proc with the result.
3689 * f = proc {|x| x * x }
3690 * g = proc {|x| x + x }
3691 * p (f << g).call(2) #=> 16
3693 * See Proc#>> for detailed explanations.
3695 static VALUE
3696 proc_compose_to_left(VALUE self, VALUE g)
3698 return rb_proc_compose_to_left(self, to_callable(g));
3701 static VALUE
3702 rb_proc_compose_to_left(VALUE self, VALUE g)
3704 VALUE proc, args, procs[2];
3705 rb_proc_t *procp;
3706 int is_lambda;
3708 procs[0] = self;
3709 procs[1] = g;
3710 args = rb_ary_tmp_new_from_values(0, 2, procs);
3712 if (rb_obj_is_proc(g)) {
3713 GetProcPtr(g, procp);
3714 is_lambda = procp->is_lambda;
3716 else {
3717 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
3718 is_lambda = 1;
3721 proc = rb_proc_new(compose, args);
3722 GetProcPtr(proc, procp);
3723 procp->is_lambda = is_lambda;
3725 return proc;
3729 * call-seq:
3730 * prc >> g -> a_proc
3732 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3733 * The returned proc takes a variable number of arguments, calls this proc with them
3734 * then calls <i>g</i> with the result.
3736 * f = proc {|x| x * x }
3737 * g = proc {|x| x + x }
3738 * p (f >> g).call(2) #=> 8
3740 * <i>g</i> could be other Proc, or Method, or any other object responding to
3741 * +call+ method:
3743 * class Parser
3744 * def self.call(text)
3745 * # ...some complicated parsing logic...
3746 * end
3747 * end
3749 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3750 * pipeline.call('data.json')
3752 * See also Method#>> and Method#<<.
3754 static VALUE
3755 proc_compose_to_right(VALUE self, VALUE g)
3757 return rb_proc_compose_to_right(self, to_callable(g));
3760 static VALUE
3761 rb_proc_compose_to_right(VALUE self, VALUE g)
3763 VALUE proc, args, procs[2];
3764 rb_proc_t *procp;
3765 int is_lambda;
3767 procs[0] = g;
3768 procs[1] = self;
3769 args = rb_ary_tmp_new_from_values(0, 2, procs);
3771 GetProcPtr(self, procp);
3772 is_lambda = procp->is_lambda;
3774 proc = rb_proc_new(compose, args);
3775 GetProcPtr(proc, procp);
3776 procp->is_lambda = is_lambda;
3778 return proc;
3782 * call-seq:
3783 * meth << g -> a_proc
3785 * Returns a proc that is the composition of this method and the given <i>g</i>.
3786 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3787 * then calls this method with the result.
3789 * def f(x)
3790 * x * x
3791 * end
3793 * f = self.method(:f)
3794 * g = proc {|x| x + x }
3795 * p (f << g).call(2) #=> 16
3797 static VALUE
3798 rb_method_compose_to_left(VALUE self, VALUE g)
3800 g = to_callable(g);
3801 self = method_to_proc(self);
3802 return proc_compose_to_left(self, g);
3806 * call-seq:
3807 * meth >> g -> a_proc
3809 * Returns a proc that is the composition of this method and the given <i>g</i>.
3810 * The returned proc takes a variable number of arguments, calls this method
3811 * with them then calls <i>g</i> with the result.
3813 * def f(x)
3814 * x * x
3815 * end
3817 * f = self.method(:f)
3818 * g = proc {|x| x + x }
3819 * p (f >> g).call(2) #=> 8
3821 static VALUE
3822 rb_method_compose_to_right(VALUE self, VALUE g)
3824 g = to_callable(g);
3825 self = method_to_proc(self);
3826 return proc_compose_to_right(self, g);
3830 * call-seq:
3831 * proc.ruby2_keywords -> proc
3833 * Marks the proc as passing keywords through a normal argument splat.
3834 * This should only be called on procs that accept an argument splat
3835 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3836 * marks the proc such that if the proc is called with keyword arguments,
3837 * the final hash argument is marked with a special flag such that if it
3838 * is the final element of a normal argument splat to another method call,
3839 * and that method call does not include explicit keywords or a keyword
3840 * splat, the final element is interpreted as keywords. In other words,
3841 * keywords will be passed through the proc to other methods.
3843 * This should only be used for procs that delegate keywords to another
3844 * method, and only for backwards compatibility with Ruby versions before
3845 * 2.7.
3847 * This method will probably be removed at some point, as it exists only
3848 * for backwards compatibility. As it does not exist in Ruby versions
3849 * before 2.7, check that the proc responds to this method before calling
3850 * it. Also, be aware that if this method is removed, the behavior of the
3851 * proc will change so that it does not pass through keywords.
3853 * module Mod
3854 * foo = ->(meth, *args, &block) do
3855 * send(:"do_#{meth}", *args, &block)
3856 * end
3857 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3858 * end
3861 static VALUE
3862 proc_ruby2_keywords(VALUE procval)
3864 rb_proc_t *proc;
3865 GetProcPtr(procval, proc);
3867 rb_check_frozen(procval);
3869 if (proc->is_from_method) {
3870 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
3871 return procval;
3874 switch (proc->block.type) {
3875 case block_type_iseq:
3876 if (ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_rest &&
3877 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kw &&
3878 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kwrest) {
3879 ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.ruby2_keywords = 1;
3881 else {
3882 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
3884 break;
3885 default:
3886 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
3887 break;
3890 return procval;
3894 * Document-class: LocalJumpError
3896 * Raised when Ruby can't yield as requested.
3898 * A typical scenario is attempting to yield when no block is given:
3900 * def call_block
3901 * yield 42
3902 * end
3903 * call_block
3905 * <em>raises the exception:</em>
3907 * LocalJumpError: no block given (yield)
3909 * A more subtle example:
3911 * def get_me_a_return
3912 * Proc.new { return 42 }
3913 * end
3914 * get_me_a_return.call
3916 * <em>raises the exception:</em>
3918 * LocalJumpError: unexpected return
3922 * Document-class: SystemStackError
3924 * Raised in case of a stack overflow.
3926 * def me_myself_and_i
3927 * me_myself_and_i
3928 * end
3929 * me_myself_and_i
3931 * <em>raises the exception:</em>
3933 * SystemStackError: stack level too deep
3937 * Document-class: Proc
3939 * A +Proc+ object is an encapsulation of a block of code, which can be stored
3940 * in a local variable, passed to a method or another Proc, and can be called.
3941 * Proc is an essential concept in Ruby and a core of its functional
3942 * programming features.
3944 * square = Proc.new {|x| x**2 }
3946 * square.call(3) #=> 9
3947 * # shorthands:
3948 * square.(3) #=> 9
3949 * square[3] #=> 9
3951 * Proc objects are _closures_, meaning they remember and can use the entire
3952 * context in which they were created.
3954 * def gen_times(factor)
3955 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
3956 * end
3958 * times3 = gen_times(3)
3959 * times5 = gen_times(5)
3961 * times3.call(12) #=> 36
3962 * times5.call(5) #=> 25
3963 * times3.call(times5.call(4)) #=> 60
3965 * == Creation
3967 * There are several methods to create a Proc
3969 * * Use the Proc class constructor:
3971 * proc1 = Proc.new {|x| x**2 }
3973 * * Use the Kernel#proc method as a shorthand of Proc.new:
3975 * proc2 = proc {|x| x**2 }
3977 * * Receiving a block of code into proc argument (note the <code>&</code>):
3979 * def make_proc(&block)
3980 * block
3981 * end
3983 * proc3 = make_proc {|x| x**2 }
3985 * * Construct a proc with lambda semantics using the Kernel#lambda method
3986 * (see below for explanations about lambdas):
3988 * lambda1 = lambda {|x| x**2 }
3990 * * Use the {Lambda proc literal}[rdoc-ref:syntax/literals.rdoc@Lambda+Proc+Literals] syntax
3991 * (also constructs a proc with lambda semantics):
3993 * lambda2 = ->(x) { x**2 }
3995 * == Lambda and non-lambda semantics
3997 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
3998 * Differences are:
4000 * * In lambdas, +return+ and +break+ means exit from this lambda;
4001 * * In non-lambda procs, +return+ means exit from embracing method
4002 * (and will throw +LocalJumpError+ if invoked outside the method);
4003 * * In non-lambda procs, +break+ means exit from the method which the block given for.
4004 * (and will throw +LocalJumpError+ if invoked after the method returns);
4005 * * In lambdas, arguments are treated in the same way as in methods: strict,
4006 * with +ArgumentError+ for mismatching argument number,
4007 * and no additional argument processing;
4008 * * Regular procs accept arguments more generously: missing arguments
4009 * are filled with +nil+, single Array arguments are deconstructed if the
4010 * proc has multiple arguments, and there is no error raised on extra
4011 * arguments.
4013 * Examples:
4015 * # +return+ in non-lambda proc, +b+, exits +m2+.
4016 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
4017 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
4018 * #=> []
4020 * # +break+ in non-lambda proc, +b+, exits +m1+.
4021 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
4022 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
4023 * #=> [:m2]
4025 * # +next+ in non-lambda proc, +b+, exits the block.
4026 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
4027 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
4028 * #=> [:m1, :m2]
4030 * # Using +proc+ method changes the behavior as follows because
4031 * # The block is given for +proc+ method and embraced by +m2+.
4032 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
4033 * #=> []
4034 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4035 * # break from proc-closure (LocalJumpError)
4036 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4037 * #=> [:m1, :m2]
4039 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4040 * # (+lambda+ method behaves same.)
4041 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4042 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4043 * #=> [:m1, :m2]
4044 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4045 * #=> [:m1, :m2]
4046 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
4047 * #=> [:m1, :m2]
4049 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4050 * p.call(1, 2) #=> "x=1, y=2"
4051 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4052 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4053 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4055 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4056 * l.call(1, 2) #=> "x=1, y=2"
4057 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4058 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4059 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4061 * def test_return
4062 * -> { return 3 }.call # just returns from lambda into method body
4063 * proc { return 4 }.call # returns from method
4064 * return 5
4065 * end
4067 * test_return # => 4, return from proc
4069 * Lambdas are useful as self-sufficient functions, in particular useful as
4070 * arguments to higher-order functions, behaving exactly like Ruby methods.
4072 * Procs are useful for implementing iterators:
4074 * def test
4075 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4076 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4077 * end
4079 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4080 * which means that the internal arrays will be deconstructed to pairs of
4081 * arguments, and +return+ will exit from the method +test+. That would
4082 * not be possible with a stricter lambda.
4084 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4086 * Lambda semantics is typically preserved during the proc lifetime, including
4087 * <code>&</code>-deconstruction to a block of code:
4089 * p = proc {|x, y| x }
4090 * l = lambda {|x, y| x }
4091 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4092 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4094 * The only exception is dynamic method definition: even if defined by
4095 * passing a non-lambda proc, methods still have normal semantics of argument
4096 * checking.
4098 * class C
4099 * define_method(:e, &proc {})
4100 * end
4101 * C.new.e(1,2) #=> ArgumentError
4102 * C.new.method(:e).to_proc.lambda? #=> true
4104 * This exception ensures that methods never have unusual argument passing
4105 * conventions, and makes it easy to have wrappers defining methods that
4106 * behave as usual.
4108 * class C
4109 * def self.def2(name, &body)
4110 * define_method(name, &body)
4111 * end
4113 * def2(:f) {}
4114 * end
4115 * C.new.f(1,2) #=> ArgumentError
4117 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4118 * yet defines a method which has normal semantics.
4120 * == Conversion of other objects to procs
4122 * Any object that implements the +to_proc+ method can be converted into
4123 * a proc by the <code>&</code> operator, and therefore can be
4124 * consumed by iterators.
4127 * class Greeter
4128 * def initialize(greeting)
4129 * @greeting = greeting
4130 * end
4132 * def to_proc
4133 * proc {|name| "#{@greeting}, #{name}!" }
4134 * end
4135 * end
4137 * hi = Greeter.new("Hi")
4138 * hey = Greeter.new("Hey")
4139 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4140 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4142 * Of the Ruby core classes, this method is implemented by Symbol,
4143 * Method, and Hash.
4145 * :to_s.to_proc.call(1) #=> "1"
4146 * [1, 2].map(&:to_s) #=> ["1", "2"]
4148 * method(:puts).to_proc.call(1) # prints 1
4149 * [1, 2].each(&method(:puts)) # prints 1, 2
4151 * {test: 1}.to_proc.call(:test) #=> 1
4152 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4154 * == Orphaned Proc
4156 * +return+ and +break+ in a block exit a method.
4157 * If a Proc object is generated from the block and the Proc object
4158 * survives until the method is returned, +return+ and +break+ cannot work.
4159 * In such case, +return+ and +break+ raises LocalJumpError.
4160 * A Proc object in such situation is called as orphaned Proc object.
4162 * Note that the method to exit is different for +return+ and +break+.
4163 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4165 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4166 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4168 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4169 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4171 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4172 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4174 * Since +return+ and +break+ exits the block itself in lambdas,
4175 * lambdas cannot be orphaned.
4177 * == Numbered parameters
4179 * Numbered parameters are implicitly defined block parameters intended to
4180 * simplify writing short blocks:
4182 * # Explicit parameter:
4183 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4184 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4186 * # Implicit parameter:
4187 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4188 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4190 * Parameter names from +_1+ to +_9+ are supported:
4192 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4193 * # => [120, 150, 180]
4195 * Though, it is advised to resort to them wisely, probably limiting
4196 * yourself to +_1+ and +_2+, and to one-line blocks.
4198 * Numbered parameters can't be used together with explicitly named
4199 * ones:
4201 * [10, 20, 30].map { |x| _1**2 }
4202 * # SyntaxError (ordinary parameter is defined)
4204 * To avoid conflicts, naming local variables or method
4205 * arguments +_1+, +_2+ and so on, causes a warning.
4207 * _1 = 'test'
4208 * # warning: `_1' is reserved as numbered parameter
4210 * Using implicit numbered parameters affects block's arity:
4212 * p = proc { _1 + _2 }
4213 * l = lambda { _1 + _2 }
4214 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4215 * p.arity # => 2
4216 * l.parameters # => [[:req, :_1], [:req, :_2]]
4217 * l.arity # => 2
4219 * Blocks with numbered parameters can't be nested:
4221 * %w[test me].each { _1.each_char { p _1 } }
4222 * # SyntaxError (numbered parameter is already used in outer block here)
4223 * # %w[test me].each { _1.each_char { p _1 } }
4224 * # ^~
4226 * Numbered parameters were introduced in Ruby 2.7.
4230 void
4231 Init_Proc(void)
4233 #undef rb_intern
4234 /* Proc */
4235 rb_cProc = rb_define_class("Proc", rb_cObject);
4236 rb_undef_alloc_func(rb_cProc);
4237 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
4239 rb_add_method_optimized(rb_cProc, idCall, OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4240 rb_add_method_optimized(rb_cProc, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4241 rb_add_method_optimized(rb_cProc, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4242 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4244 #if 0 /* for RDoc */
4245 rb_define_method(rb_cProc, "call", proc_call, -1);
4246 rb_define_method(rb_cProc, "[]", proc_call, -1);
4247 rb_define_method(rb_cProc, "===", proc_call, -1);
4248 rb_define_method(rb_cProc, "yield", proc_call, -1);
4249 #endif
4251 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
4252 rb_define_method(rb_cProc, "arity", proc_arity, 0);
4253 rb_define_method(rb_cProc, "clone", proc_clone, 0);
4254 rb_define_method(rb_cProc, "dup", proc_dup, 0);
4255 rb_define_method(rb_cProc, "hash", proc_hash, 0);
4256 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
4257 rb_define_alias(rb_cProc, "inspect", "to_s");
4258 rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
4259 rb_define_method(rb_cProc, "binding", proc_binding, 0);
4260 rb_define_method(rb_cProc, "curry", proc_curry, -1);
4261 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
4262 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
4263 rb_define_method(rb_cProc, "==", proc_eq, 1);
4264 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
4265 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
4266 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, -1);
4267 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
4268 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4270 /* Exceptions */
4271 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
4272 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
4273 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
4275 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
4276 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
4278 /* utility functions */
4279 rb_define_global_function("proc", f_proc, 0);
4280 rb_define_global_function("lambda", f_lambda, 0);
4282 /* Method */
4283 rb_cMethod = rb_define_class("Method", rb_cObject);
4284 rb_undef_alloc_func(rb_cMethod);
4285 rb_undef_method(CLASS_OF(rb_cMethod), "new");
4286 rb_define_method(rb_cMethod, "==", method_eq, 1);
4287 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
4288 rb_define_method(rb_cMethod, "hash", method_hash, 0);
4289 rb_define_method(rb_cMethod, "clone", method_clone, 0);
4290 rb_define_method(rb_cMethod, "dup", method_dup, 0);
4291 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
4292 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
4293 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
4294 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
4295 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
4296 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
4297 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
4298 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
4299 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
4300 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
4301 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
4302 rb_define_method(rb_cMethod, "name", method_name, 0);
4303 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
4304 rb_define_method(rb_cMethod, "owner", method_owner, 0);
4305 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
4306 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
4307 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
4308 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
4309 rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
4310 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
4311 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
4313 /* UnboundMethod */
4314 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
4315 rb_undef_alloc_func(rb_cUnboundMethod);
4316 rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
4317 rb_define_method(rb_cUnboundMethod, "==", unbound_method_eq, 1);
4318 rb_define_method(rb_cUnboundMethod, "eql?", unbound_method_eq, 1);
4319 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
4320 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
4321 rb_define_method(rb_cUnboundMethod, "dup", method_dup, 0);
4322 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
4323 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
4324 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
4325 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
4326 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
4327 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
4328 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
4329 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
4330 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
4331 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
4332 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
4334 /* Module#*_method */
4335 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
4336 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
4337 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
4339 /* Kernel */
4340 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
4342 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
4343 "define_method", top_define_method, -1);
4347 * Objects of class Binding encapsulate the execution context at some
4348 * particular place in the code and retain this context for future
4349 * use. The variables, methods, value of <code>self</code>, and
4350 * possibly an iterator block that can be accessed in this context
4351 * are all retained. Binding objects can be created using
4352 * Kernel#binding, and are made available to the callback of
4353 * Kernel#set_trace_func and instances of TracePoint.
4355 * These binding objects can be passed as the second argument of the
4356 * Kernel#eval method, establishing an environment for the
4357 * evaluation.
4359 * class Demo
4360 * def initialize(n)
4361 * @secret = n
4362 * end
4363 * def get_binding
4364 * binding
4365 * end
4366 * end
4368 * k1 = Demo.new(99)
4369 * b1 = k1.get_binding
4370 * k2 = Demo.new(-3)
4371 * b2 = k2.get_binding
4373 * eval("@secret", b1) #=> 99
4374 * eval("@secret", b2) #=> -3
4375 * eval("@secret") #=> nil
4377 * Binding objects have no class-specific methods.
4381 void
4382 Init_Binding(void)
4384 rb_cBinding = rb_define_class("Binding", rb_cObject);
4385 rb_undef_alloc_func(rb_cBinding);
4386 rb_undef_method(CLASS_OF(rb_cBinding), "new");
4387 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
4388 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
4389 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
4390 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
4391 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
4392 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
4393 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
4394 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
4395 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
4396 rb_define_global_function("binding", rb_f_binding, 0);