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