Ruby: proc.c Source File

Ruby 3.3.5p100 (2024-09-03 revision ef084cc8f4958c1b6e4ead99136631bef6d8ddba)

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