1 /**********************************************************************
3 proc.c - Proc, Binding, Env
6 created at: Wed Jan 17 12:13:14 2007
8 Copyright (C) 2004-2007 Koichi Sasada
10 **********************************************************************/
12 #include "eval_intern.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"
26 const rb_cref_t
*rb_vm_cref_in_context(VALUE self
, VALUE cbase
);
31 /* needed for #super_method */
33 /* Different than me->owner only for ZSUPER methods.
34 This is error-prone but unavoidable unless ZSUPER methods are removed. */
36 const rb_method_entry_t
* const me
;
37 /* for bound methods, `me' should be rb_callable_method_entry_t * */
40 VALUE rb_cUnboundMethod
;
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
);
52 #define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
55 block_mark_and_move(struct rb_block
*block
)
57 switch (block
->type
) {
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
);
65 rb_gc_mark_and_move((VALUE
*)&captured
->ep
[VM_ENV_DATA_INDEX_ENV
]);
69 case block_type_symbol
:
70 rb_gc_mark_and_move(&block
->as
.symbol
);
73 rb_gc_mark_and_move(&block
->as
.proc
);
79 proc_mark_and_move(void *ptr
)
81 rb_proc_t
*proc
= ptr
;
82 block_mark_and_move((struct rb_block
*)&proc
->block
);
87 VALUE env
[VM_ENV_DATA_SIZE
+ 1]; /* ..., envval */
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
= {
103 RUBY_TYPED_DEFAULT_FREE
,
107 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
| RUBY_TYPED_WB_PROTECTED
111 rb_proc_alloc(VALUE klass
)
114 return TypedData_Make_Struct(klass
, rb_proc_t
, &proc_data_type
, proc
);
118 rb_obj_is_proc(VALUE proc
)
120 return RBOOL(rb_typeddata_is_kind_of(proc
, &proc_data_type
));
125 proc_clone(VALUE self
)
127 VALUE procval
= rb_proc_dup(self
);
128 return rb_obj_clone_setup(self
, procval
, Qnil
);
135 VALUE procval
= rb_proc_dup(self
);
136 return rb_obj_dup_setup(self
, procval
);
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
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.
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.
211 * define_method(:d) {}
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.
221 * define_method(:e, &proc {})
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.
230 * def self.def2(name, &body)
231 * define_method(name, &body)
236 * C.new.f(1,2) #=> ArgumentError
238 * The wrapper <i>def2</i> defines a method which has no tricks.
243 rb_proc_lambda_p(VALUE procval
)
246 GetProcPtr(procval
, proc
);
248 return RBOOL(proc
->is_lambda
);
254 binding_free(void *ptr
)
256 RUBY_FREE_ENTER("binding");
258 RUBY_FREE_LEAVE("binding");
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
);
271 binding_memsize(const void *ptr
)
273 return sizeof(rb_binding_t
);
276 const rb_data_type_t ruby_binding_data_type
= {
279 binding_mark_and_move
,
282 binding_mark_and_move
,
284 0, 0, RUBY_TYPED_WB_PROTECTED
| RUBY_TYPED_FREE_IMMEDIATELY
288 rb_binding_alloc(VALUE klass
)
292 obj
= TypedData_Make_Struct(klass
, rb_binding_t
, &ruby_binding_data_type
, bind
);
294 rb_yjit_collect_binding_alloc();
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
);
316 binding_clone(VALUE self
)
318 VALUE bindval
= binding_dup(self
);
319 return rb_obj_clone_setup(self
, bindval
, Qnil
);
325 rb_execution_context_t
*ec
= GET_EC();
326 return rb_vm_make_binding(ec
, ec
->cfp
);
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.
339 * def initialize(name, position)
341 * @position = position
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 ...
368 * validate(:name, :empty?, if: false) # skips validation
369 * validate(:name, :empty?, if: true) # performs validation
374 rb_f_binding(VALUE self
)
376 return rb_binding_new();
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)
391 * b = get_binding("hello")
392 * b.eval("param") #=> "hello"
396 bind_eval(int argc
, VALUE
*argv
, VALUE bindval
)
400 rb_scan_args(argc
, argv
, "12", &args
[0], &args
[2], &args
[3]);
402 return rb_f_eval(argc
+1, args
, Qnil
/* self will be searched in eval */);
406 get_local_variable_ptr(const rb_env_t
**envp
, ID lid
)
408 const rb_env_t
*env
= *envp
;
410 if (!VM_ENV_FLAGS(env
->ep
, VM_FRAME_FLAG_CFRAME
)) {
411 if (VM_ENV_FLAGS(env
->ep
, VM_ENV_FLAG_ISOLATED
)) {
415 const rb_iseq_t
*iseq
= env
->iseq
;
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
);
441 } while ((env
= rb_vm_env_prev_env(env
)) != 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.
453 check_local_id(VALUE bindval
, volatile VALUE
*pname
)
455 ID lid
= rb_check_id(pname
);
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
));
465 if (!rb_is_local_name(name
)) {
466 rb_name_err_raise("wrong local variable name '%1$s' for %2$s",
476 * binding.local_variables -> Array
478 * Returns the names of the binding's local variables as symbols.
483 * binding.local_variables #=> [:a, :n]
487 * This method is the short version of the following code:
489 * binding.eval("local_variables")
493 bind_local_variables(VALUE bindval
)
495 const rb_binding_t
*bind
;
498 GetBindingPtr(bindval
, bind
);
499 env
= VM_ENV_ENVVAL_PTR(vm_block_ep(&bind
->block
));
500 return rb_vm_env_local_variables(env
);
505 * binding.local_variable_get(symbol) -> obj
507 * Returns the value of the local variable +symbol+.
511 * binding.local_variable_get(:a) #=> 1
512 * binding.local_variable_get(:b) #=> NameError
515 * This method is the short version of the following code:
517 * binding.eval("#{symbol}")
521 bind_local_variable_get(VALUE bindval
, VALUE sym
)
523 ID lid
= check_local_id(bindval
, &sym
);
524 const rb_binding_t
*bind
;
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
) {
539 rb_name_err_raise("local variable '%1$s' is not defined for %2$s",
541 UNREACHABLE_RETURN(Qundef
);
546 * binding.local_variable_set(symbol, obj) -> obj
548 * Set local variable named +symbol+ as +obj+.
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
563 * This method behaves similarly to the following code:
565 * binding.eval("#{symbol} = #{obj}")
567 * if +obj+ can be dumped in Ruby code.
570 bind_local_variable_set(VALUE bindval
, VALUE sym
, VALUE val
)
572 ID lid
= check_local_id(bindval
, &sym
);
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
));
588 rb_yjit_collect_binding_set();
591 RB_OBJ_WRITE(env
, ptr
, val
);
598 * binding.local_variable_defined?(symbol) -> obj
600 * Returns +true+ if a local variable +symbol+ exists.
604 * binding.local_variable_defined?(:a) #=> true
605 * binding.local_variable_defined?(:b) #=> false
608 * This method is the short version of the following code:
610 * binding.eval("defined?(#{symbol}) == 'local-variable'")
614 bind_local_variable_defined_p(VALUE bindval
, VALUE sym
)
616 ID lid
= check_local_id(bindval
, &sym
);
617 const rb_binding_t
*bind
;
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
));
629 * binding.receiver -> object
631 * Returns the bound receiver of the binding object.
634 bind_receiver(VALUE bindval
)
636 const rb_binding_t
*bind
;
637 GetBindingPtr(bindval
, bind
);
638 return vm_block_self(&bind
->block
);
643 * binding.source_location -> [String, Integer]
645 * Returns the Ruby source filename and line number of the binding object.
648 bind_location(VALUE bindval
)
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
);
660 cfunc_proc_new(VALUE klass
, VALUE ifunc
)
664 VALUE procval
= TypedData_Make_Struct(klass
, cfunc_proc_t
, &proc_data_type
, sproc
);
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 */
677 RB_OBJ_WRITE(procval
, &proc
->block
.as
.captured
.code
.ifunc
, ifunc
);
678 proc
->is_lambda
= TRUE
;
683 sym_proc_new(VALUE klass
, VALUE sym
)
685 VALUE procval
= rb_proc_alloc(klass
);
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
);
696 rb_vm_ifunc_new(rb_block_call_func_t func
, const void *data
, int min_argc
, int max_argc
)
699 struct vm_ifunc_argc argc
;
703 if (min_argc
< UNLIMITED_ARGUMENTS
||
704 #if SIZEOF_INT * 2 > SIZEOF_VALUE
705 min_argc
>= (int)(1U << (SIZEOF_VALUE
* CHAR_BIT
) / 2) ||
708 rb_raise(rb_eRangeError
, "minimum argument number out of range: %d",
711 if (max_argc
< UNLIMITED_ARGUMENTS
||
712 #if SIZEOF_INT * 2 > SIZEOF_VALUE
713 max_argc
>= (int)(1U << (SIZEOF_VALUE
* CHAR_BIT
) / 2) ||
716 rb_raise(rb_eRangeError
, "maximum argument number out of range: %d",
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
));
726 ifunc
->argc
= arity
.argc
;
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
);
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";
748 proc_new(VALUE klass
, int8_t is_lambda
)
751 const rb_execution_context_t
*ec
= GET_EC();
752 rb_control_frame_t
*cfp
= ec
->cfp
;
755 if ((block_handler
= rb_vm_frame_block_handler(cfp
)) == VM_BLOCK_HANDLER_NONE
) {
756 rb_raise(rb_eArgError
, proc_without_block
);
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
) {
768 VALUE newprocval
= rb_proc_dup(procval
);
769 RBASIC_SET_CLASS(newprocval
, klass
);
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
));
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
);
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
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
);
814 return proc_new(rb_cProc
, FALSE
);
819 * proc { |...| block } -> a_proc
821 * Equivalent to Proc.new.
827 return proc_new(rb_cProc
, FALSE
);
831 rb_block_lambda(void)
833 return proc_new(rb_cProc
, TRUE
);
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
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
) {
853 case block_handler_type_symbol
:
855 case block_handler_type_proc
:
856 if (rb_proc_lambda_p(VM_BH_TO_PROC(block_handler
))) {
860 case block_handler_type_ifunc
:
864 rb_raise(rb_eArgError
, "the lambda method requires a literal block");
869 * lambda { |...| block } -> a_proc
871 * Equivalent to Proc.new, except the resulting Proc objects check the
872 * number of parameters passed when called.
878 f_lambda_filter_non_literal();
879 return rb_block_lambda();
882 /* Document-method: Proc#===
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
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
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?.
934 proc_call(int argc
, VALUE
*argv
, VALUE procval
)
940 #if SIZEOF_LONG > SIZEOF_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
);
951 #define check_argc(argc) (argc)
955 rb_proc_call_kw(VALUE self
, VALUE args
, int kw_splat
)
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
);
970 rb_proc_call(VALUE self
, VALUE args
)
972 return rb_proc_call_kw(self
, args
, RB_NO_KEYWORDS
);
976 proc_to_block_handler(VALUE procval
)
978 return NIL_P(procval
) ? VM_BLOCK_HANDLER_NONE
: procval
;
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();
987 GetProcPtr(self
, proc
);
988 vret
= rb_vm_invoke_proc(ec
, proc
, argc
, argv
, kw_splat
, proc_to_block_handler(passed_procval
));
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
);
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
1042 proc_arity(VALUE self
)
1044 int arity
= rb_proc_arity(self
);
1045 return INT2FIX(arity
);
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
|| ISEQ_BODY(iseq
)->param
.flags
.forwardable
== 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);
1059 rb_vm_block_min_max_arity(const struct rb_block
*block
, int *max
)
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
);
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
;
1082 *max
= UNLIMITED_ARGUMENTS
;
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
1093 rb_proc_min_max_arity(VALUE self
, int *max
)
1096 GetProcPtr(self
, proc
);
1097 return rb_vm_block_min_max_arity(&proc
->block
, max
);
1101 rb_proc_arity(VALUE self
)
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;
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
);
1118 case block_handler_type_ifunc
:
1119 block
->type
= block_type_ifunc
;
1120 block
->as
.captured
= *VM_BH_TO_IFUNC_BLOCK(block_handler
);
1122 case block_handler_type_symbol
:
1123 block
->type
= block_type_symbol
;
1124 block
->as
.symbol
= VM_BH_TO_SYMBOL(block_handler
);
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)
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
:
1152 case block_handler_type_proc
:
1154 VALUE procval
= block_handler
;
1156 GetProcPtr(procval
, proc
);
1157 if (proc
->is_lambda
) return 0;
1158 if (min
!= max
) return 0;
1162 case block_handler_type_ifunc
:
1164 const struct vm_ifunc
*ifunc
= block
.as
.captured
.code
.ifunc
;
1165 if (ifunc
->flags
& IFUNC_YIELD_OPTIMIZABLE
) return 1;
1174 rb_block_arity(void)
1177 const rb_execution_context_t
*ec
= GET_EC();
1178 rb_control_frame_t
*cfp
= ec
->cfp
;
1179 VALUE block_handler
= rb_vm_frame_block_handler(cfp
);
1180 struct rb_block block
;
1182 if (block_handler
== VM_BLOCK_HANDLER_NONE
) {
1183 rb_raise(rb_eArgError
, "no block given");
1186 block_setup(&block
, block_handler
);
1188 switch (vm_block_type(&block
)) {
1189 case block_handler_type_symbol
:
1192 case block_handler_type_proc
:
1193 return rb_proc_arity(block_handler
);
1196 min
= rb_vm_block_min_max_arity(&block
, &max
);
1197 return max
!= UNLIMITED_ARGUMENTS
? min
: -min
-1;
1202 rb_block_min_max_arity(int *max
)
1204 const rb_execution_context_t
*ec
= GET_EC();
1205 rb_control_frame_t
*cfp
= ec
->cfp
;
1206 VALUE block_handler
= rb_vm_frame_block_handler(cfp
);
1207 struct rb_block block
;
1209 if (block_handler
== VM_BLOCK_HANDLER_NONE
) {
1210 rb_raise(rb_eArgError
, "no block given");
1213 block_setup(&block
, block_handler
);
1214 return rb_vm_block_min_max_arity(&block
, max
);
1218 rb_proc_get_iseq(VALUE self
, int *is_proc
)
1220 const rb_proc_t
*proc
;
1221 const struct rb_block
*block
;
1223 GetProcPtr(self
, proc
);
1224 block
= &proc
->block
;
1225 if (is_proc
) *is_proc
= !proc
->is_lambda
;
1227 switch (vm_block_type(block
)) {
1228 case block_type_iseq
:
1229 return rb_iseq_check(block
->as
.captured
.code
.iseq
);
1230 case block_type_proc
:
1231 return rb_proc_get_iseq(block
->as
.proc
, is_proc
);
1232 case block_type_ifunc
:
1234 const struct vm_ifunc
*ifunc
= block
->as
.captured
.code
.ifunc
;
1235 if (IS_METHOD_PROC_IFUNC(ifunc
)) {
1236 /* method(:foo).to_proc */
1237 if (is_proc
) *is_proc
= 0;
1238 return rb_method_iseq((VALUE
)ifunc
->data
);
1244 case block_type_symbol
:
1248 VM_UNREACHABLE(rb_proc_get_iseq
);
1253 * prc == other -> true or false
1254 * prc.eql?(other) -> true or false
1256 * Two procs are the same if, and only if, they were created from the same code block.
1258 * def return_block(&block)
1262 * def pass_block_twice(&block)
1263 * [return_block(&block), return_block(&block)]
1266 * block1, block2 = pass_block_twice { puts 'test' }
1267 * # Blocks might be instantiated into Proc's lazily, so they may, or may not,
1268 * # be the same object.
1269 * # But they are produced from the same code block, so they are equal
1273 * # Another Proc will never be equal, even if the code is the "same"
1274 * block1 == proc { puts 'test' }
1279 proc_eq(VALUE self
, VALUE other
)
1281 const rb_proc_t
*self_proc
, *other_proc
;
1282 const struct rb_block
*self_block
, *other_block
;
1284 if (rb_obj_class(self
) != rb_obj_class(other
)) {
1288 GetProcPtr(self
, self_proc
);
1289 GetProcPtr(other
, other_proc
);
1291 if (self_proc
->is_from_method
!= other_proc
->is_from_method
||
1292 self_proc
->is_lambda
!= other_proc
->is_lambda
) {
1296 self_block
= &self_proc
->block
;
1297 other_block
= &other_proc
->block
;
1299 if (vm_block_type(self_block
) != vm_block_type(other_block
)) {
1303 switch (vm_block_type(self_block
)) {
1304 case block_type_iseq
:
1305 if (self_block
->as
.captured
.ep
!= \
1306 other_block
->as
.captured
.ep
||
1307 self_block
->as
.captured
.code
.iseq
!= \
1308 other_block
->as
.captured
.code
.iseq
) {
1312 case block_type_ifunc
:
1313 if (self_block
->as
.captured
.ep
!= \
1314 other_block
->as
.captured
.ep
||
1315 self_block
->as
.captured
.code
.ifunc
!= \
1316 other_block
->as
.captured
.code
.ifunc
) {
1320 case block_type_proc
:
1321 if (self_block
->as
.proc
!= other_block
->as
.proc
) {
1325 case block_type_symbol
:
1326 if (self_block
->as
.symbol
!= other_block
->as
.symbol
) {
1336 iseq_location(const rb_iseq_t
*iseq
)
1340 if (!iseq
) return Qnil
;
1341 rb_iseq_check(iseq
);
1342 loc
[0] = rb_iseq_path(iseq
);
1343 loc
[1] = RB_INT2NUM(ISEQ_BODY(iseq
)->location
.first_lineno
);
1345 return rb_ary_new4(2, loc
);
1349 rb_iseq_location(const rb_iseq_t
*iseq
)
1351 return iseq_location(iseq
);
1356 * prc.source_location -> [String, Integer]
1358 * Returns the Ruby source filename and line number containing this proc
1359 * or +nil+ if this proc was not defined in Ruby (i.e. native).
1363 rb_proc_location(VALUE self
)
1365 return iseq_location(rb_proc_get_iseq(self
, 0));
1369 rb_unnamed_parameters(int arity
)
1371 VALUE a
, param
= rb_ary_new2((arity
< 0) ? -arity
: arity
);
1372 int n
= (arity
< 0) ? ~arity
: arity
;
1374 CONST_ID(req
, "req");
1375 a
= rb_ary_new3(1, ID2SYM(req
));
1378 rb_ary_push(param
, a
);
1381 CONST_ID(rest
, "rest");
1382 rb_ary_store(param
, ~arity
, rb_ary_new3(1, ID2SYM(rest
)));
1389 * prc.parameters(lambda: nil) -> array
1391 * Returns the parameter information of this proc. If the lambda
1392 * keyword is provided and not nil, treats the proc as a lambda if
1393 * true and as a non-lambda if false.
1395 * prc = proc{|x, y=42, *other|}
1396 * prc.parameters #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
1397 * prc = lambda{|x, y=42, *other|}
1398 * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1399 * prc = proc{|x, y=42, *other|}
1400 * prc.parameters(lambda: true) #=> [[:req, :x], [:opt, :y], [:rest, :other]]
1401 * prc = lambda{|x, y=42, *other|}
1402 * prc.parameters(lambda: false) #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
1406 rb_proc_parameters(int argc
, VALUE
*argv
, VALUE self
)
1408 static ID keyword_ids
[1];
1412 const rb_iseq_t
*iseq
;
1414 iseq
= rb_proc_get_iseq(self
, &is_proc
);
1416 if (!keyword_ids
[0]) {
1417 CONST_ID(keyword_ids
[0], "lambda");
1420 rb_scan_args(argc
, argv
, "0:", &opt
);
1422 rb_get_kwargs(opt
, keyword_ids
, 0, 1, kwargs
);
1424 if (!NIL_P(lambda
)) {
1425 is_proc
= !RTEST(lambda
);
1430 return rb_unnamed_parameters(rb_proc_arity(self
));
1432 return rb_iseq_parameters(iseq
, is_proc
);
1436 rb_hash_proc(st_index_t hash
, VALUE prc
)
1439 GetProcPtr(prc
, proc
);
1440 hash
= rb_hash_uint(hash
, (st_index_t
)proc
->block
.as
.captured
.code
.val
);
1441 hash
= rb_hash_uint(hash
, (st_index_t
)proc
->block
.as
.captured
.self
);
1442 return rb_hash_uint(hash
, (st_index_t
)proc
->block
.as
.captured
.ep
);
1450 * Returns a Proc object which calls the method with name of +self+
1451 * on the first parameter and passes the remaining parameters to the method.
1453 * proc = :to_s.to_proc # => #<Proc:0x000001afe0e48680(&:to_s) (lambda)>
1454 * proc.call(1000) # => "1000"
1455 * proc.call(1000, 16) # => "3e8"
1456 * (1..3).collect(&:to_s) # => ["1", "2", "3"]
1461 rb_sym_to_proc(VALUE sym
)
1463 static VALUE sym_proc_cache
= Qfalse
;
1464 enum {SYM_PROC_CACHE_SIZE
= 67};
1469 if (!sym_proc_cache
) {
1470 sym_proc_cache
= rb_ary_hidden_new(SYM_PROC_CACHE_SIZE
* 2);
1471 rb_vm_register_global_object(sym_proc_cache
);
1472 rb_ary_store(sym_proc_cache
, SYM_PROC_CACHE_SIZE
*2 - 1, Qnil
);
1476 index
= (id
% SYM_PROC_CACHE_SIZE
) << 1;
1478 if (RARRAY_AREF(sym_proc_cache
, index
) == sym
) {
1479 return RARRAY_AREF(sym_proc_cache
, index
+ 1);
1482 proc
= sym_proc_new(rb_cProc
, ID2SYM(id
));
1483 RARRAY_ASET(sym_proc_cache
, index
, sym
);
1484 RARRAY_ASET(sym_proc_cache
, index
+ 1, proc
);
1491 * prc.hash -> integer
1493 * Returns a hash value corresponding to proc body.
1495 * See also Object#hash.
1499 proc_hash(VALUE self
)
1502 hash
= rb_hash_start(0);
1503 hash
= rb_hash_proc(hash
, self
);
1504 hash
= rb_hash_end(hash
);
1505 return ST2FIX(hash
);
1509 rb_block_to_s(VALUE self
, const struct rb_block
*block
, const char *additional_info
)
1511 VALUE cname
= rb_obj_class(self
);
1512 VALUE str
= rb_sprintf("#<%"PRIsVALUE
":", cname
);
1515 switch (vm_block_type(block
)) {
1516 case block_type_proc
:
1517 block
= vm_proc_block(block
->as
.proc
);
1519 case block_type_iseq
:
1521 const rb_iseq_t
*iseq
= rb_iseq_check(block
->as
.captured
.code
.iseq
);
1522 rb_str_catf(str
, "%p %"PRIsVALUE
":%d", (void *)self
,
1524 ISEQ_BODY(iseq
)->location
.first_lineno
);
1527 case block_type_symbol
:
1528 rb_str_catf(str
, "%p(&%+"PRIsVALUE
")", (void *)self
, block
->as
.symbol
);
1530 case block_type_ifunc
:
1531 rb_str_catf(str
, "%p", (void *)block
->as
.captured
.code
.ifunc
);
1535 if (additional_info
) rb_str_cat_cstr(str
, additional_info
);
1536 rb_str_cat_cstr(str
, ">");
1542 * prc.to_s -> string
1544 * Returns the unique identifier for this proc, along with
1545 * an indication of where the proc was defined.
1549 proc_to_s(VALUE self
)
1551 const rb_proc_t
*proc
;
1552 GetProcPtr(self
, proc
);
1553 return rb_block_to_s(self
, &proc
->block
, proc
->is_lambda
? " (lambda)" : NULL
);
1558 * prc.to_proc -> proc
1560 * Part of the protocol for converting objects to Proc objects.
1561 * Instances of class Proc simply return themselves.
1565 proc_to_proc(VALUE self
)
1571 bm_mark_and_move(void *ptr
)
1573 struct METHOD
*data
= ptr
;
1574 rb_gc_mark_and_move((VALUE
*)&data
->recv
);
1575 rb_gc_mark_and_move((VALUE
*)&data
->klass
);
1576 rb_gc_mark_and_move((VALUE
*)&data
->iclass
);
1577 rb_gc_mark_and_move((VALUE
*)&data
->owner
);
1578 rb_gc_mark_and_move_ptr((rb_method_entry_t
**)&data
->me
);
1581 static const rb_data_type_t method_data_type
= {
1585 RUBY_TYPED_DEFAULT_FREE
,
1586 NULL
, // No external memory to report,
1589 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
| RUBY_TYPED_WB_PROTECTED
| RUBY_TYPED_EMBEDDABLE
1593 rb_obj_is_method(VALUE m
)
1595 return RBOOL(rb_typeddata_is_kind_of(m
, &method_data_type
));
1599 respond_to_missing_p(VALUE klass
, VALUE obj
, VALUE sym
, int scope
)
1601 /* TODO: merge with obj_respond_to() */
1602 ID rmiss
= idRespond_to_missing
;
1604 if (UNDEF_P(obj
)) return 0;
1605 if (rb_method_basic_definition_p(klass
, rmiss
)) return 0;
1606 return RTEST(rb_funcall(obj
, rmiss
, 2, sym
, RBOOL(!scope
)));
1611 mnew_missing(VALUE klass
, VALUE obj
, ID id
, VALUE mclass
)
1613 struct METHOD
*data
;
1614 VALUE method
= TypedData_Make_Struct(mclass
, struct METHOD
, &method_data_type
, data
);
1615 rb_method_entry_t
*me
;
1616 rb_method_definition_t
*def
;
1618 RB_OBJ_WRITE(method
, &data
->recv
, obj
);
1619 RB_OBJ_WRITE(method
, &data
->klass
, klass
);
1620 RB_OBJ_WRITE(method
, &data
->owner
, klass
);
1622 def
= ZALLOC(rb_method_definition_t
);
1623 def
->type
= VM_METHOD_TYPE_MISSING
;
1624 def
->original_id
= id
;
1626 me
= rb_method_entry_create(id
, klass
, METHOD_VISI_UNDEF
, def
);
1628 RB_OBJ_WRITE(method
, &data
->me
, me
);
1634 mnew_missing_by_name(VALUE klass
, VALUE obj
, VALUE
*name
, int scope
, VALUE mclass
)
1636 VALUE vid
= rb_str_intern(*name
);
1638 if (!respond_to_missing_p(klass
, obj
, vid
, scope
)) return Qfalse
;
1639 return mnew_missing(klass
, obj
, SYM2ID(vid
), mclass
);
1643 mnew_internal(const rb_method_entry_t
*me
, VALUE klass
, VALUE iclass
,
1644 VALUE obj
, ID id
, VALUE mclass
, int scope
, int error
)
1646 struct METHOD
*data
;
1648 const rb_method_entry_t
*original_me
= me
;
1649 rb_method_visibility_t visi
= METHOD_VISI_UNDEF
;
1652 if (UNDEFINED_METHOD_ENTRY_P(me
)) {
1653 if (respond_to_missing_p(klass
, obj
, ID2SYM(id
), scope
)) {
1654 return mnew_missing(klass
, obj
, id
, mclass
);
1656 if (!error
) return Qnil
;
1657 rb_print_undef(klass
, id
, METHOD_VISI_UNDEF
);
1659 if (visi
== METHOD_VISI_UNDEF
) {
1660 visi
= METHOD_ENTRY_VISI(me
);
1661 RUBY_ASSERT(visi
!= METHOD_VISI_UNDEF
); /* !UNDEFINED_METHOD_ENTRY_P(me) */
1662 if (scope
&& (visi
!= METHOD_VISI_PUBLIC
)) {
1663 if (!error
) return Qnil
;
1664 rb_print_inaccessible(klass
, id
, visi
);
1667 if (me
->def
->type
== VM_METHOD_TYPE_ZSUPER
) {
1668 if (me
->defined_class
) {
1669 VALUE klass
= RCLASS_SUPER(RCLASS_ORIGIN(me
->defined_class
));
1670 id
= me
->def
->original_id
;
1671 me
= (rb_method_entry_t
*)rb_callable_method_entry_with_refinements(klass
, id
, &iclass
);
1674 VALUE klass
= RCLASS_SUPER(RCLASS_ORIGIN(me
->owner
));
1675 id
= me
->def
->original_id
;
1676 me
= rb_method_entry_without_refinements(klass
, id
, &iclass
);
1681 method
= TypedData_Make_Struct(mclass
, struct METHOD
, &method_data_type
, data
);
1684 RB_OBJ_WRITE(method
, &data
->recv
, Qundef
);
1685 RB_OBJ_WRITE(method
, &data
->klass
, Qundef
);
1688 RB_OBJ_WRITE(method
, &data
->recv
, obj
);
1689 RB_OBJ_WRITE(method
, &data
->klass
, klass
);
1691 RB_OBJ_WRITE(method
, &data
->iclass
, iclass
);
1692 RB_OBJ_WRITE(method
, &data
->owner
, original_me
->owner
);
1693 RB_OBJ_WRITE(method
, &data
->me
, me
);
1699 mnew_from_me(const rb_method_entry_t
*me
, VALUE klass
, VALUE iclass
,
1700 VALUE obj
, ID id
, VALUE mclass
, int scope
)
1702 return mnew_internal(me
, klass
, iclass
, obj
, id
, mclass
, scope
, TRUE
);
1706 mnew_callable(VALUE klass
, VALUE obj
, ID id
, VALUE mclass
, int scope
)
1708 const rb_method_entry_t
*me
;
1709 VALUE iclass
= Qnil
;
1711 ASSUME(!UNDEF_P(obj
));
1712 me
= (rb_method_entry_t
*)rb_callable_method_entry_with_refinements(klass
, id
, &iclass
);
1713 return mnew_from_me(me
, klass
, iclass
, obj
, id
, mclass
, scope
);
1717 mnew_unbound(VALUE klass
, ID id
, VALUE mclass
, int scope
)
1719 const rb_method_entry_t
*me
;
1720 VALUE iclass
= Qnil
;
1722 me
= rb_method_entry_with_refinements(klass
, id
, &iclass
);
1723 return mnew_from_me(me
, klass
, iclass
, Qundef
, id
, mclass
, scope
);
1727 method_entry_defined_class(const rb_method_entry_t
*me
)
1729 VALUE defined_class
= me
->defined_class
;
1730 return defined_class
? defined_class
: me
->owner
;
1733 /**********************************************************************
1735 * Document-class: Method
1737 * Method objects are created by Object#method, and are associated
1738 * with a particular object (not just with a class). They may be
1739 * used to invoke the method within the object, and as a block
1740 * associated with an iterator. They may also be unbound from one
1741 * object (creating an UnboundMethod) and bound to another.
1749 * meth = thing.method(:square)
1751 * meth.call(9) #=> 81
1752 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1754 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
1757 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1758 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1763 * meth.eql?(other_meth) -> true or false
1764 * meth == other_meth -> true or false
1766 * Two method objects are equal if they are bound to the same
1767 * object and refer to the same method definition and the classes
1768 * defining the methods are the same class or module.
1772 method_eq(VALUE method
, VALUE other
)
1774 struct METHOD
*m1
, *m2
;
1775 VALUE klass1
, klass2
;
1777 if (!rb_obj_is_method(other
))
1779 if (CLASS_OF(method
) != CLASS_OF(other
))
1782 Check_TypedStruct(method
, &method_data_type
);
1783 m1
= (struct METHOD
*)RTYPEDDATA_GET_DATA(method
);
1784 m2
= (struct METHOD
*)RTYPEDDATA_GET_DATA(other
);
1786 klass1
= method_entry_defined_class(m1
->me
);
1787 klass2
= method_entry_defined_class(m2
->me
);
1789 if (!rb_method_entry_eq(m1
->me
, m2
->me
) ||
1791 m1
->klass
!= m2
->klass
||
1792 m1
->recv
!= m2
->recv
) {
1801 * meth.eql?(other_meth) -> true or false
1802 * meth == other_meth -> true or false
1804 * Two unbound method objects are equal if they refer to the same
1805 * method definition.
1807 * Array.instance_method(:each_slice) == Enumerable.instance_method(:each_slice)
1810 * Array.instance_method(:sum) == Enumerable.instance_method(:sum)
1811 * #=> false, Array redefines the method for efficiency
1813 #define unbound_method_eq method_eq
1817 * meth.hash -> integer
1819 * Returns a hash value corresponding to the method object.
1821 * See also Object#hash.
1825 method_hash(VALUE method
)
1830 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, m
);
1831 hash
= rb_hash_start((st_index_t
)m
->recv
);
1832 hash
= rb_hash_method_entry(hash
, m
->me
);
1833 hash
= rb_hash_end(hash
);
1835 return ST2FIX(hash
);
1840 * meth.unbind -> unbound_method
1842 * Dissociates <i>meth</i> from its current receiver. The resulting
1843 * UnboundMethod can subsequently be bound to a new object of the
1844 * same class (see UnboundMethod).
1848 method_unbind(VALUE obj
)
1851 struct METHOD
*orig
, *data
;
1853 TypedData_Get_Struct(obj
, struct METHOD
, &method_data_type
, orig
);
1854 method
= TypedData_Make_Struct(rb_cUnboundMethod
, struct METHOD
,
1855 &method_data_type
, data
);
1856 RB_OBJ_WRITE(method
, &data
->recv
, Qundef
);
1857 RB_OBJ_WRITE(method
, &data
->klass
, Qundef
);
1858 RB_OBJ_WRITE(method
, &data
->iclass
, orig
->iclass
);
1859 RB_OBJ_WRITE(method
, &data
->owner
, orig
->me
->owner
);
1860 RB_OBJ_WRITE(method
, &data
->me
, rb_method_entry_clone(orig
->me
));
1867 * meth.receiver -> object
1869 * Returns the bound receiver of the method object.
1871 * (1..3).method(:map).receiver # => 1..3
1875 method_receiver(VALUE obj
)
1877 struct METHOD
*data
;
1879 TypedData_Get_Struct(obj
, struct METHOD
, &method_data_type
, data
);
1885 * meth.name -> symbol
1887 * Returns the name of the method.
1891 method_name(VALUE obj
)
1893 struct METHOD
*data
;
1895 TypedData_Get_Struct(obj
, struct METHOD
, &method_data_type
, data
);
1896 return ID2SYM(data
->me
->called_id
);
1901 * meth.original_name -> symbol
1903 * Returns the original name of the method.
1909 * C.instance_method(:bar).original_name # => :foo
1913 method_original_name(VALUE obj
)
1915 struct METHOD
*data
;
1917 TypedData_Get_Struct(obj
, struct METHOD
, &method_data_type
, data
);
1918 return ID2SYM(data
->me
->def
->original_id
);
1923 * meth.owner -> class_or_module
1925 * Returns the class or module on which this method is defined.
1928 * meth.owner.instance_methods(false).include?(meth.name) # => true
1930 * holds as long as the method is not removed/undefined/replaced,
1931 * (with private_instance_methods instead of instance_methods if the method
1934 * See also Method#receiver.
1936 * (1..3).method(:map).owner #=> Enumerable
1940 method_owner(VALUE obj
)
1942 struct METHOD
*data
;
1943 TypedData_Get_Struct(obj
, struct METHOD
, &method_data_type
, data
);
1948 rb_method_name_error(VALUE klass
, VALUE str
)
1950 #define MSG(s) rb_fstring_lit("undefined method '%1$s' for"s" '%2$s'")
1954 if (RCLASS_SINGLETON_P(c
)) {
1955 VALUE obj
= RCLASS_ATTACHED_OBJECT(klass
);
1957 switch (BUILTIN_TYPE(obj
)) {
1966 else if (RB_TYPE_P(c
, T_MODULE
)) {
1972 rb_name_err_raise_str(s
, c
, str
);
1977 obj_method(VALUE obj
, VALUE vid
, int scope
)
1979 ID id
= rb_check_id(&vid
);
1980 const VALUE klass
= CLASS_OF(obj
);
1981 const VALUE mclass
= rb_cMethod
;
1984 VALUE m
= mnew_missing_by_name(klass
, obj
, &vid
, scope
, mclass
);
1986 rb_method_name_error(klass
, vid
);
1988 return mnew_callable(klass
, obj
, id
, mclass
, scope
);
1993 * obj.method(sym) -> method
1995 * Looks up the named method as a receiver in <i>obj</i>, returning a
1996 * Method object (or raising NameError). The Method object acts as a
1997 * closure in <i>obj</i>'s object instance, so instance variables and
1998 * the value of <code>self</code> remain available.
2005 * "Hello, @iv = #{@iv}"
2010 * m = k.method(:hello)
2011 * m.call #=> "Hello, @iv = 99"
2013 * l = Demo.new('Fred')
2014 * m = l.method("hello")
2015 * m.call #=> "Hello, @iv = Fred"
2017 * Note that Method implements <code>to_proc</code> method, which
2018 * means it can be used with iterators.
2020 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
2022 * out = File.open('test.txt', 'w')
2023 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
2026 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
2027 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2031 rb_obj_method(VALUE obj
, VALUE vid
)
2033 return obj_method(obj
, vid
, FALSE
);
2038 * obj.public_method(sym) -> method
2040 * Similar to _method_, searches public method only.
2044 rb_obj_public_method(VALUE obj
, VALUE vid
)
2046 return obj_method(obj
, vid
, TRUE
);
2051 * obj.singleton_method(sym) -> method
2053 * Similar to _method_, searches singleton method only.
2060 * "Hello, @iv = #{@iv}"
2066 * "Hi, @iv = #{@iv}"
2068 * m = k.singleton_method(:hi)
2069 * m.call #=> "Hi, @iv = 99"
2070 * m = k.singleton_method(:hello) #=> NameError
2074 rb_obj_singleton_method(VALUE obj
, VALUE vid
)
2076 VALUE klass
= rb_singleton_class_get(obj
);
2077 ID id
= rb_check_id(&vid
);
2080 NIL_P(klass
= RCLASS_ORIGIN(klass
)) ||
2081 !NIL_P(rb_special_singleton_class(obj
))) {
2085 VALUE m
= mnew_missing_by_name(klass
, obj
, &vid
, FALSE
, rb_cMethod
);
2087 /* else goto undef; */
2090 const rb_method_entry_t
*me
= rb_method_entry_at(klass
, id
);
2093 if (UNDEFINED_METHOD_ENTRY_P(me
)) {
2096 else if (UNDEFINED_REFINED_METHOD_P(me
->def
)) {
2100 return mnew_from_me(me
, klass
, klass
, obj
, id
, rb_cMethod
, FALSE
);
2105 rb_name_err_raise("undefined singleton method '%1$s' for '%2$s'",
2107 UNREACHABLE_RETURN(Qundef
);
2112 * mod.instance_method(symbol) -> unbound_method
2114 * Returns an +UnboundMethod+ representing the given
2115 * instance method in _mod_.
2118 * def do_a() print "there, "; end
2119 * def do_d() print "Hello "; end
2120 * def do_e() print "!\n"; end
2121 * def do_v() print "Dave"; end
2123 * "a" => instance_method(:do_a),
2124 * "d" => instance_method(:do_d),
2125 * "e" => instance_method(:do_e),
2126 * "v" => instance_method(:do_v)
2128 * def interpret(string)
2129 * string.each_char {|b| Dispatcher[b].bind(self).call }
2133 * interpreter = Interpreter.new
2134 * interpreter.interpret('dave')
2136 * <em>produces:</em>
2138 * Hello there, Dave!
2142 rb_mod_instance_method(VALUE mod
, VALUE vid
)
2144 ID id
= rb_check_id(&vid
);
2146 rb_method_name_error(mod
, vid
);
2148 return mnew_unbound(mod
, id
, rb_cUnboundMethod
, FALSE
);
2153 * mod.public_instance_method(symbol) -> unbound_method
2155 * Similar to _instance_method_, searches public method only.
2159 rb_mod_public_instance_method(VALUE mod
, VALUE vid
)
2161 ID id
= rb_check_id(&vid
);
2163 rb_method_name_error(mod
, vid
);
2165 return mnew_unbound(mod
, id
, rb_cUnboundMethod
, TRUE
);
2169 rb_mod_define_method_with_visibility(int argc
, VALUE
*argv
, VALUE mod
, const struct rb_scope_visi_struct
* scope_visi
)
2174 int is_method
= FALSE
;
2176 rb_check_arity(argc
, 1, 2);
2178 id
= rb_check_id(&name
);
2180 body
= rb_block_lambda();
2185 if (rb_obj_is_method(body
)) {
2188 else if (rb_obj_is_proc(body
)) {
2192 rb_raise(rb_eTypeError
,
2193 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
2194 rb_obj_classname(body
));
2197 if (!id
) id
= rb_to_id(name
);
2200 struct METHOD
*method
= (struct METHOD
*)RTYPEDDATA_GET_DATA(body
);
2201 if (method
->me
->owner
!= mod
&& !RB_TYPE_P(method
->me
->owner
, T_MODULE
) &&
2202 !RTEST(rb_class_inherited_p(mod
, method
->me
->owner
))) {
2203 if (RCLASS_SINGLETON_P(method
->me
->owner
)) {
2204 rb_raise(rb_eTypeError
,
2205 "can't bind singleton method to a different class");
2208 rb_raise(rb_eTypeError
,
2209 "bind argument must be a subclass of % "PRIsVALUE
,
2213 rb_method_entry_set(mod
, id
, method
->me
, scope_visi
->method_visi
);
2214 if (scope_visi
->module_func
) {
2215 rb_method_entry_set(rb_singleton_class(mod
), id
, method
->me
, METHOD_VISI_PUBLIC
);
2220 VALUE procval
= rb_proc_dup(body
);
2221 if (vm_proc_iseq(procval
) != NULL
) {
2223 GetProcPtr(procval
, proc
);
2224 proc
->is_lambda
= TRUE
;
2225 proc
->is_from_method
= TRUE
;
2227 rb_add_method(mod
, id
, VM_METHOD_TYPE_BMETHOD
, (void *)procval
, scope_visi
->method_visi
);
2228 if (scope_visi
->module_func
) {
2229 rb_add_method(rb_singleton_class(mod
), id
, VM_METHOD_TYPE_BMETHOD
, (void *)body
, METHOD_VISI_PUBLIC
);
2238 * define_method(symbol, method) -> symbol
2239 * define_method(symbol) { block } -> symbol
2241 * Defines an instance method in the receiver. The _method_
2242 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2243 * If a block is specified, it is used as the method body.
2244 * If a block or the _method_ parameter has parameters,
2245 * they're used as method parameters.
2246 * This block is evaluated using #instance_eval.
2252 * def create_method(name, &block)
2253 * self.class.define_method(name, &block)
2255 * define_method(:wilma) { puts "Charge it!" }
2256 * define_method(:flint) {|name| puts "I'm #{name}!"}
2259 * define_method(:barney, instance_method(:fred))
2265 * a.create_method(:betty) { p self }
2268 * <em>produces:</em>
2277 rb_mod_define_method(int argc
, VALUE
*argv
, VALUE mod
)
2279 const rb_cref_t
*cref
= rb_vm_cref_in_context(mod
, mod
);
2280 const rb_scope_visibility_t default_scope_visi
= {METHOD_VISI_PUBLIC
, FALSE
};
2281 const rb_scope_visibility_t
*scope_visi
= &default_scope_visi
;
2284 scope_visi
= CREF_SCOPE_VISI(cref
);
2287 return rb_mod_define_method_with_visibility(argc
, argv
, mod
, scope_visi
);
2292 * define_singleton_method(symbol, method) -> symbol
2293 * define_singleton_method(symbol) { block } -> symbol
2295 * Defines a public singleton method in the receiver. The _method_
2296 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2297 * If a block is specified, it is used as the method body.
2298 * If a block or a method has parameters, they're used as method parameters.
2307 * A.define_singleton_method(:who_am_i) do
2308 * "I am: #{class_name}"
2310 * A.who_am_i # ==> "I am: A"
2313 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
2314 * guy.hello #=> "Bob: Hello there!"
2317 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
2318 * chris.greet("Hi") #=> "Hi, I'm Chris!"
2322 rb_obj_define_method(int argc
, VALUE
*argv
, VALUE obj
)
2324 VALUE klass
= rb_singleton_class(obj
);
2325 const rb_scope_visibility_t scope_visi
= {METHOD_VISI_PUBLIC
, FALSE
};
2327 return rb_mod_define_method_with_visibility(argc
, argv
, klass
, &scope_visi
);
2331 * define_method(symbol, method) -> symbol
2332 * define_method(symbol) { block } -> symbol
2334 * Defines a global function by _method_ or the block.
2338 top_define_method(int argc
, VALUE
*argv
, VALUE obj
)
2340 return rb_mod_define_method(argc
, argv
, rb_top_main_class("define_method"));
2345 * method.clone -> new_method
2347 * Returns a clone of this method.
2355 * m = A.new.method(:foo)
2357 * n = m.clone.call # => "bar"
2361 method_clone(VALUE self
)
2364 struct METHOD
*orig
, *data
;
2366 TypedData_Get_Struct(self
, struct METHOD
, &method_data_type
, orig
);
2367 clone
= TypedData_Make_Struct(CLASS_OF(self
), struct METHOD
, &method_data_type
, data
);
2368 rb_obj_clone_setup(self
, clone
, Qnil
);
2369 RB_OBJ_WRITE(clone
, &data
->recv
, orig
->recv
);
2370 RB_OBJ_WRITE(clone
, &data
->klass
, orig
->klass
);
2371 RB_OBJ_WRITE(clone
, &data
->iclass
, orig
->iclass
);
2372 RB_OBJ_WRITE(clone
, &data
->owner
, orig
->owner
);
2373 RB_OBJ_WRITE(clone
, &data
->me
, rb_method_entry_clone(orig
->me
));
2379 method_dup(VALUE self
)
2382 struct METHOD
*orig
, *data
;
2384 TypedData_Get_Struct(self
, struct METHOD
, &method_data_type
, orig
);
2385 clone
= TypedData_Make_Struct(CLASS_OF(self
), struct METHOD
, &method_data_type
, data
);
2386 rb_obj_dup_setup(self
, clone
);
2387 RB_OBJ_WRITE(clone
, &data
->recv
, orig
->recv
);
2388 RB_OBJ_WRITE(clone
, &data
->klass
, orig
->klass
);
2389 RB_OBJ_WRITE(clone
, &data
->iclass
, orig
->iclass
);
2390 RB_OBJ_WRITE(clone
, &data
->owner
, orig
->owner
);
2391 RB_OBJ_WRITE(clone
, &data
->me
, rb_method_entry_clone(orig
->me
));
2395 /* Document-method: Method#===
2398 * method === obj -> result_of_method
2400 * Invokes the method with +obj+ as the parameter like #call.
2401 * This allows a method object to be the target of a +when+ clause
2402 * in a case statement.
2407 * when Prime.method(:prime?)
2413 /* Document-method: Method#[]
2416 * meth[args, ...] -> obj
2418 * Invokes the <i>meth</i> with the specified arguments, returning the
2419 * method's return value, like #call.
2421 * m = 12.method("+")
2428 * meth.call(args, ...) -> obj
2430 * Invokes the <i>meth</i> with the specified arguments, returning the
2431 * method's return value.
2433 * m = 12.method("+")
2439 rb_method_call_pass_called_kw(int argc
, const VALUE
*argv
, VALUE method
)
2441 return rb_method_call_kw(argc
, argv
, method
, RB_PASS_CALLED_KEYWORDS
);
2445 rb_method_call_kw(int argc
, const VALUE
*argv
, VALUE method
, int kw_splat
)
2447 VALUE procval
= rb_block_given_p() ? rb_block_proc() : Qnil
;
2448 return rb_method_call_with_block_kw(argc
, argv
, method
, procval
, kw_splat
);
2452 rb_method_call(int argc
, const VALUE
*argv
, VALUE method
)
2454 VALUE procval
= rb_block_given_p() ? rb_block_proc() : Qnil
;
2455 return rb_method_call_with_block(argc
, argv
, method
, procval
);
2458 static const rb_callable_method_entry_t
*
2459 method_callable_method_entry(const struct METHOD
*data
)
2461 if (data
->me
->defined_class
== 0) rb_bug("method_callable_method_entry: not callable.");
2462 return (const rb_callable_method_entry_t
*)data
->me
;
2466 call_method_data(rb_execution_context_t
*ec
, const struct METHOD
*data
,
2467 int argc
, const VALUE
*argv
, VALUE passed_procval
, int kw_splat
)
2469 vm_passed_block_handler_set(ec
, proc_to_block_handler(passed_procval
));
2470 return rb_vm_call_kw(ec
, data
->recv
, data
->me
->called_id
, argc
, argv
,
2471 method_callable_method_entry(data
), kw_splat
);
2475 rb_method_call_with_block_kw(int argc
, const VALUE
*argv
, VALUE method
, VALUE passed_procval
, int kw_splat
)
2477 const struct METHOD
*data
;
2478 rb_execution_context_t
*ec
= GET_EC();
2480 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2481 if (UNDEF_P(data
->recv
)) {
2482 rb_raise(rb_eTypeError
, "can't call unbound method; bind first");
2484 return call_method_data(ec
, data
, argc
, argv
, passed_procval
, kw_splat
);
2488 rb_method_call_with_block(int argc
, const VALUE
*argv
, VALUE method
, VALUE passed_procval
)
2490 return rb_method_call_with_block_kw(argc
, argv
, method
, passed_procval
, RB_NO_KEYWORDS
);
2493 /**********************************************************************
2495 * Document-class: UnboundMethod
2497 * Ruby supports two forms of objectified methods. Class Method is
2498 * used to represent methods that are associated with a particular
2499 * object: these method objects are bound to that object. Bound
2500 * method objects for an object can be created using Object#method.
2502 * Ruby also supports unbound methods; methods objects that are not
2503 * associated with a particular object. These can be created either
2504 * by calling Module#instance_method or by calling #unbind on a bound
2505 * method object. The result of both of these is an UnboundMethod
2508 * Unbound methods can only be called after they are bound to an
2509 * object. That object must be a kind_of? the method's original
2516 * def initialize(side)
2521 * area_un = Square.instance_method(:area)
2523 * s = Square.new(12)
2524 * area = area_un.bind(s)
2527 * Unbound methods are a reference to the method at the time it was
2528 * objectified: subsequent changes to the underlying class will not
2529 * affect the unbound method.
2536 * um = Test.instance_method(:test)
2543 * t.test #=> :modified
2544 * um.bind(t).call #=> :original
2549 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
)
2551 VALUE methclass
= data
->owner
;
2552 VALUE iclass
= data
->me
->defined_class
;
2553 VALUE klass
= CLASS_OF(recv
);
2555 if (RB_TYPE_P(methclass
, T_MODULE
)) {
2556 VALUE refined_class
= rb_refinement_module_get_refined_class(methclass
);
2557 if (!NIL_P(refined_class
)) methclass
= refined_class
;
2559 if (!RB_TYPE_P(methclass
, T_MODULE
) && !RTEST(rb_obj_is_kind_of(recv
, methclass
))) {
2560 if (RCLASS_SINGLETON_P(methclass
)) {
2561 rb_raise(rb_eTypeError
,
2562 "singleton method called for a different object");
2565 rb_raise(rb_eTypeError
, "bind argument must be an instance of % "PRIsVALUE
,
2570 const rb_method_entry_t
*me
;
2572 me
= rb_method_entry_clone(data
->me
);
2578 if (RB_TYPE_P(me
->owner
, T_MODULE
)) {
2580 // if we didn't previously clone the method entry, then we need to clone it now
2581 // because this branch manipulates it in rb_method_entry_complement_defined_class
2582 me
= rb_method_entry_clone(me
);
2584 VALUE ic
= rb_class_search_ancestor(klass
, me
->owner
);
2590 klass
= rb_include_class_new(methclass
, klass
);
2592 me
= (const rb_method_entry_t
*) rb_method_entry_complement_defined_class(me
, me
->called_id
, klass
);
2595 *methclass_out
= methclass
;
2597 *iclass_out
= iclass
;
2603 * umeth.bind(obj) -> method
2605 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2606 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2611 * puts "In test, class = #{self.class}"
2620 * um = B.instance_method(:test)
2621 * bm = um.bind(C.new)
2623 * bm = um.bind(B.new)
2625 * bm = um.bind(A.new)
2628 * <em>produces:</em>
2630 * In test, class = C
2631 * In test, class = B
2632 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2637 umethod_bind(VALUE method
, VALUE recv
)
2639 VALUE methclass
, klass
, iclass
;
2640 const rb_method_entry_t
*me
;
2641 const struct METHOD
*data
;
2642 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2643 convert_umethod_to_method_components(data
, recv
, &methclass
, &klass
, &iclass
, &me
, true);
2645 struct METHOD
*bound
;
2646 method
= TypedData_Make_Struct(rb_cMethod
, struct METHOD
, &method_data_type
, bound
);
2647 RB_OBJ_WRITE(method
, &bound
->recv
, recv
);
2648 RB_OBJ_WRITE(method
, &bound
->klass
, klass
);
2649 RB_OBJ_WRITE(method
, &bound
->iclass
, iclass
);
2650 RB_OBJ_WRITE(method
, &bound
->owner
, methclass
);
2651 RB_OBJ_WRITE(method
, &bound
->me
, me
);
2658 * umeth.bind_call(recv, args, ...) -> obj
2660 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2661 * specified arguments.
2662 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2665 umethod_bind_call(int argc
, VALUE
*argv
, VALUE method
)
2667 rb_check_arity(argc
, 1, UNLIMITED_ARGUMENTS
);
2668 VALUE recv
= argv
[0];
2672 VALUE passed_procval
= rb_block_given_p() ? rb_block_proc() : Qnil
;
2673 rb_execution_context_t
*ec
= GET_EC();
2675 const struct METHOD
*data
;
2676 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2678 const rb_callable_method_entry_t
*cme
= rb_callable_method_entry(CLASS_OF(recv
), data
->me
->called_id
);
2679 if (data
->me
== (const rb_method_entry_t
*)cme
) {
2680 vm_passed_block_handler_set(ec
, proc_to_block_handler(passed_procval
));
2681 return rb_vm_call_kw(ec
, recv
, cme
->called_id
, argc
, argv
, cme
, RB_PASS_CALLED_KEYWORDS
);
2684 VALUE methclass
, klass
, iclass
;
2685 const rb_method_entry_t
*me
;
2686 convert_umethod_to_method_components(data
, recv
, &methclass
, &klass
, &iclass
, &me
, false);
2687 struct METHOD bound
= { recv
, klass
, 0, methclass
, me
};
2689 return call_method_data(ec
, &bound
, argc
, argv
, passed_procval
, RB_PASS_CALLED_KEYWORDS
);
2694 * Returns the number of required parameters and stores the maximum
2695 * number of parameters in max, or UNLIMITED_ARGUMENTS
2696 * if there is no maximum.
2699 method_def_min_max_arity(const rb_method_definition_t
*def
, int *max
)
2702 if (!def
) return *max
= 0;
2703 switch (def
->type
) {
2704 case VM_METHOD_TYPE_CFUNC
:
2705 if (def
->body
.cfunc
.argc
< 0) {
2706 *max
= UNLIMITED_ARGUMENTS
;
2709 return *max
= check_argc(def
->body
.cfunc
.argc
);
2710 case VM_METHOD_TYPE_ZSUPER
:
2711 *max
= UNLIMITED_ARGUMENTS
;
2713 case VM_METHOD_TYPE_ATTRSET
:
2715 case VM_METHOD_TYPE_IVAR
:
2717 case VM_METHOD_TYPE_ALIAS
:
2718 def
= def
->body
.alias
.original_me
->def
;
2720 case VM_METHOD_TYPE_BMETHOD
:
2721 return rb_proc_min_max_arity(def
->body
.bmethod
.proc
, max
);
2722 case VM_METHOD_TYPE_ISEQ
:
2723 return rb_iseq_min_max_arity(rb_iseq_check(def
->body
.iseq
.iseqptr
), max
);
2724 case VM_METHOD_TYPE_UNDEF
:
2725 case VM_METHOD_TYPE_NOTIMPLEMENTED
:
2727 case VM_METHOD_TYPE_MISSING
:
2728 *max
= UNLIMITED_ARGUMENTS
;
2730 case VM_METHOD_TYPE_OPTIMIZED
: {
2731 switch (def
->body
.optimized
.type
) {
2732 case OPTIMIZED_METHOD_TYPE_SEND
:
2733 *max
= UNLIMITED_ARGUMENTS
;
2735 case OPTIMIZED_METHOD_TYPE_CALL
:
2736 *max
= UNLIMITED_ARGUMENTS
;
2738 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL
:
2739 *max
= UNLIMITED_ARGUMENTS
;
2741 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF
:
2744 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET
:
2752 case VM_METHOD_TYPE_REFINED
:
2753 *max
= UNLIMITED_ARGUMENTS
;
2756 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def
->type
);
2757 UNREACHABLE_RETURN(Qnil
);
2761 method_def_arity(const rb_method_definition_t
*def
)
2763 int max
, min
= method_def_min_max_arity(def
, &max
);
2764 return min
== max
? min
: -min
-1;
2768 rb_method_entry_arity(const rb_method_entry_t
*me
)
2770 return method_def_arity(me
->def
);
2775 * meth.arity -> integer
2777 * Returns an indication of the number of arguments accepted by a
2778 * method. Returns a nonnegative integer for methods that take a fixed
2779 * number of arguments. For Ruby methods that take a variable number of
2780 * arguments, returns -n-1, where n is the number of required arguments.
2781 * Keyword arguments will be considered as a single additional argument,
2782 * that argument being mandatory if any keyword argument is mandatory.
2783 * For methods written in C, returns -1 if the call takes a
2784 * variable number of arguments.
2789 * def three(*a); end
2790 * def four(a, b); end
2791 * def five(a, b, *c); end
2792 * def six(a, b, *c, &d); end
2793 * def seven(a, b, x:0); end
2794 * def eight(x:, y:); end
2795 * def nine(x:, y:, **z); end
2796 * def ten(*a, x:, y:); end
2799 * c.method(:one).arity #=> 0
2800 * c.method(:two).arity #=> 1
2801 * c.method(:three).arity #=> -1
2802 * c.method(:four).arity #=> 2
2803 * c.method(:five).arity #=> -3
2804 * c.method(:six).arity #=> -3
2805 * c.method(:seven).arity #=> -3
2806 * c.method(:eight).arity #=> 1
2807 * c.method(:nine).arity #=> 1
2808 * c.method(:ten).arity #=> -2
2810 * "cat".method(:size).arity #=> 0
2811 * "cat".method(:replace).arity #=> 1
2812 * "cat".method(:squeeze).arity #=> -1
2813 * "cat".method(:count).arity #=> -1
2817 method_arity_m(VALUE method
)
2819 int n
= method_arity(method
);
2824 method_arity(VALUE method
)
2826 struct METHOD
*data
;
2828 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2829 return rb_method_entry_arity(data
->me
);
2832 static const rb_method_entry_t
*
2833 original_method_entry(VALUE mod
, ID id
)
2835 const rb_method_entry_t
*me
;
2837 while ((me
= rb_method_entry(mod
, id
)) != 0) {
2838 const rb_method_definition_t
*def
= me
->def
;
2839 if (def
->type
!= VM_METHOD_TYPE_ZSUPER
) break;
2840 mod
= RCLASS_SUPER(me
->owner
);
2841 id
= def
->original_id
;
2847 method_min_max_arity(VALUE method
, int *max
)
2849 const struct METHOD
*data
;
2851 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2852 return method_def_min_max_arity(data
->me
->def
, max
);
2856 rb_mod_method_arity(VALUE mod
, ID id
)
2858 const rb_method_entry_t
*me
= original_method_entry(mod
, id
);
2859 if (!me
) return 0; /* should raise? */
2860 return rb_method_entry_arity(me
);
2864 rb_obj_method_arity(VALUE obj
, ID id
)
2866 return rb_mod_method_arity(CLASS_OF(obj
), id
);
2870 rb_callable_receiver(VALUE callable
)
2872 if (rb_obj_is_proc(callable
)) {
2873 VALUE binding
= proc_binding(callable
);
2874 return rb_funcall(binding
, rb_intern("receiver"), 0);
2876 else if (rb_obj_is_method(callable
)) {
2877 return method_receiver(callable
);
2884 const rb_method_definition_t
*
2885 rb_method_def(VALUE method
)
2887 const struct METHOD
*data
;
2889 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
2890 return data
->me
->def
;
2893 static const rb_iseq_t
*
2894 method_def_iseq(const rb_method_definition_t
*def
)
2896 switch (def
->type
) {
2897 case VM_METHOD_TYPE_ISEQ
:
2898 return rb_iseq_check(def
->body
.iseq
.iseqptr
);
2899 case VM_METHOD_TYPE_BMETHOD
:
2900 return rb_proc_get_iseq(def
->body
.bmethod
.proc
, 0);
2901 case VM_METHOD_TYPE_ALIAS
:
2902 return method_def_iseq(def
->body
.alias
.original_me
->def
);
2903 case VM_METHOD_TYPE_CFUNC
:
2904 case VM_METHOD_TYPE_ATTRSET
:
2905 case VM_METHOD_TYPE_IVAR
:
2906 case VM_METHOD_TYPE_ZSUPER
:
2907 case VM_METHOD_TYPE_UNDEF
:
2908 case VM_METHOD_TYPE_NOTIMPLEMENTED
:
2909 case VM_METHOD_TYPE_OPTIMIZED
:
2910 case VM_METHOD_TYPE_MISSING
:
2911 case VM_METHOD_TYPE_REFINED
:
2918 rb_method_iseq(VALUE method
)
2920 return method_def_iseq(rb_method_def(method
));
2923 static const rb_cref_t
*
2924 method_cref(VALUE method
)
2926 const rb_method_definition_t
*def
= rb_method_def(method
);
2929 switch (def
->type
) {
2930 case VM_METHOD_TYPE_ISEQ
:
2931 return def
->body
.iseq
.cref
;
2932 case VM_METHOD_TYPE_ALIAS
:
2933 def
= def
->body
.alias
.original_me
->def
;
2941 method_def_location(const rb_method_definition_t
*def
)
2943 if (def
->type
== VM_METHOD_TYPE_ATTRSET
|| def
->type
== VM_METHOD_TYPE_IVAR
) {
2944 if (!def
->body
.attr
.location
)
2946 return rb_ary_dup(def
->body
.attr
.location
);
2948 return iseq_location(method_def_iseq(def
));
2952 rb_method_entry_location(const rb_method_entry_t
*me
)
2954 if (!me
) return Qnil
;
2955 return method_def_location(me
->def
);
2960 * meth.source_location -> [String, Integer]
2962 * Returns the Ruby source filename and line number containing this method
2963 * or nil if this method was not defined in Ruby (i.e. native).
2967 rb_method_location(VALUE method
)
2969 return method_def_location(rb_method_def(method
));
2972 static const rb_method_definition_t
*
2973 vm_proc_method_def(VALUE procval
)
2975 const rb_proc_t
*proc
;
2976 const struct rb_block
*block
;
2977 const struct vm_ifunc
*ifunc
;
2979 GetProcPtr(procval
, proc
);
2980 block
= &proc
->block
;
2982 if (vm_block_type(block
) == block_type_ifunc
&&
2983 IS_METHOD_PROC_IFUNC(ifunc
= block
->as
.captured
.code
.ifunc
)) {
2984 return rb_method_def((VALUE
)ifunc
->data
);
2992 method_def_parameters(const rb_method_definition_t
*def
)
2994 const rb_iseq_t
*iseq
;
2995 const rb_method_definition_t
*bmethod_def
;
2997 switch (def
->type
) {
2998 case VM_METHOD_TYPE_ISEQ
:
2999 iseq
= method_def_iseq(def
);
3000 return rb_iseq_parameters(iseq
, 0);
3001 case VM_METHOD_TYPE_BMETHOD
:
3002 if ((iseq
= method_def_iseq(def
)) != NULL
) {
3003 return rb_iseq_parameters(iseq
, 0);
3005 else if ((bmethod_def
= vm_proc_method_def(def
->body
.bmethod
.proc
)) != NULL
) {
3006 return method_def_parameters(bmethod_def
);
3010 case VM_METHOD_TYPE_ALIAS
:
3011 return method_def_parameters(def
->body
.alias
.original_me
->def
);
3013 case VM_METHOD_TYPE_OPTIMIZED
:
3014 if (def
->body
.optimized
.type
== OPTIMIZED_METHOD_TYPE_STRUCT_ASET
) {
3015 VALUE param
= rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
3016 return rb_ary_new_from_args(1, param
);
3020 case VM_METHOD_TYPE_CFUNC
:
3021 case VM_METHOD_TYPE_ATTRSET
:
3022 case VM_METHOD_TYPE_IVAR
:
3023 case VM_METHOD_TYPE_ZSUPER
:
3024 case VM_METHOD_TYPE_UNDEF
:
3025 case VM_METHOD_TYPE_NOTIMPLEMENTED
:
3026 case VM_METHOD_TYPE_MISSING
:
3027 case VM_METHOD_TYPE_REFINED
:
3031 return rb_unnamed_parameters(method_def_arity(def
));
3037 * meth.parameters -> array
3039 * Returns the parameter information of this method.
3042 * method(:foo).parameters #=> [[:req, :bar]]
3044 * def foo(bar, baz, bat, &blk); end
3045 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
3047 * def foo(bar, *args); end
3048 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
3050 * def foo(bar, baz, *args, &blk); end
3051 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
3055 rb_method_parameters(VALUE method
)
3057 return method_def_parameters(rb_method_def(method
));
3062 * meth.to_s -> string
3063 * meth.inspect -> string
3065 * Returns a human-readable description of the underlying method.
3067 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3068 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3070 * In the latter case, the method description includes the "owner" of the
3071 * original method (+Enumerable+ module, which is included into +Range+).
3073 * +inspect+ also provides, when possible, method argument names (call
3074 * sequence) and source location.
3076 * require 'net/http'
3077 * Net::HTTP.method(:get).inspect
3078 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3080 * <code>...</code> in argument definition means argument is optional (has
3081 * some default value).
3083 * For methods defined in C (language core and extensions), location and
3084 * argument names can't be extracted, and only generic information is provided
3085 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3086 * positional argument).
3088 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3089 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3094 method_inspect(VALUE method
)
3096 struct METHOD
*data
;
3098 const char *sharp
= "#";
3100 VALUE defined_class
;
3102 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
3103 str
= rb_sprintf("#<% "PRIsVALUE
": ", rb_obj_class(method
));
3105 mklass
= data
->iclass
;
3106 if (!mklass
) mklass
= data
->klass
;
3108 if (RB_TYPE_P(mklass
, T_ICLASS
)) {
3109 /* TODO: I'm not sure why mklass is T_ICLASS.
3110 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3111 * but not sure it is needed.
3113 mklass
= RBASIC_CLASS(mklass
);
3116 if (data
->me
->def
->type
== VM_METHOD_TYPE_ALIAS
) {
3117 defined_class
= data
->me
->def
->body
.alias
.original_me
->owner
;
3120 defined_class
= method_entry_defined_class(data
->me
);
3123 if (RB_TYPE_P(defined_class
, T_ICLASS
)) {
3124 defined_class
= RBASIC_CLASS(defined_class
);
3127 if (UNDEF_P(data
->recv
)) {
3129 rb_str_buf_append(str
, rb_inspect(defined_class
));
3131 else if (RCLASS_SINGLETON_P(mklass
)) {
3132 VALUE v
= RCLASS_ATTACHED_OBJECT(mklass
);
3134 if (UNDEF_P(data
->recv
)) {
3135 rb_str_buf_append(str
, rb_inspect(mklass
));
3137 else if (data
->recv
== v
) {
3138 rb_str_buf_append(str
, rb_inspect(v
));
3142 rb_str_buf_append(str
, rb_inspect(data
->recv
));
3143 rb_str_buf_cat2(str
, "(");
3144 rb_str_buf_append(str
, rb_inspect(v
));
3145 rb_str_buf_cat2(str
, ")");
3150 mklass
= data
->klass
;
3151 if (RCLASS_SINGLETON_P(mklass
)) {
3152 VALUE v
= RCLASS_ATTACHED_OBJECT(mklass
);
3153 if (!(RB_TYPE_P(v
, T_CLASS
) || RB_TYPE_P(v
, T_MODULE
))) {
3155 mklass
= RCLASS_SUPER(mklass
);
3156 } while (RB_TYPE_P(mklass
, T_ICLASS
));
3159 rb_str_buf_append(str
, rb_inspect(mklass
));
3160 if (defined_class
!= mklass
) {
3161 rb_str_catf(str
, "(% "PRIsVALUE
")", defined_class
);
3164 rb_str_buf_cat2(str
, sharp
);
3165 rb_str_append(str
, rb_id2str(data
->me
->called_id
));
3166 if (data
->me
->called_id
!= data
->me
->def
->original_id
) {
3167 rb_str_catf(str
, "(%"PRIsVALUE
")",
3168 rb_id2str(data
->me
->def
->original_id
));
3170 if (data
->me
->def
->type
== VM_METHOD_TYPE_NOTIMPLEMENTED
) {
3171 rb_str_buf_cat2(str
, " (not-implemented)");
3174 // parameter information
3176 VALUE params
= rb_method_parameters(method
);
3177 VALUE pair
, name
, kind
;
3178 const VALUE req
= ID2SYM(rb_intern("req"));
3179 const VALUE opt
= ID2SYM(rb_intern("opt"));
3180 const VALUE keyreq
= ID2SYM(rb_intern("keyreq"));
3181 const VALUE key
= ID2SYM(rb_intern("key"));
3182 const VALUE rest
= ID2SYM(rb_intern("rest"));
3183 const VALUE keyrest
= ID2SYM(rb_intern("keyrest"));
3184 const VALUE block
= ID2SYM(rb_intern("block"));
3185 const VALUE nokey
= ID2SYM(rb_intern("nokey"));
3188 rb_str_buf_cat2(str
, "(");
3190 if (RARRAY_LEN(params
) == 3 &&
3191 RARRAY_AREF(RARRAY_AREF(params
, 0), 0) == rest
&&
3192 RARRAY_AREF(RARRAY_AREF(params
, 0), 1) == ID2SYM('*') &&
3193 RARRAY_AREF(RARRAY_AREF(params
, 1), 0) == keyrest
&&
3194 RARRAY_AREF(RARRAY_AREF(params
, 1), 1) == ID2SYM(idPow
) &&
3195 RARRAY_AREF(RARRAY_AREF(params
, 2), 0) == block
&&
3196 RARRAY_AREF(RARRAY_AREF(params
, 2), 1) == ID2SYM('&')) {
3200 for (int i
= 0; i
< RARRAY_LEN(params
); i
++) {
3201 pair
= RARRAY_AREF(params
, i
);
3202 kind
= RARRAY_AREF(pair
, 0);
3203 name
= RARRAY_AREF(pair
, 1);
3204 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3205 if (NIL_P(name
) || name
== Qfalse
) {
3206 // FIXME: can it be reduced to switch/case?
3207 if (kind
== req
|| kind
== opt
) {
3208 name
= rb_str_new2("_");
3210 else if (kind
== rest
|| kind
== keyrest
) {
3211 name
= rb_str_new2("");
3213 else if (kind
== block
) {
3214 name
= rb_str_new2("block");
3216 else if (kind
== nokey
) {
3217 name
= rb_str_new2("nil");
3222 rb_str_catf(str
, "%"PRIsVALUE
, name
);
3224 else if (kind
== opt
) {
3225 rb_str_catf(str
, "%"PRIsVALUE
"=...", name
);
3227 else if (kind
== keyreq
) {
3228 rb_str_catf(str
, "%"PRIsVALUE
":", name
);
3230 else if (kind
== key
) {
3231 rb_str_catf(str
, "%"PRIsVALUE
": ...", name
);
3233 else if (kind
== rest
) {
3234 if (name
== ID2SYM('*')) {
3235 rb_str_cat_cstr(str
, forwarding
? "..." : "*");
3238 rb_str_catf(str
, "*%"PRIsVALUE
, name
);
3241 else if (kind
== keyrest
) {
3242 if (name
!= ID2SYM(idPow
)) {
3243 rb_str_catf(str
, "**%"PRIsVALUE
, name
);
3246 rb_str_set_len(str
, RSTRING_LEN(str
) - 2);
3249 rb_str_cat_cstr(str
, "**");
3252 else if (kind
== block
) {
3253 if (name
== ID2SYM('&')) {
3255 rb_str_set_len(str
, RSTRING_LEN(str
) - 2);
3258 rb_str_cat_cstr(str
, "...");
3262 rb_str_catf(str
, "&%"PRIsVALUE
, name
);
3265 else if (kind
== nokey
) {
3266 rb_str_buf_cat2(str
, "**nil");
3269 if (i
< RARRAY_LEN(params
) - 1) {
3270 rb_str_buf_cat2(str
, ", ");
3273 rb_str_buf_cat2(str
, ")");
3276 { // source location
3277 VALUE loc
= rb_method_location(method
);
3279 rb_str_catf(str
, " %"PRIsVALUE
":%"PRIsVALUE
,
3280 RARRAY_AREF(loc
, 0), RARRAY_AREF(loc
, 1));
3284 rb_str_buf_cat2(str
, ">");
3290 bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args
, method
))
3292 return rb_method_call_with_block_kw(argc
, argv
, method
, blockarg
, RB_PASS_CALLED_KEYWORDS
);
3297 rb_block_call_func_t func
,
3300 VALUE procval
= rb_block_call(rb_mRubyVMFrozenCore
, idProc
, 0, 0, func
, val
);
3306 * meth.to_proc -> proc
3308 * Returns a Proc object corresponding to this method.
3312 method_to_proc(VALUE method
)
3326 procval
= rb_block_call(rb_mRubyVMFrozenCore
, idLambda
, 0, 0, bmcall
, method
);
3327 GetProcPtr(procval
, proc
);
3328 proc
->is_from_method
= 1;
3332 extern VALUE
rb_find_defined_class_by_owner(VALUE current_class
, VALUE target_owner
);
3336 * meth.super_method -> method
3338 * Returns a Method of superclass which would be called when super is used
3339 * or nil if there is no method on superclass.
3343 method_super_method(VALUE method
)
3345 const struct METHOD
*data
;
3346 VALUE super_class
, iclass
;
3348 const rb_method_entry_t
*me
;
3350 TypedData_Get_Struct(method
, struct METHOD
, &method_data_type
, data
);
3351 iclass
= data
->iclass
;
3352 if (!iclass
) return Qnil
;
3353 if (data
->me
->def
->type
== VM_METHOD_TYPE_ALIAS
&& data
->me
->defined_class
) {
3354 super_class
= RCLASS_SUPER(rb_find_defined_class_by_owner(data
->me
->defined_class
,
3355 data
->me
->def
->body
.alias
.original_me
->owner
));
3356 mid
= data
->me
->def
->body
.alias
.original_me
->def
->original_id
;
3359 super_class
= RCLASS_SUPER(RCLASS_ORIGIN(iclass
));
3360 mid
= data
->me
->def
->original_id
;
3362 if (!super_class
) return Qnil
;
3363 me
= (rb_method_entry_t
*)rb_callable_method_entry_with_refinements(super_class
, mid
, &iclass
);
3364 if (!me
) return Qnil
;
3365 return mnew_internal(me
, me
->owner
, iclass
, data
->recv
, mid
, rb_obj_class(method
), FALSE
, FALSE
);
3370 * local_jump_error.exit_value -> obj
3372 * Returns the exit value associated with this +LocalJumpError+.
3375 localjump_xvalue(VALUE exc
)
3377 return rb_iv_get(exc
, "@exit_value");
3382 * local_jump_error.reason -> symbol
3384 * The reason this block was terminated:
3385 * :break, :redo, :retry, :next, :return, or :noreason.
3389 localjump_reason(VALUE exc
)
3391 return rb_iv_get(exc
, "@reason");
3394 rb_cref_t
*rb_vm_cref_new_toplevel(void); /* vm.c */
3396 static const rb_env_t
*
3397 env_clone(const rb_env_t
*env
, const rb_cref_t
*cref
)
3401 const rb_env_t
*new_env
;
3403 VM_ASSERT(env
->ep
> env
->env
);
3404 VM_ASSERT(VM_ENV_ESCAPED_P(env
->ep
));
3407 cref
= rb_vm_cref_new_toplevel();
3410 new_body
= ALLOC_N(VALUE
, env
->env_size
);
3411 new_ep
= &new_body
[env
->ep
- env
->env
];
3412 new_env
= vm_env_new(new_ep
, new_body
, env
->env_size
, env
->iseq
);
3414 /* The memcpy has to happen after the vm_env_new because it can trigger a
3415 * GC compaction which can move the objects in the env. */
3416 MEMCPY(new_body
, env
->env
, VALUE
, env
->env_size
);
3417 /* VM_ENV_DATA_INDEX_ENV is set in vm_env_new but will get overwritten
3418 * by the memcpy above. */
3419 new_ep
[VM_ENV_DATA_INDEX_ENV
] = (VALUE
)new_env
;
3420 RB_OBJ_WRITE(new_env
, &new_ep
[VM_ENV_DATA_INDEX_ME_CREF
], (VALUE
)cref
);
3421 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep
));
3427 * prc.binding -> binding
3429 * Returns the binding associated with <i>prc</i>.
3436 * eval("param", b.binding) #=> 99
3439 proc_binding(VALUE self
)
3441 VALUE bindval
, binding_self
= Qundef
;
3443 const rb_proc_t
*proc
;
3444 const rb_iseq_t
*iseq
= NULL
;
3445 const struct rb_block
*block
;
3446 const rb_env_t
*env
= NULL
;
3448 GetProcPtr(self
, proc
);
3449 block
= &proc
->block
;
3451 if (proc
->is_isolated
) rb_raise(rb_eArgError
, "Can't create Binding from isolated Proc");
3454 switch (vm_block_type(block
)) {
3455 case block_type_iseq
:
3456 iseq
= block
->as
.captured
.code
.iseq
;
3457 binding_self
= block
->as
.captured
.self
;
3458 env
= VM_ENV_ENVVAL_PTR(block
->as
.captured
.ep
);
3460 case block_type_proc
:
3461 GetProcPtr(block
->as
.proc
, proc
);
3462 block
= &proc
->block
;
3464 case block_type_ifunc
:
3466 const struct vm_ifunc
*ifunc
= block
->as
.captured
.code
.ifunc
;
3467 if (IS_METHOD_PROC_IFUNC(ifunc
)) {
3468 VALUE method
= (VALUE
)ifunc
->data
;
3469 VALUE name
= rb_fstring_lit("<empty_iseq>");
3471 binding_self
= method_receiver(method
);
3472 iseq
= rb_method_iseq(method
);
3473 env
= VM_ENV_ENVVAL_PTR(block
->as
.captured
.ep
);
3474 env
= env_clone(env
, method_cref(method
));
3475 /* set empty iseq */
3476 empty
= rb_iseq_new(Qnil
, name
, name
, Qnil
, 0, ISEQ_TYPE_TOP
);
3477 RB_OBJ_WRITE(env
, &env
->iseq
, empty
);
3482 case block_type_symbol
:
3483 rb_raise(rb_eArgError
, "Can't create Binding from C level Proc");
3484 UNREACHABLE_RETURN(Qnil
);
3487 bindval
= rb_binding_alloc(rb_cBinding
);
3488 GetBindingPtr(bindval
, bind
);
3489 RB_OBJ_WRITE(bindval
, &bind
->block
.as
.captured
.self
, binding_self
);
3490 RB_OBJ_WRITE(bindval
, &bind
->block
.as
.captured
.code
.iseq
, env
->iseq
);
3491 rb_vm_block_ep_update(bindval
, &bind
->block
, env
->ep
);
3492 RB_OBJ_WRITTEN(bindval
, Qundef
, VM_ENV_ENVVAL(env
->ep
));
3495 rb_iseq_check(iseq
);
3496 RB_OBJ_WRITE(bindval
, &bind
->pathobj
, ISEQ_BODY(iseq
)->location
.pathobj
);
3497 bind
->first_lineno
= ISEQ_BODY(iseq
)->location
.first_lineno
;
3500 RB_OBJ_WRITE(bindval
, &bind
->pathobj
,
3501 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil
));
3502 bind
->first_lineno
= 1;
3508 static rb_block_call_func curry
;
3511 make_curry_proc(VALUE proc
, VALUE passed
, VALUE arity
)
3513 VALUE args
= rb_ary_new3(3, proc
, passed
, arity
);
3517 GetProcPtr(proc
, procp
);
3518 is_lambda
= procp
->is_lambda
;
3519 rb_ary_freeze(passed
);
3520 rb_ary_freeze(args
);
3521 proc
= rb_proc_new(curry
, args
);
3522 GetProcPtr(proc
, procp
);
3523 procp
->is_lambda
= is_lambda
;
3528 curry(RB_BLOCK_CALL_FUNC_ARGLIST(_
, args
))
3530 VALUE proc
, passed
, arity
;
3531 proc
= RARRAY_AREF(args
, 0);
3532 passed
= RARRAY_AREF(args
, 1);
3533 arity
= RARRAY_AREF(args
, 2);
3535 passed
= rb_ary_plus(passed
, rb_ary_new4(argc
, argv
));
3536 rb_ary_freeze(passed
);
3538 if (RARRAY_LEN(passed
) < FIX2INT(arity
)) {
3539 if (!NIL_P(blockarg
)) {
3540 rb_warn("given block not used");
3542 arity
= make_curry_proc(proc
, passed
, arity
);
3546 return rb_proc_call_with_block(proc
, check_argc(RARRAY_LEN(passed
)), RARRAY_CONST_PTR(passed
), blockarg
);
3552 * prc.curry -> a_proc
3553 * prc.curry(arity) -> a_proc
3555 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3556 * it determines the number of arguments.
3557 * A curried proc receives some arguments. If a sufficient number of
3558 * arguments are supplied, it passes the supplied arguments to the original
3559 * proc and returns the result. Otherwise, returns another curried proc that
3560 * takes the rest of arguments.
3562 * The optional <i>arity</i> argument should be supplied when currying procs with
3563 * variable arguments to determine how many arguments are needed before the proc is
3566 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3567 * p b.curry[1][2][3] #=> 6
3568 * p b.curry[1, 2][3, 4] #=> 6
3569 * p b.curry(5)[1][2][3][4][5] #=> 6
3570 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3571 * p b.curry(1)[1] #=> 1
3573 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3574 * p b.curry[1][2][3] #=> 6
3575 * p b.curry[1, 2][3, 4] #=> 10
3576 * p b.curry(5)[1][2][3][4][5] #=> 15
3577 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3578 * p b.curry(1)[1] #=> 1
3580 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3581 * p b.curry[1][2][3] #=> 6
3582 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3583 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3584 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3586 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3587 * p b.curry[1][2][3] #=> 6
3588 * p b.curry[1, 2][3, 4] #=> 10
3589 * p b.curry(5)[1][2][3][4][5] #=> 15
3590 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3591 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3594 * p b.curry[] #=> :foo
3597 proc_curry(int argc
, const VALUE
*argv
, VALUE self
)
3599 int sarity
, max_arity
, min_arity
= rb_proc_min_max_arity(self
, &max_arity
);
3602 if (rb_check_arity(argc
, 0, 1) == 0 || NIL_P(arity
= argv
[0])) {
3603 arity
= INT2FIX(min_arity
);
3606 sarity
= FIX2INT(arity
);
3607 if (rb_proc_lambda_p(self
)) {
3608 rb_check_arity(sarity
, min_arity
, max_arity
);
3612 return make_curry_proc(self
, rb_ary_new(), arity
);
3617 * meth.curry -> proc
3618 * meth.curry(arity) -> proc
3620 * Returns a curried proc based on the method. When the proc is called with a number of
3621 * arguments that is lower than the method's arity, then another curried proc is returned.
3622 * Only when enough arguments have been supplied to satisfy the method signature, will the
3623 * method actually be called.
3625 * The optional <i>arity</i> argument should be supplied when currying methods with
3626 * variable arguments to determine how many arguments are needed before the method is
3633 * proc = self.method(:foo).curry
3634 * proc2 = proc.call(1, 2) #=> #<Proc>
3635 * proc2.call(3) #=> [1,2,3]
3641 * proc = self.method(:vararg).curry(4)
3642 * proc2 = proc.call(:x) #=> #<Proc>
3643 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3644 * proc3.call(:a) #=> [:x, :y, :z, :a]
3648 rb_method_curry(int argc
, const VALUE
*argv
, VALUE self
)
3650 VALUE proc
= method_to_proc(self
);
3651 return proc_curry(argc
, argv
, proc
);
3655 compose(RB_BLOCK_CALL_FUNC_ARGLIST(_
, args
))
3658 f
= RARRAY_AREF(args
, 0);
3659 g
= RARRAY_AREF(args
, 1);
3661 if (rb_obj_is_proc(g
))
3662 fargs
= rb_proc_call_with_block_kw(g
, argc
, argv
, blockarg
, RB_PASS_CALLED_KEYWORDS
);
3664 fargs
= rb_funcall_with_block_kw(g
, idCall
, argc
, argv
, blockarg
, RB_PASS_CALLED_KEYWORDS
);
3666 if (rb_obj_is_proc(f
))
3667 return rb_proc_call(f
, rb_ary_new3(1, fargs
));
3669 return rb_funcallv(f
, idCall
, 1, &fargs
);
3673 to_callable(VALUE f
)
3677 if (rb_obj_is_proc(f
)) return f
;
3678 if (rb_obj_is_method(f
)) return f
;
3679 if (rb_obj_respond_to(f
, idCall
, TRUE
)) return f
;
3680 mesg
= rb_fstring_lit("callable object is expected");
3681 rb_exc_raise(rb_exc_new_str(rb_eTypeError
, mesg
));
3684 static VALUE
rb_proc_compose_to_left(VALUE self
, VALUE g
);
3685 static VALUE
rb_proc_compose_to_right(VALUE self
, VALUE g
);
3689 * prc << g -> a_proc
3691 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3692 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3693 * then calls this proc with the result.
3695 * f = proc {|x| x * x }
3696 * g = proc {|x| x + x }
3697 * p (f << g).call(2) #=> 16
3699 * See Proc#>> for detailed explanations.
3702 proc_compose_to_left(VALUE self
, VALUE g
)
3704 return rb_proc_compose_to_left(self
, to_callable(g
));
3708 rb_proc_compose_to_left(VALUE self
, VALUE g
)
3710 VALUE proc
, args
, procs
[2];
3716 args
= rb_ary_tmp_new_from_values(0, 2, procs
);
3718 if (rb_obj_is_proc(g
)) {
3719 GetProcPtr(g
, procp
);
3720 is_lambda
= procp
->is_lambda
;
3723 VM_ASSERT(rb_obj_is_method(g
) || rb_obj_respond_to(g
, idCall
, TRUE
));
3727 proc
= rb_proc_new(compose
, args
);
3728 GetProcPtr(proc
, procp
);
3729 procp
->is_lambda
= is_lambda
;
3736 * prc >> g -> a_proc
3738 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3739 * The returned proc takes a variable number of arguments, calls this proc with them
3740 * then calls <i>g</i> with the result.
3742 * f = proc {|x| x * x }
3743 * g = proc {|x| x + x }
3744 * p (f >> g).call(2) #=> 8
3746 * <i>g</i> could be other Proc, or Method, or any other object responding to
3750 * def self.call(text)
3751 * # ...some complicated parsing logic...
3755 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3756 * pipeline.call('data.json')
3758 * See also Method#>> and Method#<<.
3761 proc_compose_to_right(VALUE self
, VALUE g
)
3763 return rb_proc_compose_to_right(self
, to_callable(g
));
3767 rb_proc_compose_to_right(VALUE self
, VALUE g
)
3769 VALUE proc
, args
, procs
[2];
3775 args
= rb_ary_tmp_new_from_values(0, 2, procs
);
3777 GetProcPtr(self
, procp
);
3778 is_lambda
= procp
->is_lambda
;
3780 proc
= rb_proc_new(compose
, args
);
3781 GetProcPtr(proc
, procp
);
3782 procp
->is_lambda
= is_lambda
;
3789 * meth << g -> a_proc
3791 * Returns a proc that is the composition of this method and the given <i>g</i>.
3792 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3793 * then calls this method with the result.
3799 * f = self.method(:f)
3800 * g = proc {|x| x + x }
3801 * p (f << g).call(2) #=> 16
3804 rb_method_compose_to_left(VALUE self
, VALUE g
)
3807 self
= method_to_proc(self
);
3808 return proc_compose_to_left(self
, g
);
3813 * meth >> g -> a_proc
3815 * Returns a proc that is the composition of this method and the given <i>g</i>.
3816 * The returned proc takes a variable number of arguments, calls this method
3817 * with them then calls <i>g</i> with the result.
3823 * f = self.method(:f)
3824 * g = proc {|x| x + x }
3825 * p (f >> g).call(2) #=> 8
3828 rb_method_compose_to_right(VALUE self
, VALUE g
)
3831 self
= method_to_proc(self
);
3832 return proc_compose_to_right(self
, g
);
3837 * proc.ruby2_keywords -> proc
3839 * Marks the proc as passing keywords through a normal argument splat.
3840 * This should only be called on procs that accept an argument splat
3841 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3842 * marks the proc such that if the proc is called with keyword arguments,
3843 * the final hash argument is marked with a special flag such that if it
3844 * is the final element of a normal argument splat to another method call,
3845 * and that method call does not include explicit keywords or a keyword
3846 * splat, the final element is interpreted as keywords. In other words,
3847 * keywords will be passed through the proc to other methods.
3849 * This should only be used for procs that delegate keywords to another
3850 * method, and only for backwards compatibility with Ruby versions before
3853 * This method will probably be removed at some point, as it exists only
3854 * for backwards compatibility. As it does not exist in Ruby versions
3855 * before 2.7, check that the proc responds to this method before calling
3856 * it. Also, be aware that if this method is removed, the behavior of the
3857 * proc will change so that it does not pass through keywords.
3860 * foo = ->(meth, *args, &block) do
3861 * send(:"do_#{meth}", *args, &block)
3863 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3868 proc_ruby2_keywords(VALUE procval
)
3871 GetProcPtr(procval
, proc
);
3873 rb_check_frozen(procval
);
3875 if (proc
->is_from_method
) {
3876 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
3880 switch (proc
->block
.type
) {
3881 case block_type_iseq
:
3882 if (ISEQ_BODY(proc
->block
.as
.captured
.code
.iseq
)->param
.flags
.has_rest
&&
3883 !ISEQ_BODY(proc
->block
.as
.captured
.code
.iseq
)->param
.flags
.has_kw
&&
3884 !ISEQ_BODY(proc
->block
.as
.captured
.code
.iseq
)->param
.flags
.has_kwrest
) {
3885 ISEQ_BODY(proc
->block
.as
.captured
.code
.iseq
)->param
.flags
.ruby2_keywords
= 1;
3888 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
3892 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
3900 * Document-class: LocalJumpError
3902 * Raised when Ruby can't yield as requested.
3904 * A typical scenario is attempting to yield when no block is given:
3911 * <em>raises the exception:</em>
3913 * LocalJumpError: no block given (yield)
3915 * A more subtle example:
3917 * def get_me_a_return
3918 * Proc.new { return 42 }
3920 * get_me_a_return.call
3922 * <em>raises the exception:</em>
3924 * LocalJumpError: unexpected return
3928 * Document-class: SystemStackError
3930 * Raised in case of a stack overflow.
3932 * def me_myself_and_i
3937 * <em>raises the exception:</em>
3939 * SystemStackError: stack level too deep
3943 * Document-class: Proc
3945 * A +Proc+ object is an encapsulation of a block of code, which can be stored
3946 * in a local variable, passed to a method or another Proc, and can be called.
3947 * Proc is an essential concept in Ruby and a core of its functional
3948 * programming features.
3950 * square = Proc.new {|x| x**2 }
3952 * square.call(3) #=> 9
3957 * Proc objects are _closures_, meaning they remember and can use the entire
3958 * context in which they were created.
3960 * def gen_times(factor)
3961 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
3964 * times3 = gen_times(3)
3965 * times5 = gen_times(5)
3967 * times3.call(12) #=> 36
3968 * times5.call(5) #=> 25
3969 * times3.call(times5.call(4)) #=> 60
3973 * There are several methods to create a Proc
3975 * * Use the Proc class constructor:
3977 * proc1 = Proc.new {|x| x**2 }
3979 * * Use the Kernel#proc method as a shorthand of Proc.new:
3981 * proc2 = proc {|x| x**2 }
3983 * * Receiving a block of code into proc argument (note the <code>&</code>):
3985 * def make_proc(&block)
3989 * proc3 = make_proc {|x| x**2 }
3991 * * Construct a proc with lambda semantics using the Kernel#lambda method
3992 * (see below for explanations about lambdas):
3994 * lambda1 = lambda {|x| x**2 }
3996 * * Use the {Lambda proc literal}[rdoc-ref:syntax/literals.rdoc@Lambda+Proc+Literals] syntax
3997 * (also constructs a proc with lambda semantics):
3999 * lambda2 = ->(x) { x**2 }
4001 * == Lambda and non-lambda semantics
4003 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
4006 * * In lambdas, +return+ and +break+ means exit from this lambda;
4007 * * In non-lambda procs, +return+ means exit from embracing method
4008 * (and will throw +LocalJumpError+ if invoked outside the method);
4009 * * In non-lambda procs, +break+ means exit from the method which the block given for.
4010 * (and will throw +LocalJumpError+ if invoked after the method returns);
4011 * * In lambdas, arguments are treated in the same way as in methods: strict,
4012 * with +ArgumentError+ for mismatching argument number,
4013 * and no additional argument processing;
4014 * * Regular procs accept arguments more generously: missing arguments
4015 * are filled with +nil+, single Array arguments are deconstructed if the
4016 * proc has multiple arguments, and there is no error raised on extra
4021 * # +return+ in non-lambda proc, +b+, exits +m2+.
4022 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
4023 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
4026 * # +break+ in non-lambda proc, +b+, exits +m1+.
4027 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
4028 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
4031 * # +next+ in non-lambda proc, +b+, exits the block.
4032 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
4033 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
4036 * # Using +proc+ method changes the behavior as follows because
4037 * # The block is given for +proc+ method and embraced by +m2+.
4038 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
4040 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4041 * # break from proc-closure (LocalJumpError)
4042 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4045 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4046 * # (+lambda+ method behaves same.)
4047 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4048 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4050 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4052 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
4055 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4056 * p.call(1, 2) #=> "x=1, y=2"
4057 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4058 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4059 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4061 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4062 * l.call(1, 2) #=> "x=1, y=2"
4063 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4064 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4065 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4068 * -> { return 3 }.call # just returns from lambda into method body
4069 * proc { return 4 }.call # returns from method
4073 * test_return # => 4, return from proc
4075 * Lambdas are useful as self-sufficient functions, in particular useful as
4076 * arguments to higher-order functions, behaving exactly like Ruby methods.
4078 * Procs are useful for implementing iterators:
4081 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4082 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4085 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4086 * which means that the internal arrays will be deconstructed to pairs of
4087 * arguments, and +return+ will exit from the method +test+. That would
4088 * not be possible with a stricter lambda.
4090 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4092 * Lambda semantics is typically preserved during the proc lifetime, including
4093 * <code>&</code>-deconstruction to a block of code:
4095 * p = proc {|x, y| x }
4096 * l = lambda {|x, y| x }
4097 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4098 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4100 * The only exception is dynamic method definition: even if defined by
4101 * passing a non-lambda proc, methods still have normal semantics of argument
4105 * define_method(:e, &proc {})
4107 * C.new.e(1,2) #=> ArgumentError
4108 * C.new.method(:e).to_proc.lambda? #=> true
4110 * This exception ensures that methods never have unusual argument passing
4111 * conventions, and makes it easy to have wrappers defining methods that
4115 * def self.def2(name, &body)
4116 * define_method(name, &body)
4121 * C.new.f(1,2) #=> ArgumentError
4123 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4124 * yet defines a method which has normal semantics.
4126 * == Conversion of other objects to procs
4128 * Any object that implements the +to_proc+ method can be converted into
4129 * a proc by the <code>&</code> operator, and therefore can be
4130 * consumed by iterators.
4134 * def initialize(greeting)
4135 * @greeting = greeting
4139 * proc {|name| "#{@greeting}, #{name}!" }
4143 * hi = Greeter.new("Hi")
4144 * hey = Greeter.new("Hey")
4145 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4146 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4148 * Of the Ruby core classes, this method is implemented by Symbol,
4151 * :to_s.to_proc.call(1) #=> "1"
4152 * [1, 2].map(&:to_s) #=> ["1", "2"]
4154 * method(:puts).to_proc.call(1) # prints 1
4155 * [1, 2].each(&method(:puts)) # prints 1, 2
4157 * {test: 1}.to_proc.call(:test) #=> 1
4158 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4162 * +return+ and +break+ in a block exit a method.
4163 * If a Proc object is generated from the block and the Proc object
4164 * survives until the method is returned, +return+ and +break+ cannot work.
4165 * In such case, +return+ and +break+ raises LocalJumpError.
4166 * A Proc object in such situation is called as orphaned Proc object.
4168 * Note that the method to exit is different for +return+ and +break+.
4169 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4171 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4172 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4174 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4175 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4177 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4178 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4180 * Since +return+ and +break+ exits the block itself in lambdas,
4181 * lambdas cannot be orphaned.
4183 * == Numbered parameters
4185 * Numbered parameters are implicitly defined block parameters intended to
4186 * simplify writing short blocks:
4188 * # Explicit parameter:
4189 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4190 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4192 * # Implicit parameter:
4193 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4194 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4196 * Parameter names from +_1+ to +_9+ are supported:
4198 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4199 * # => [120, 150, 180]
4201 * Though, it is advised to resort to them wisely, probably limiting
4202 * yourself to +_1+ and +_2+, and to one-line blocks.
4204 * Numbered parameters can't be used together with explicitly named
4207 * [10, 20, 30].map { |x| _1**2 }
4208 * # SyntaxError (ordinary parameter is defined)
4210 * To avoid conflicts, naming local variables or method
4211 * arguments +_1+, +_2+ and so on, causes a warning.
4214 * # warning: `_1' is reserved as numbered parameter
4216 * Using implicit numbered parameters affects block's arity:
4218 * p = proc { _1 + _2 }
4219 * l = lambda { _1 + _2 }
4220 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4222 * l.parameters # => [[:req, :_1], [:req, :_2]]
4225 * Blocks with numbered parameters can't be nested:
4227 * %w[test me].each { _1.each_char { p _1 } }
4228 * # SyntaxError (numbered parameter is already used in outer block here)
4229 * # %w[test me].each { _1.each_char { p _1 } }
4232 * Numbered parameters were introduced in Ruby 2.7.
4241 rb_cProc
= rb_define_class("Proc", rb_cObject
);
4242 rb_undef_alloc_func(rb_cProc
);
4243 rb_define_singleton_method(rb_cProc
, "new", rb_proc_s_new
, -1);
4245 rb_add_method_optimized(rb_cProc
, idCall
, OPTIMIZED_METHOD_TYPE_CALL
, 0, METHOD_VISI_PUBLIC
);
4246 rb_add_method_optimized(rb_cProc
, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL
, 0, METHOD_VISI_PUBLIC
);
4247 rb_add_method_optimized(rb_cProc
, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL
, 0, METHOD_VISI_PUBLIC
);
4248 rb_add_method_optimized(rb_cProc
, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL
, 0, METHOD_VISI_PUBLIC
);
4250 #if 0 /* for RDoc */
4251 rb_define_method(rb_cProc
, "call", proc_call
, -1);
4252 rb_define_method(rb_cProc
, "[]", proc_call
, -1);
4253 rb_define_method(rb_cProc
, "===", proc_call
, -1);
4254 rb_define_method(rb_cProc
, "yield", proc_call
, -1);
4257 rb_define_method(rb_cProc
, "to_proc", proc_to_proc
, 0);
4258 rb_define_method(rb_cProc
, "arity", proc_arity
, 0);
4259 rb_define_method(rb_cProc
, "clone", proc_clone
, 0);
4260 rb_define_method(rb_cProc
, "dup", proc_dup
, 0);
4261 rb_define_method(rb_cProc
, "hash", proc_hash
, 0);
4262 rb_define_method(rb_cProc
, "to_s", proc_to_s
, 0);
4263 rb_define_alias(rb_cProc
, "inspect", "to_s");
4264 rb_define_method(rb_cProc
, "lambda?", rb_proc_lambda_p
, 0);
4265 rb_define_method(rb_cProc
, "binding", proc_binding
, 0);
4266 rb_define_method(rb_cProc
, "curry", proc_curry
, -1);
4267 rb_define_method(rb_cProc
, "<<", proc_compose_to_left
, 1);
4268 rb_define_method(rb_cProc
, ">>", proc_compose_to_right
, 1);
4269 rb_define_method(rb_cProc
, "==", proc_eq
, 1);
4270 rb_define_method(rb_cProc
, "eql?", proc_eq
, 1);
4271 rb_define_method(rb_cProc
, "source_location", rb_proc_location
, 0);
4272 rb_define_method(rb_cProc
, "parameters", rb_proc_parameters
, -1);
4273 rb_define_method(rb_cProc
, "ruby2_keywords", proc_ruby2_keywords
, 0);
4274 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4277 rb_eLocalJumpError
= rb_define_class("LocalJumpError", rb_eStandardError
);
4278 rb_define_method(rb_eLocalJumpError
, "exit_value", localjump_xvalue
, 0);
4279 rb_define_method(rb_eLocalJumpError
, "reason", localjump_reason
, 0);
4281 rb_eSysStackError
= rb_define_class("SystemStackError", rb_eException
);
4282 rb_vm_register_special_exception(ruby_error_sysstack
, rb_eSysStackError
, "stack level too deep");
4284 /* utility functions */
4285 rb_define_global_function("proc", f_proc
, 0);
4286 rb_define_global_function("lambda", f_lambda
, 0);
4289 rb_cMethod
= rb_define_class("Method", rb_cObject
);
4290 rb_undef_alloc_func(rb_cMethod
);
4291 rb_undef_method(CLASS_OF(rb_cMethod
), "new");
4292 rb_define_method(rb_cMethod
, "==", method_eq
, 1);
4293 rb_define_method(rb_cMethod
, "eql?", method_eq
, 1);
4294 rb_define_method(rb_cMethod
, "hash", method_hash
, 0);
4295 rb_define_method(rb_cMethod
, "clone", method_clone
, 0);
4296 rb_define_method(rb_cMethod
, "dup", method_dup
, 0);
4297 rb_define_method(rb_cMethod
, "call", rb_method_call_pass_called_kw
, -1);
4298 rb_define_method(rb_cMethod
, "===", rb_method_call_pass_called_kw
, -1);
4299 rb_define_method(rb_cMethod
, "curry", rb_method_curry
, -1);
4300 rb_define_method(rb_cMethod
, "<<", rb_method_compose_to_left
, 1);
4301 rb_define_method(rb_cMethod
, ">>", rb_method_compose_to_right
, 1);
4302 rb_define_method(rb_cMethod
, "[]", rb_method_call_pass_called_kw
, -1);
4303 rb_define_method(rb_cMethod
, "arity", method_arity_m
, 0);
4304 rb_define_method(rb_cMethod
, "inspect", method_inspect
, 0);
4305 rb_define_method(rb_cMethod
, "to_s", method_inspect
, 0);
4306 rb_define_method(rb_cMethod
, "to_proc", method_to_proc
, 0);
4307 rb_define_method(rb_cMethod
, "receiver", method_receiver
, 0);
4308 rb_define_method(rb_cMethod
, "name", method_name
, 0);
4309 rb_define_method(rb_cMethod
, "original_name", method_original_name
, 0);
4310 rb_define_method(rb_cMethod
, "owner", method_owner
, 0);
4311 rb_define_method(rb_cMethod
, "unbind", method_unbind
, 0);
4312 rb_define_method(rb_cMethod
, "source_location", rb_method_location
, 0);
4313 rb_define_method(rb_cMethod
, "parameters", rb_method_parameters
, 0);
4314 rb_define_method(rb_cMethod
, "super_method", method_super_method
, 0);
4315 rb_define_method(rb_mKernel
, "method", rb_obj_method
, 1);
4316 rb_define_method(rb_mKernel
, "public_method", rb_obj_public_method
, 1);
4317 rb_define_method(rb_mKernel
, "singleton_method", rb_obj_singleton_method
, 1);
4320 rb_cUnboundMethod
= rb_define_class("UnboundMethod", rb_cObject
);
4321 rb_undef_alloc_func(rb_cUnboundMethod
);
4322 rb_undef_method(CLASS_OF(rb_cUnboundMethod
), "new");
4323 rb_define_method(rb_cUnboundMethod
, "==", unbound_method_eq
, 1);
4324 rb_define_method(rb_cUnboundMethod
, "eql?", unbound_method_eq
, 1);
4325 rb_define_method(rb_cUnboundMethod
, "hash", method_hash
, 0);
4326 rb_define_method(rb_cUnboundMethod
, "clone", method_clone
, 0);
4327 rb_define_method(rb_cUnboundMethod
, "dup", method_dup
, 0);
4328 rb_define_method(rb_cUnboundMethod
, "arity", method_arity_m
, 0);
4329 rb_define_method(rb_cUnboundMethod
, "inspect", method_inspect
, 0);
4330 rb_define_method(rb_cUnboundMethod
, "to_s", method_inspect
, 0);
4331 rb_define_method(rb_cUnboundMethod
, "name", method_name
, 0);
4332 rb_define_method(rb_cUnboundMethod
, "original_name", method_original_name
, 0);
4333 rb_define_method(rb_cUnboundMethod
, "owner", method_owner
, 0);
4334 rb_define_method(rb_cUnboundMethod
, "bind", umethod_bind
, 1);
4335 rb_define_method(rb_cUnboundMethod
, "bind_call", umethod_bind_call
, -1);
4336 rb_define_method(rb_cUnboundMethod
, "source_location", rb_method_location
, 0);
4337 rb_define_method(rb_cUnboundMethod
, "parameters", rb_method_parameters
, 0);
4338 rb_define_method(rb_cUnboundMethod
, "super_method", method_super_method
, 0);
4340 /* Module#*_method */
4341 rb_define_method(rb_cModule
, "instance_method", rb_mod_instance_method
, 1);
4342 rb_define_method(rb_cModule
, "public_instance_method", rb_mod_public_instance_method
, 1);
4343 rb_define_method(rb_cModule
, "define_method", rb_mod_define_method
, -1);
4346 rb_define_method(rb_mKernel
, "define_singleton_method", rb_obj_define_method
, -1);
4348 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
4349 "define_method", top_define_method
, -1);
4353 * Objects of class Binding encapsulate the execution context at some
4354 * particular place in the code and retain this context for future
4355 * use. The variables, methods, value of <code>self</code>, and
4356 * possibly an iterator block that can be accessed in this context
4357 * are all retained. Binding objects can be created using
4358 * Kernel#binding, and are made available to the callback of
4359 * Kernel#set_trace_func and instances of TracePoint.
4361 * These binding objects can be passed as the second argument of the
4362 * Kernel#eval method, establishing an environment for the
4375 * b1 = k1.get_binding
4377 * b2 = k2.get_binding
4379 * eval("@secret", b1) #=> 99
4380 * eval("@secret", b2) #=> -3
4381 * eval("@secret") #=> nil
4383 * Binding objects have no class-specific methods.
4390 rb_cBinding
= rb_define_class("Binding", rb_cObject
);
4391 rb_undef_alloc_func(rb_cBinding
);
4392 rb_undef_method(CLASS_OF(rb_cBinding
), "new");
4393 rb_define_method(rb_cBinding
, "clone", binding_clone
, 0);
4394 rb_define_method(rb_cBinding
, "dup", binding_dup
, 0);
4395 rb_define_method(rb_cBinding
, "eval", bind_eval
, -1);
4396 rb_define_method(rb_cBinding
, "local_variables", bind_local_variables
, 0);
4397 rb_define_method(rb_cBinding
, "local_variable_get", bind_local_variable_get
, 1);
4398 rb_define_method(rb_cBinding
, "local_variable_set", bind_local_variable_set
, 2);
4399 rb_define_method(rb_cBinding
, "local_variable_defined?", bind_local_variable_defined_p
, 1);
4400 rb_define_method(rb_cBinding
, "receiver", bind_receiver
, 0);
4401 rb_define_method(rb_cBinding
, "source_location", bind_location
, 0);
4402 rb_define_global_function("binding", rb_f_binding
, 0);