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