Ruby: proc.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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
37 struct 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
49 VALUE rb_cUnboundMethod;
50 VALUE rb_cMethod;
51 VALUE rb_cBinding;
52 VALUE rb_cProc;
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
70 CLONESETUP(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
75 const VALUE flags = RUBY_FL_PROMOTED0 | RUBY_FL_PROMOTED1 | RUBY_FL_FINALIZE;
76 rb_obj_setup(clone, rb_singleton_class_clone(obj),
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
142 typedef struct {
143 rb_proc_t basic;
144 VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
145} cfunc_proc_t;
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,
160 RUBY_TYPED_DEFAULT_FREE,
161 proc_memsize,
162 proc_compact,
163 },
164 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
165};
166
167 VALUE
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
174 VALUE
175rb_obj_is_proc(VALUE proc)
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
292 VALUE
293rb_proc_lambda_p(VALUE procval)
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
348 VALUE
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
384 VALUE
385rb_binding_new(void)
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);
575 UNREACHABLE_RETURN(Qundef);
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
847 VALUE
848rb_block_proc(void)
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
866 VALUE
867rb_block_lambda(void)
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
987 VALUE
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
1002 VALUE
1003rb_proc_call(VALUE self, VALUE args)
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
1014 VALUE
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
1026 VALUE
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)
1087 : UNLIMITED_ARGUMENTS;
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
1134rb_proc_arity(VALUE self)
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
1389 VALUE
1390rb_proc_location(VALUE self)
1391{
1392 return iseq_location(rb_proc_get_iseq(self, 0));
1393}
1394
1395 VALUE
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
1535 VALUE
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,
1629 RUBY_TYPED_DEFAULT_FREE,
1630 bm_memsize,
1631 bm_compact,
1632 },
1633 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1634};
1635
1636 VALUE
1637rb_obj_is_method(VALUE m)
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);
1659 rb_method_entry_t *me;
1660 rb_method_definition_t *def;
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
1666 def = ZALLOC(rb_method_definition_t);
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);
1898 method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD,
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
2074 VALUE
2075rb_obj_method(VALUE obj, VALUE vid)
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
2087 VALUE
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
2117 VALUE
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);
2152 UNREACHABLE_RETURN(Qundef);
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 {
2237 rb_raise(rb_eTypeError,
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)) {
2249 rb_raise(rb_eTypeError,
2250 "can't bind singleton method to a different class");
2251 }
2252 else {
2253 rb_raise(rb_eTypeError,
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 return rb_mod_define_method(argc, argv, rb_top_main_class("define_method"));
2386}
2387
2388/*
2389 * call-seq:
2390 * method.clone -> new_method
2391 *
2392 * Returns a clone of this method.
2393 *
2394 * class A
2395 * def foo
2396 * return "bar"
2397 * end
2398 * end
2399 *
2400 * m = A.new.method(:foo)
2401 * m.call # => "bar"
2402 * n = m.clone.call # => "bar"
2403 */
2404
2405static VALUE
2406method_clone(VALUE self)
2407{
2408 VALUE clone;
2409 struct METHOD *orig, *data;
2410
2411 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2412 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2413 CLONESETUP(clone, self);
2414 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2415 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2416 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2417 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
2418 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2419 return clone;
2420}
2421
2422/* Document-method: Method#===
2423 *
2424 * call-seq:
2425 * method === obj -> result_of_method
2426 *
2427 * Invokes the method with +obj+ as the parameter like #call.
2428 * This allows a method object to be the target of a +when+ clause
2429 * in a case statement.
2430 *
2431 * require 'prime'
2432 *
2433 * case 1373
2434 * when Prime.method(:prime?)
2435 * # ...
2436 * end
2437 */
2438
2439
2440/* Document-method: Method#[]
2441 *
2442 * call-seq:
2443 * meth[args, ...] -> obj
2444 *
2445 * Invokes the <i>meth</i> with the specified arguments, returning the
2446 * method's return value, like #call.
2447 *
2448 * m = 12.method("+")
2449 * m[3] #=> 15
2450 * m[20] #=> 32
2451 */
2452
2453/*
2454 * call-seq:
2455 * meth.call(args, ...) -> obj
2456 *
2457 * Invokes the <i>meth</i> with the specified arguments, returning the
2458 * method's return value.
2459 *
2460 * m = 12.method("+")
2461 * m.call(3) #=> 15
2462 * m.call(20) #=> 32
2463 */
2464
2465static VALUE
2466rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
2467{
2468 return rb_method_call_kw(argc, argv, method, RB_PASS_CALLED_KEYWORDS);
2469}
2470
2471 VALUE
2472rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
2473{
2474 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2475 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
2476}
2477
2478 VALUE
2479rb_method_call(int argc, const VALUE *argv, VALUE method)
2480{
2481 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2482 return rb_method_call_with_block(argc, argv, method, procval);
2483}
2484
2485static const rb_callable_method_entry_t *
2486method_callable_method_entry(const struct METHOD *data)
2487{
2488 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
2489 return (const rb_callable_method_entry_t *)data->me;
2490}
2491
2492static inline VALUE
2493call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
2494 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
2495{
2496 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2497 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
2498 method_callable_method_entry(data), kw_splat);
2499}
2500
2501 VALUE
2502rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
2503{
2504 const struct METHOD *data;
2505 rb_execution_context_t *ec = GET_EC();
2506
2507 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2508 if (UNDEF_P(data->recv)) {
2509 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
2510 }
2511 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
2512}
2513
2514 VALUE
2515rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
2516{
2517 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
2518}
2519
2520/**********************************************************************
2521 *
2522 * Document-class: UnboundMethod
2523 *
2524 * Ruby supports two forms of objectified methods. Class Method is
2525 * used to represent methods that are associated with a particular
2526 * object: these method objects are bound to that object. Bound
2527 * method objects for an object can be created using Object#method.
2528 *
2529 * Ruby also supports unbound methods; methods objects that are not
2530 * associated with a particular object. These can be created either
2531 * by calling Module#instance_method or by calling #unbind on a bound
2532 * method object. The result of both of these is an UnboundMethod
2533 * object.
2534 *
2535 * Unbound methods can only be called after they are bound to an
2536 * object. That object must be a kind_of? the method's original
2537 * class.
2538 *
2539 * class Square
2540 * def area
2541 * @side * @side
2542 * end
2543 * def initialize(side)
2544 * @side = side
2545 * end
2546 * end
2547 *
2548 * area_un = Square.instance_method(:area)
2549 *
2550 * s = Square.new(12)
2551 * area = area_un.bind(s)
2552 * area.call #=> 144
2553 *
2554 * Unbound methods are a reference to the method at the time it was
2555 * objectified: subsequent changes to the underlying class will not
2556 * affect the unbound method.
2557 *
2558 * class Test
2559 * def test
2560 * :original
2561 * end
2562 * end
2563 * um = Test.instance_method(:test)
2564 * class Test
2565 * def test
2566 * :modified
2567 * end
2568 * end
2569 * t = Test.new
2570 * t.test #=> :modified
2571 * um.bind(t).call #=> :original
2572 *
2573 */
2574
2575static void
2576convert_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)
2577{
2578 VALUE methclass = data->owner;
2579 VALUE iclass = data->me->defined_class;
2580 VALUE klass = CLASS_OF(recv);
2581
2582 if (RB_TYPE_P(methclass, T_MODULE)) {
2583 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
2584 if (!NIL_P(refined_class)) methclass = refined_class;
2585 }
2586 if (!RB_TYPE_P(methclass, T_MODULE) && !RTEST(rb_obj_is_kind_of(recv, methclass))) {
2587 if (FL_TEST(methclass, FL_SINGLETON)) {
2588 rb_raise(rb_eTypeError,
2589 "singleton method called for a different object");
2590 }
2591 else {
2592 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
2593 methclass);
2594 }
2595 }
2596
2597 const rb_method_entry_t *me;
2598 if (clone) {
2599 me = rb_method_entry_clone(data->me);
2600 }
2601 else {
2602 me = data->me;
2603 }
2604
2605 if (RB_TYPE_P(me->owner, T_MODULE)) {
2606 if (!clone) {
2607 // if we didn't previously clone the method entry, then we need to clone it now
2608 // because this branch manipulates it in rb_method_entry_complement_defined_class
2609 me = rb_method_entry_clone(me);
2610 }
2611 VALUE ic = rb_class_search_ancestor(klass, me->owner);
2612 if (ic) {
2613 klass = ic;
2614 iclass = ic;
2615 }
2616 else {
2617 klass = rb_include_class_new(methclass, klass);
2618 }
2619 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
2620 }
2621
2622 *methclass_out = methclass;
2623 *klass_out = klass;
2624 *iclass_out = iclass;
2625 *me_out = me;
2626}
2627
2628/*
2629 * call-seq:
2630 * umeth.bind(obj) -> method
2631 *
2632 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2633 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2634 * be true.
2635 *
2636 * class A
2637 * def test
2638 * puts "In test, class = #{self.class}"
2639 * end
2640 * end
2641 * class B < A
2642 * end
2643 * class C < B
2644 * end
2645 *
2646 *
2647 * um = B.instance_method(:test)
2648 * bm = um.bind(C.new)
2649 * bm.call
2650 * bm = um.bind(B.new)
2651 * bm.call
2652 * bm = um.bind(A.new)
2653 * bm.call
2654 *
2655 * <em>produces:</em>
2656 *
2657 * In test, class = C
2658 * In test, class = B
2659 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2660 * from prog.rb:16
2661 */
2662
2663static VALUE
2664umethod_bind(VALUE method, VALUE recv)
2665{
2666 VALUE methclass, klass, iclass;
2667 const rb_method_entry_t *me;
2668 const struct METHOD *data;
2669 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2670 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, true);
2671
2672 struct METHOD *bound;
2673 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
2674 RB_OBJ_WRITE(method, &bound->recv, recv);
2675 RB_OBJ_WRITE(method, &bound->klass, klass);
2676 RB_OBJ_WRITE(method, &bound->iclass, iclass);
2677 RB_OBJ_WRITE(method, &bound->owner, methclass);
2678 RB_OBJ_WRITE(method, &bound->me, me);
2679
2680 return method;
2681}
2682
2683/*
2684 * call-seq:
2685 * umeth.bind_call(recv, args, ...) -> obj
2686 *
2687 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2688 * specified arguments.
2689 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2690 */
2691static VALUE
2692umethod_bind_call(int argc, VALUE *argv, VALUE method)
2693{
2694 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2695 VALUE recv = argv[0];
2696 argc--;
2697 argv++;
2698
2699 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2700 rb_execution_context_t *ec = GET_EC();
2701
2702 const struct METHOD *data;
2703 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2704
2705 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
2706 if (data->me == (const rb_method_entry_t *)cme) {
2707 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2708 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
2709 }
2710 else {
2711 VALUE methclass, klass, iclass;
2712 const rb_method_entry_t *me;
2713 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, false);
2714 struct METHOD bound = { recv, klass, 0, methclass, me };
2715
2716 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
2717 }
2718}
2719
2720/*
2721 * Returns the number of required parameters and stores the maximum
2722 * number of parameters in max, or UNLIMITED_ARGUMENTS
2723 * if there is no maximum.
2724 */
2725static int
2726method_def_min_max_arity(const rb_method_definition_t *def, int *max)
2727{
2728 again:
2729 if (!def) return *max = 0;
2730 switch (def->type) {
2731 case VM_METHOD_TYPE_CFUNC:
2732 if (def->body.cfunc.argc < 0) {
2733 *max = UNLIMITED_ARGUMENTS;
2734 return 0;
2735 }
2736 return *max = check_argc(def->body.cfunc.argc);
2737 case VM_METHOD_TYPE_ZSUPER:
2738 *max = UNLIMITED_ARGUMENTS;
2739 return 0;
2740 case VM_METHOD_TYPE_ATTRSET:
2741 return *max = 1;
2742 case VM_METHOD_TYPE_IVAR:
2743 return *max = 0;
2744 case VM_METHOD_TYPE_ALIAS:
2745 def = def->body.alias.original_me->def;
2746 goto again;
2747 case VM_METHOD_TYPE_BMETHOD:
2748 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
2749 case VM_METHOD_TYPE_ISEQ:
2750 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
2751 case VM_METHOD_TYPE_UNDEF:
2752 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2753 return *max = 0;
2754 case VM_METHOD_TYPE_MISSING:
2755 *max = UNLIMITED_ARGUMENTS;
2756 return 0;
2757 case VM_METHOD_TYPE_OPTIMIZED: {
2758 switch (def->body.optimized.type) {
2759 case OPTIMIZED_METHOD_TYPE_SEND:
2760 *max = UNLIMITED_ARGUMENTS;
2761 return 0;
2762 case OPTIMIZED_METHOD_TYPE_CALL:
2763 *max = UNLIMITED_ARGUMENTS;
2764 return 0;
2765 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
2766 *max = UNLIMITED_ARGUMENTS;
2767 return 0;
2768 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
2769 *max = 0;
2770 return 0;
2771 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
2772 *max = 1;
2773 return 1;
2774 default:
2775 break;
2776 }
2777 break;
2778 }
2779 case VM_METHOD_TYPE_REFINED:
2780 *max = UNLIMITED_ARGUMENTS;
2781 return 0;
2782 }
2783 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
2784 UNREACHABLE_RETURN(Qnil);
2785}
2786
2787static int
2788method_def_arity(const rb_method_definition_t *def)
2789{
2790 int max, min = method_def_min_max_arity(def, &max);
2791 return min == max ? min : -min-1;
2792}
2793
2794int
2795rb_method_entry_arity(const rb_method_entry_t *me)
2796{
2797 return method_def_arity(me->def);
2798}
2799
2800/*
2801 * call-seq:
2802 * meth.arity -> integer
2803 *
2804 * Returns an indication of the number of arguments accepted by a
2805 * method. Returns a nonnegative integer for methods that take a fixed
2806 * number of arguments. For Ruby methods that take a variable number of
2807 * arguments, returns -n-1, where n is the number of required arguments.
2808 * Keyword arguments will be considered as a single additional argument,
2809 * that argument being mandatory if any keyword argument is mandatory.
2810 * For methods written in C, returns -1 if the call takes a
2811 * variable number of arguments.
2812 *
2813 * class C
2814 * def one; end
2815 * def two(a); end
2816 * def three(*a); end
2817 * def four(a, b); end
2818 * def five(a, b, *c); end
2819 * def six(a, b, *c, &d); end
2820 * def seven(a, b, x:0); end
2821 * def eight(x:, y:); end
2822 * def nine(x:, y:, **z); end
2823 * def ten(*a, x:, y:); end
2824 * end
2825 * c = C.new
2826 * c.method(:one).arity #=> 0
2827 * c.method(:two).arity #=> 1
2828 * c.method(:three).arity #=> -1
2829 * c.method(:four).arity #=> 2
2830 * c.method(:five).arity #=> -3
2831 * c.method(:six).arity #=> -3
2832 * c.method(:seven).arity #=> -3
2833 * c.method(:eight).arity #=> 1
2834 * c.method(:nine).arity #=> 1
2835 * c.method(:ten).arity #=> -2
2836 *
2837 * "cat".method(:size).arity #=> 0
2838 * "cat".method(:replace).arity #=> 1
2839 * "cat".method(:squeeze).arity #=> -1
2840 * "cat".method(:count).arity #=> -1
2841 */
2842
2843static VALUE
2844method_arity_m(VALUE method)
2845{
2846 int n = method_arity(method);
2847 return INT2FIX(n);
2848}
2849
2850static int
2851method_arity(VALUE method)
2852{
2853 struct METHOD *data;
2854
2855 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2856 return rb_method_entry_arity(data->me);
2857}
2858
2859static const rb_method_entry_t *
2860original_method_entry(VALUE mod, ID id)
2861{
2862 const rb_method_entry_t *me;
2863
2864 while ((me = rb_method_entry(mod, id)) != 0) {
2865 const rb_method_definition_t *def = me->def;
2866 if (def->type != VM_METHOD_TYPE_ZSUPER) break;
2867 mod = RCLASS_SUPER(me->owner);
2868 id = def->original_id;
2869 }
2870 return me;
2871}
2872
2873static int
2874method_min_max_arity(VALUE method, int *max)
2875{
2876 const struct METHOD *data;
2877
2878 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2879 return method_def_min_max_arity(data->me->def, max);
2880}
2881
2882int
2883rb_mod_method_arity(VALUE mod, ID id)
2884{
2885 const rb_method_entry_t *me = original_method_entry(mod, id);
2886 if (!me) return 0; /* should raise? */
2887 return rb_method_entry_arity(me);
2888}
2889
2890int
2891rb_obj_method_arity(VALUE obj, ID id)
2892{
2893 return rb_mod_method_arity(CLASS_OF(obj), id);
2894}
2895
2896 VALUE
2897rb_callable_receiver(VALUE callable)
2898{
2899 if (rb_obj_is_proc(callable)) {
2900 VALUE binding = proc_binding(callable);
2901 return rb_funcall(binding, rb_intern("receiver"), 0);
2902 }
2903 else if (rb_obj_is_method(callable)) {
2904 return method_receiver(callable);
2905 }
2906 else {
2907 return Qundef;
2908 }
2909}
2910
2911const rb_method_definition_t *
2912rb_method_def(VALUE method)
2913{
2914 const struct METHOD *data;
2915
2916 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2917 return data->me->def;
2918}
2919
2920static const rb_iseq_t *
2921method_def_iseq(const rb_method_definition_t *def)
2922{
2923 switch (def->type) {
2924 case VM_METHOD_TYPE_ISEQ:
2925 return rb_iseq_check(def->body.iseq.iseqptr);
2926 case VM_METHOD_TYPE_BMETHOD:
2927 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
2928 case VM_METHOD_TYPE_ALIAS:
2929 return method_def_iseq(def->body.alias.original_me->def);
2930 case VM_METHOD_TYPE_CFUNC:
2931 case VM_METHOD_TYPE_ATTRSET:
2932 case VM_METHOD_TYPE_IVAR:
2933 case VM_METHOD_TYPE_ZSUPER:
2934 case VM_METHOD_TYPE_UNDEF:
2935 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2936 case VM_METHOD_TYPE_OPTIMIZED:
2937 case VM_METHOD_TYPE_MISSING:
2938 case VM_METHOD_TYPE_REFINED:
2939 break;
2940 }
2941 return NULL;
2942}
2943
2944const rb_iseq_t *
2945rb_method_iseq(VALUE method)
2946{
2947 return method_def_iseq(rb_method_def(method));
2948}
2949
2950static const rb_cref_t *
2951method_cref(VALUE method)
2952{
2953 const rb_method_definition_t *def = rb_method_def(method);
2954
2955 again:
2956 switch (def->type) {
2957 case VM_METHOD_TYPE_ISEQ:
2958 return def->body.iseq.cref;
2959 case VM_METHOD_TYPE_ALIAS:
2960 def = def->body.alias.original_me->def;
2961 goto again;
2962 default:
2963 return NULL;
2964 }
2965}
2966
2967static VALUE
2968method_def_location(const rb_method_definition_t *def)
2969{
2970 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
2971 if (!def->body.attr.location)
2972 return Qnil;
2973 return rb_ary_dup(def->body.attr.location);
2974 }
2975 return iseq_location(method_def_iseq(def));
2976}
2977
2978 VALUE
2979rb_method_entry_location(const rb_method_entry_t *me)
2980{
2981 if (!me) return Qnil;
2982 return method_def_location(me->def);
2983}
2984
2985/*
2986 * call-seq:
2987 * meth.source_location -> [String, Integer]
2988 *
2989 * Returns the Ruby source filename and line number containing this method
2990 * or nil if this method was not defined in Ruby (i.e. native).
2991 */
2992
2993 VALUE
2994rb_method_location(VALUE method)
2995{
2996 return method_def_location(rb_method_def(method));
2997}
2998
2999static const rb_method_definition_t *
3000vm_proc_method_def(VALUE procval)
3001{
3002 const rb_proc_t *proc;
3003 const struct rb_block *block;
3004 const struct vm_ifunc *ifunc;
3005
3006 GetProcPtr(procval, proc);
3007 block = &proc->block;
3008
3009 if (vm_block_type(block) == block_type_ifunc &&
3010 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
3011 return rb_method_def((VALUE)ifunc->data);
3012 }
3013 else {
3014 return NULL;
3015 }
3016}
3017
3018static VALUE
3019method_def_parameters(const rb_method_definition_t *def)
3020{
3021 const rb_iseq_t *iseq;
3022 const rb_method_definition_t *bmethod_def;
3023
3024 switch (def->type) {
3025 case VM_METHOD_TYPE_ISEQ:
3026 iseq = method_def_iseq(def);
3027 return rb_iseq_parameters(iseq, 0);
3028 case VM_METHOD_TYPE_BMETHOD:
3029 if ((iseq = method_def_iseq(def)) != NULL) {
3030 return rb_iseq_parameters(iseq, 0);
3031 }
3032 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
3033 return method_def_parameters(bmethod_def);
3034 }
3035 break;
3036
3037 case VM_METHOD_TYPE_ALIAS:
3038 return method_def_parameters(def->body.alias.original_me->def);
3039
3040 case VM_METHOD_TYPE_OPTIMIZED:
3041 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
3042 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
3043 return rb_ary_new_from_args(1, param);
3044 }
3045 break;
3046
3047 case VM_METHOD_TYPE_CFUNC:
3048 case VM_METHOD_TYPE_ATTRSET:
3049 case VM_METHOD_TYPE_IVAR:
3050 case VM_METHOD_TYPE_ZSUPER:
3051 case VM_METHOD_TYPE_UNDEF:
3052 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3053 case VM_METHOD_TYPE_MISSING:
3054 case VM_METHOD_TYPE_REFINED:
3055 break;
3056 }
3057
3058 return rb_unnamed_parameters(method_def_arity(def));
3059
3060}
3061
3062/*
3063 * call-seq:
3064 * meth.parameters -> array
3065 *
3066 * Returns the parameter information of this method.
3067 *
3068 * def foo(bar); end
3069 * method(:foo).parameters #=> [[:req, :bar]]
3070 *
3071 * def foo(bar, baz, bat, &blk); end
3072 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
3073 *
3074 * def foo(bar, *args); end
3075 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
3076 *
3077 * def foo(bar, baz, *args, &blk); end
3078 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
3079 */
3080
3081static VALUE
3082rb_method_parameters(VALUE method)
3083{
3084 return method_def_parameters(rb_method_def(method));
3085}
3086
3087/*
3088 * call-seq:
3089 * meth.to_s -> string
3090 * meth.inspect -> string
3091 *
3092 * Returns a human-readable description of the underlying method.
3093 *
3094 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3095 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3096 *
3097 * In the latter case, the method description includes the "owner" of the
3098 * original method (+Enumerable+ module, which is included into +Range+).
3099 *
3100 * +inspect+ also provides, when possible, method argument names (call
3101 * sequence) and source location.
3102 *
3103 * require 'net/http'
3104 * Net::HTTP.method(:get).inspect
3105 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3106 *
3107 * <code>...</code> in argument definition means argument is optional (has
3108 * some default value).
3109 *
3110 * For methods defined in C (language core and extensions), location and
3111 * argument names can't be extracted, and only generic information is provided
3112 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3113 * positional argument).
3114 *
3115 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3116 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3117
3118 */
3119
3120static VALUE
3121method_inspect(VALUE method)
3122{
3123 struct METHOD *data;
3124 VALUE str;
3125 const char *sharp = "#";
3126 VALUE mklass;
3127 VALUE defined_class;
3128
3129 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3130 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
3131
3132 mklass = data->iclass;
3133 if (!mklass) mklass = data->klass;
3134
3135 if (RB_TYPE_P(mklass, T_ICLASS)) {
3136 /* TODO: I'm not sure why mklass is T_ICLASS.
3137 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3138 * but not sure it is needed.
3139 */
3140 mklass = RBASIC_CLASS(mklass);
3141 }
3142
3143 if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
3144 defined_class = data->me->def->body.alias.original_me->owner;
3145 }
3146 else {
3147 defined_class = method_entry_defined_class(data->me);
3148 }
3149
3150 if (RB_TYPE_P(defined_class, T_ICLASS)) {
3151 defined_class = RBASIC_CLASS(defined_class);
3152 }
3153
3154 if (data->recv == Qundef) {
3155 // UnboundMethod
3156 rb_str_buf_append(str, rb_inspect(defined_class));
3157 }
3158 else if (FL_TEST(mklass, FL_SINGLETON)) {
3159 VALUE v = rb_ivar_get(mklass, attached);
3160
3161 if (UNDEF_P(data->recv)) {
3162 rb_str_buf_append(str, rb_inspect(mklass));
3163 }
3164 else if (data->recv == v) {
3165 rb_str_buf_append(str, rb_inspect(v));
3166 sharp = ".";
3167 }
3168 else {
3169 rb_str_buf_append(str, rb_inspect(data->recv));
3170 rb_str_buf_cat2(str, "(");
3171 rb_str_buf_append(str, rb_inspect(v));
3172 rb_str_buf_cat2(str, ")");
3173 sharp = ".";
3174 }
3175 }
3176 else {
3177 mklass = data->klass;
3178 if (FL_TEST(mklass, FL_SINGLETON)) {
3179 VALUE v = rb_ivar_get(mklass, attached);
3180 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
3181 do {
3182 mklass = RCLASS_SUPER(mklass);
3183 } while (RB_TYPE_P(mklass, T_ICLASS));
3184 }
3185 }
3186 rb_str_buf_append(str, rb_inspect(mklass));
3187 if (defined_class != mklass) {
3188 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
3189 }
3190 }
3191 rb_str_buf_cat2(str, sharp);
3192 rb_str_append(str, rb_id2str(data->me->called_id));
3193 if (data->me->called_id != data->me->def->original_id) {
3194 rb_str_catf(str, "(%"PRIsVALUE")",
3195 rb_id2str(data->me->def->original_id));
3196 }
3197 if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
3198 rb_str_buf_cat2(str, " (not-implemented)");
3199 }
3200
3201 // parameter information
3202 {
3203 VALUE params = rb_method_parameters(method);
3204 VALUE pair, name, kind;
3205 const VALUE req = ID2SYM(rb_intern("req"));
3206 const VALUE opt = ID2SYM(rb_intern("opt"));
3207 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
3208 const VALUE key = ID2SYM(rb_intern("key"));
3209 const VALUE rest = ID2SYM(rb_intern("rest"));
3210 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
3211 const VALUE block = ID2SYM(rb_intern("block"));
3212 const VALUE nokey = ID2SYM(rb_intern("nokey"));
3213 int forwarding = 0;
3214
3215 rb_str_buf_cat2(str, "(");
3216
3217 if (RARRAY_LEN(params) == 3 &&
3218 RARRAY_AREF(RARRAY_AREF(params, 0), 0) == rest &&
3219 RARRAY_AREF(RARRAY_AREF(params, 0), 1) == ID2SYM('*') &&
3220 RARRAY_AREF(RARRAY_AREF(params, 1), 0) == keyrest &&
3221 RARRAY_AREF(RARRAY_AREF(params, 1), 1) == ID2SYM(idPow) &&
3222 RARRAY_AREF(RARRAY_AREF(params, 2), 0) == block &&
3223 RARRAY_AREF(RARRAY_AREF(params, 2), 1) == ID2SYM('&')) {
3224 forwarding = 1;
3225 }
3226
3227 for (int i = 0; i < RARRAY_LEN(params); i++) {
3228 pair = RARRAY_AREF(params, i);
3229 kind = RARRAY_AREF(pair, 0);
3230 name = RARRAY_AREF(pair, 1);
3231 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3232 if (NIL_P(name) || name == Qfalse) {
3233 // FIXME: can it be reduced to switch/case?
3234 if (kind == req || kind == opt) {
3235 name = rb_str_new2("_");
3236 }
3237 else if (kind == rest || kind == keyrest) {
3238 name = rb_str_new2("");
3239 }
3240 else if (kind == block) {
3241 name = rb_str_new2("block");
3242 }
3243 else if (kind == nokey) {
3244 name = rb_str_new2("nil");
3245 }
3246 }
3247
3248 if (kind == req) {
3249 rb_str_catf(str, "%"PRIsVALUE, name);
3250 }
3251 else if (kind == opt) {
3252 rb_str_catf(str, "%"PRIsVALUE"=...", name);
3253 }
3254 else if (kind == keyreq) {
3255 rb_str_catf(str, "%"PRIsVALUE":", name);
3256 }
3257 else if (kind == key) {
3258 rb_str_catf(str, "%"PRIsVALUE": ...", name);
3259 }
3260 else if (kind == rest) {
3261 if (name == ID2SYM('*')) {
3262 rb_str_cat_cstr(str, forwarding ? "..." : "*");
3263 }
3264 else {
3265 rb_str_catf(str, "*%"PRIsVALUE, name);
3266 }
3267 }
3268 else if (kind == keyrest) {
3269 if (name != ID2SYM(idPow)) {
3270 rb_str_catf(str, "**%"PRIsVALUE, name);
3271 }
3272 else if (i > 0) {
3273 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3274 }
3275 else {
3276 rb_str_cat_cstr(str, "**");
3277 }
3278 }
3279 else if (kind == block) {
3280 if (name == ID2SYM('&')) {
3281 if (forwarding) {
3282 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3283 }
3284 else {
3285 rb_str_cat_cstr(str, "...");
3286 }
3287 }
3288 else {
3289 rb_str_catf(str, "&%"PRIsVALUE, name);
3290 }
3291 }
3292 else if (kind == nokey) {
3293 rb_str_buf_cat2(str, "**nil");
3294 }
3295
3296 if (i < RARRAY_LEN(params) - 1) {
3297 rb_str_buf_cat2(str, ", ");
3298 }
3299 }
3300 rb_str_buf_cat2(str, ")");
3301 }
3302
3303 { // source location
3304 VALUE loc = rb_method_location(method);
3305 if (!NIL_P(loc)) {
3306 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
3307 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
3308 }
3309 }
3310
3311 rb_str_buf_cat2(str, ">");
3312
3313 return str;
3314}
3315
3316static VALUE
3317bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
3318{
3319 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
3320}
3321
3322 VALUE
3323 rb_proc_new(
3324 rb_block_call_func_t func,
3325 VALUE val)
3326{
3327 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
3328 return procval;
3329}
3330
3331/*
3332 * call-seq:
3333 * meth.to_proc -> proc
3334 *
3335 * Returns a Proc object corresponding to this method.
3336 */
3337
3338static VALUE
3339method_to_proc(VALUE method)
3340{
3341 VALUE procval;
3342 rb_proc_t *proc;
3343
3344 /*
3345 * class Method
3346 * def to_proc
3347 * lambda{|*args|
3348 * self.call(*args)
3349 * }
3350 * end
3351 * end
3352 */
3353 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
3354 GetProcPtr(procval, proc);
3355 proc->is_from_method = 1;
3356 return procval;
3357}
3358
3359extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
3360
3361/*
3362 * call-seq:
3363 * meth.super_method -> method
3364 *
3365 * Returns a Method of superclass which would be called when super is used
3366 * or nil if there is no method on superclass.
3367 */
3368
3369static VALUE
3370method_super_method(VALUE method)
3371{
3372 const struct METHOD *data;
3373 VALUE super_class, iclass;
3374 ID mid;
3375 const rb_method_entry_t *me;
3376
3377 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3378 iclass = data->iclass;
3379 if (!iclass) return Qnil;
3380 if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
3381 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
3382 data->me->def->body.alias.original_me->owner));
3383 mid = data->me->def->body.alias.original_me->def->original_id;
3384 }
3385 else {
3386 super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
3387 mid = data->me->def->original_id;
3388 }
3389 if (!super_class) return Qnil;
3390 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
3391 if (!me) return Qnil;
3392 return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
3393}
3394
3395/*
3396 * call-seq:
3397 * local_jump_error.exit_value -> obj
3398 *
3399 * Returns the exit value associated with this +LocalJumpError+.
3400 */
3401static VALUE
3402localjump_xvalue(VALUE exc)
3403{
3404 return rb_iv_get(exc, "@exit_value");
3405}
3406
3407/*
3408 * call-seq:
3409 * local_jump_error.reason -> symbol
3410 *
3411 * The reason this block was terminated:
3412 * :break, :redo, :retry, :next, :return, or :noreason.
3413 */
3414
3415static VALUE
3416localjump_reason(VALUE exc)
3417{
3418 return rb_iv_get(exc, "@reason");
3419}
3420
3421 rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
3422
3423static const rb_env_t *
3424env_clone(const rb_env_t *env, const rb_cref_t *cref)
3425{
3426 VALUE *new_ep;
3427 VALUE *new_body;
3428 const rb_env_t *new_env;
3429
3430 VM_ASSERT(env->ep > env->env);
3431 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
3432
3433 if (cref == NULL) {
3434 cref = rb_vm_cref_new_toplevel();
3435 }
3436
3437 new_body = ALLOC_N(VALUE, env->env_size);
3438 MEMCPY(new_body, env->env, VALUE, env->env_size);
3439 new_ep = &new_body[env->ep - env->env];
3440 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
3441 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
3442 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
3443 return new_env;
3444}
3445
3446/*
3447 * call-seq:
3448 * prc.binding -> binding
3449 *
3450 * Returns the binding associated with <i>prc</i>.
3451 *
3452 * def fred(param)
3453 * proc {}
3454 * end
3455 *
3456 * b = fred(99)
3457 * eval("param", b.binding) #=> 99
3458 */
3459static VALUE
3460proc_binding(VALUE self)
3461{
3462 VALUE bindval, binding_self = Qundef;
3463 rb_binding_t *bind;
3464 const rb_proc_t *proc;
3465 const rb_iseq_t *iseq = NULL;
3466 const struct rb_block *block;
3467 const rb_env_t *env = NULL;
3468
3469 GetProcPtr(self, proc);
3470 block = &proc->block;
3471
3472 if (proc->is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
3473
3474 again:
3475 switch (vm_block_type(block)) {
3476 case block_type_iseq:
3477 iseq = block->as.captured.code.iseq;
3478 binding_self = block->as.captured.self;
3479 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3480 break;
3481 case block_type_proc:
3482 GetProcPtr(block->as.proc, proc);
3483 block = &proc->block;
3484 goto again;
3485 case block_type_ifunc:
3486 {
3487 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
3488 if (IS_METHOD_PROC_IFUNC(ifunc)) {
3489 VALUE method = (VALUE)ifunc->data;
3490 VALUE name = rb_fstring_lit("<empty_iseq>");
3491 rb_iseq_t *empty;
3492 binding_self = method_receiver(method);
3493 iseq = rb_method_iseq(method);
3494 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3495 env = env_clone(env, method_cref(method));
3496 /* set empty iseq */
3497 empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP);
3498 RB_OBJ_WRITE(env, &env->iseq, empty);
3499 break;
3500 }
3501 }
3502 /* FALLTHROUGH */
3503 case block_type_symbol:
3504 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
3505 UNREACHABLE_RETURN(Qnil);
3506 }
3507
3508 bindval = rb_binding_alloc(rb_cBinding);
3509 GetBindingPtr(bindval, bind);
3510 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
3511 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
3512 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
3513 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
3514
3515 if (iseq) {
3516 rb_iseq_check(iseq);
3517 RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(iseq)->location.pathobj);
3518 bind->first_lineno = ISEQ_BODY(iseq)->location.first_lineno;
3519 }
3520 else {
3521 RB_OBJ_WRITE(bindval, &bind->pathobj,
3522 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
3523 bind->first_lineno = 1;
3524 }
3525
3526 return bindval;
3527}
3528
3529static rb_block_call_func curry;
3530
3531static VALUE
3532make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
3533{
3534 VALUE args = rb_ary_new3(3, proc, passed, arity);
3535 rb_proc_t *procp;
3536 int is_lambda;
3537
3538 GetProcPtr(proc, procp);
3539 is_lambda = procp->is_lambda;
3540 rb_ary_freeze(passed);
3541 rb_ary_freeze(args);
3542 proc = rb_proc_new(curry, args);
3543 GetProcPtr(proc, procp);
3544 procp->is_lambda = is_lambda;
3545 return proc;
3546}
3547
3548static VALUE
3549curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3550{
3551 VALUE proc, passed, arity;
3552 proc = RARRAY_AREF(args, 0);
3553 passed = RARRAY_AREF(args, 1);
3554 arity = RARRAY_AREF(args, 2);
3555
3556 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
3557 rb_ary_freeze(passed);
3558
3559 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
3560 if (!NIL_P(blockarg)) {
3561 rb_warn("given block not used");
3562 }
3563 arity = make_curry_proc(proc, passed, arity);
3564 return arity;
3565 }
3566 else {
3567 return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
3568 }
3569}
3570
3571 /*
3572 * call-seq:
3573 * prc.curry -> a_proc
3574 * prc.curry(arity) -> a_proc
3575 *
3576 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3577 * it determines the number of arguments.
3578 * A curried proc receives some arguments. If a sufficient number of
3579 * arguments are supplied, it passes the supplied arguments to the original
3580 * proc and returns the result. Otherwise, returns another curried proc that
3581 * takes the rest of arguments.
3582 *
3583 * The optional <i>arity</i> argument should be supplied when currying procs with
3584 * variable arguments to determine how many arguments are needed before the proc is
3585 * called.
3586 *
3587 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3588 * p b.curry[1][2][3] #=> 6
3589 * p b.curry[1, 2][3, 4] #=> 6
3590 * p b.curry(5)[1][2][3][4][5] #=> 6
3591 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3592 * p b.curry(1)[1] #=> 1
3593 *
3594 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3595 * p b.curry[1][2][3] #=> 6
3596 * p b.curry[1, 2][3, 4] #=> 10
3597 * p b.curry(5)[1][2][3][4][5] #=> 15
3598 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3599 * p b.curry(1)[1] #=> 1
3600 *
3601 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3602 * p b.curry[1][2][3] #=> 6
3603 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3604 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3605 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3606 *
3607 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3608 * p b.curry[1][2][3] #=> 6
3609 * p b.curry[1, 2][3, 4] #=> 10
3610 * p b.curry(5)[1][2][3][4][5] #=> 15
3611 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3612 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3613 *
3614 * b = proc { :foo }
3615 * p b.curry[] #=> :foo
3616 */
3617static VALUE
3618proc_curry(int argc, const VALUE *argv, VALUE self)
3619{
3620 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
3621 VALUE arity;
3622
3623 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
3624 arity = INT2FIX(min_arity);
3625 }
3626 else {
3627 sarity = FIX2INT(arity);
3628 if (rb_proc_lambda_p(self)) {
3629 rb_check_arity(sarity, min_arity, max_arity);
3630 }
3631 }
3632
3633 return make_curry_proc(self, rb_ary_new(), arity);
3634}
3635
3636/*
3637 * call-seq:
3638 * meth.curry -> proc
3639 * meth.curry(arity) -> proc
3640 *
3641 * Returns a curried proc based on the method. When the proc is called with a number of
3642 * arguments that is lower than the method's arity, then another curried proc is returned.
3643 * Only when enough arguments have been supplied to satisfy the method signature, will the
3644 * method actually be called.
3645 *
3646 * The optional <i>arity</i> argument should be supplied when currying methods with
3647 * variable arguments to determine how many arguments are needed before the method is
3648 * called.
3649 *
3650 * def foo(a,b,c)
3651 * [a, b, c]
3652 * end
3653 *
3654 * proc = self.method(:foo).curry
3655 * proc2 = proc.call(1, 2) #=> #<Proc>
3656 * proc2.call(3) #=> [1,2,3]
3657 *
3658 * def vararg(*args)
3659 * args
3660 * end
3661 *
3662 * proc = self.method(:vararg).curry(4)
3663 * proc2 = proc.call(:x) #=> #<Proc>
3664 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3665 * proc3.call(:a) #=> [:x, :y, :z, :a]
3666 */
3667
3668static VALUE
3669rb_method_curry(int argc, const VALUE *argv, VALUE self)
3670{
3671 VALUE proc = method_to_proc(self);
3672 return proc_curry(argc, argv, proc);
3673}
3674
3675static VALUE
3676compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3677{
3678 VALUE f, g, fargs;
3679 f = RARRAY_AREF(args, 0);
3680 g = RARRAY_AREF(args, 1);
3681
3682 if (rb_obj_is_proc(g))
3683 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3684 else
3685 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3686
3687 if (rb_obj_is_proc(f))
3688 return rb_proc_call(f, rb_ary_new3(1, fargs));
3689 else
3690 return rb_funcallv(f, idCall, 1, &fargs);
3691}
3692
3693static VALUE
3694to_callable(VALUE f)
3695{
3696 VALUE mesg;
3697
3698 if (rb_obj_is_proc(f)) return f;
3699 if (rb_obj_is_method(f)) return f;
3700 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
3701 mesg = rb_fstring_lit("callable object is expected");
3702 rb_exc_raise(rb_exc_new_str(rb_eTypeError, mesg));
3703}
3704
3705static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
3706static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
3707
3708/*
3709 * call-seq:
3710 * prc << g -> a_proc
3711 *
3712 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3713 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3714 * then calls this proc with the result.
3715 *
3716 * f = proc {|x| x * x }
3717 * g = proc {|x| x + x }
3718 * p (f << g).call(2) #=> 16
3719 *
3720 * See Proc#>> for detailed explanations.
3721 */
3722static VALUE
3723proc_compose_to_left(VALUE self, VALUE g)
3724{
3725 return rb_proc_compose_to_left(self, to_callable(g));
3726}
3727
3728static VALUE
3729rb_proc_compose_to_left(VALUE self, VALUE g)
3730{
3731 VALUE proc, args, procs[2];
3732 rb_proc_t *procp;
3733 int is_lambda;
3734
3735 procs[0] = self;
3736 procs[1] = g;
3737 args = rb_ary_tmp_new_from_values(0, 2, procs);
3738
3739 if (rb_obj_is_proc(g)) {
3740 GetProcPtr(g, procp);
3741 is_lambda = procp->is_lambda;
3742 }
3743 else {
3744 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
3745 is_lambda = 1;
3746 }
3747
3748 proc = rb_proc_new(compose, args);
3749 GetProcPtr(proc, procp);
3750 procp->is_lambda = is_lambda;
3751
3752 return proc;
3753}
3754
3755/*
3756 * call-seq:
3757 * prc >> g -> a_proc
3758 *
3759 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3760 * The returned proc takes a variable number of arguments, calls this proc with them
3761 * then calls <i>g</i> with the result.
3762 *
3763 * f = proc {|x| x * x }
3764 * g = proc {|x| x + x }
3765 * p (f >> g).call(2) #=> 8
3766 *
3767 * <i>g</i> could be other Proc, or Method, or any other object responding to
3768 * +call+ method:
3769 *
3770 * class Parser
3771 * def self.call(text)
3772 * # ...some complicated parsing logic...
3773 * end
3774 * end
3775 *
3776 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3777 * pipeline.call('data.json')
3778 *
3779 * See also Method#>> and Method#<<.
3780 */
3781static VALUE
3782proc_compose_to_right(VALUE self, VALUE g)
3783{
3784 return rb_proc_compose_to_right(self, to_callable(g));
3785}
3786
3787static VALUE
3788rb_proc_compose_to_right(VALUE self, VALUE g)
3789{
3790 VALUE proc, args, procs[2];
3791 rb_proc_t *procp;
3792 int is_lambda;
3793
3794 procs[0] = g;
3795 procs[1] = self;
3796 args = rb_ary_tmp_new_from_values(0, 2, procs);
3797
3798 GetProcPtr(self, procp);
3799 is_lambda = procp->is_lambda;
3800
3801 proc = rb_proc_new(compose, args);
3802 GetProcPtr(proc, procp);
3803 procp->is_lambda = is_lambda;
3804
3805 return proc;
3806}
3807
3808/*
3809 * call-seq:
3810 * meth << g -> a_proc
3811 *
3812 * Returns a proc that is the composition of this method and the given <i>g</i>.
3813 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3814 * then calls this method with the result.
3815 *
3816 * def f(x)
3817 * x * x
3818 * end
3819 *
3820 * f = self.method(:f)
3821 * g = proc {|x| x + x }
3822 * p (f << g).call(2) #=> 16
3823 */
3824static VALUE
3825rb_method_compose_to_left(VALUE self, VALUE g)
3826{
3827 g = to_callable(g);
3828 self = method_to_proc(self);
3829 return proc_compose_to_left(self, g);
3830}
3831
3832/*
3833 * call-seq:
3834 * meth >> g -> a_proc
3835 *
3836 * Returns a proc that is the composition of this method and the given <i>g</i>.
3837 * The returned proc takes a variable number of arguments, calls this method
3838 * with them then calls <i>g</i> with the result.
3839 *
3840 * def f(x)
3841 * x * x
3842 * end
3843 *
3844 * f = self.method(:f)
3845 * g = proc {|x| x + x }
3846 * p (f >> g).call(2) #=> 8
3847 */
3848static VALUE
3849rb_method_compose_to_right(VALUE self, VALUE g)
3850{
3851 g = to_callable(g);
3852 self = method_to_proc(self);
3853 return proc_compose_to_right(self, g);
3854}
3855
3856/*
3857 * call-seq:
3858 * proc.ruby2_keywords -> proc
3859 *
3860 * Marks the proc as passing keywords through a normal argument splat.
3861 * This should only be called on procs that accept an argument splat
3862 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3863 * marks the proc such that if the proc is called with keyword arguments,
3864 * the final hash argument is marked with a special flag such that if it
3865 * is the final element of a normal argument splat to another method call,
3866 * and that method call does not include explicit keywords or a keyword
3867 * splat, the final element is interpreted as keywords. In other words,
3868 * keywords will be passed through the proc to other methods.
3869 *
3870 * This should only be used for procs that delegate keywords to another
3871 * method, and only for backwards compatibility with Ruby versions before
3872 * 2.7.
3873 *
3874 * This method will probably be removed at some point, as it exists only
3875 * for backwards compatibility. As it does not exist in Ruby versions
3876 * before 2.7, check that the proc responds to this method before calling
3877 * it. Also, be aware that if this method is removed, the behavior of the
3878 * proc will change so that it does not pass through keywords.
3879 *
3880 * module Mod
3881 * foo = ->(meth, *args, &block) do
3882 * send(:"do_#{meth}", *args, &block)
3883 * end
3884 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3885 * end
3886 */
3887
3888static VALUE
3889proc_ruby2_keywords(VALUE procval)
3890{
3891 rb_proc_t *proc;
3892 GetProcPtr(procval, proc);
3893
3894 rb_check_frozen(procval);
3895
3896 if (proc->is_from_method) {
3897 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
3898 return procval;
3899 }
3900
3901 switch (proc->block.type) {
3902 case block_type_iseq:
3903 if (ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_rest &&
3904 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kw &&
3905 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kwrest) {
3906 ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.ruby2_keywords = 1;
3907 }
3908 else {
3909 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
3910 }
3911 break;
3912 default:
3913 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
3914 break;
3915 }
3916
3917 return procval;
3918}
3919
3920/*
3921 * Document-class: LocalJumpError
3922 *
3923 * Raised when Ruby can't yield as requested.
3924 *
3925 * A typical scenario is attempting to yield when no block is given:
3926 *
3927 * def call_block
3928 * yield 42
3929 * end
3930 * call_block
3931 *
3932 * <em>raises the exception:</em>
3933 *
3934 * LocalJumpError: no block given (yield)
3935 *
3936 * A more subtle example:
3937 *
3938 * def get_me_a_return
3939 * Proc.new { return 42 }
3940 * end
3941 * get_me_a_return.call
3942 *
3943 * <em>raises the exception:</em>
3944 *
3945 * LocalJumpError: unexpected return
3946 */
3947
3948/*
3949 * Document-class: SystemStackError
3950 *
3951 * Raised in case of a stack overflow.
3952 *
3953 * def me_myself_and_i
3954 * me_myself_and_i
3955 * end
3956 * me_myself_and_i
3957 *
3958 * <em>raises the exception:</em>
3959 *
3960 * SystemStackError: stack level too deep
3961 */
3962
3963/*
3964 * Document-class: Proc
3965 *
3966 * A +Proc+ object is an encapsulation of a block of code, which can be stored
3967 * in a local variable, passed to a method or another Proc, and can be called.
3968 * Proc is an essential concept in Ruby and a core of its functional
3969 * programming features.
3970 *
3971 * square = Proc.new {|x| x**2 }
3972 *
3973 * square.call(3) #=> 9
3974 * # shorthands:
3975 * square.(3) #=> 9
3976 * square[3] #=> 9
3977 *
3978 * Proc objects are _closures_, meaning they remember and can use the entire
3979 * context in which they were created.
3980 *
3981 * def gen_times(factor)
3982 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
3983 * end
3984 *
3985 * times3 = gen_times(3)
3986 * times5 = gen_times(5)
3987 *
3988 * times3.call(12) #=> 36
3989 * times5.call(5) #=> 25
3990 * times3.call(times5.call(4)) #=> 60
3991 *
3992 * == Creation
3993 *
3994 * There are several methods to create a Proc
3995 *
3996 * * Use the Proc class constructor:
3997 *
3998 * proc1 = Proc.new {|x| x**2 }
3999 *
4000 * * Use the Kernel#proc method as a shorthand of Proc.new:
4001 *
4002 * proc2 = proc {|x| x**2 }
4003 *
4004 * * Receiving a block of code into proc argument (note the <code>&</code>):
4005 *
4006 * def make_proc(&block)
4007 * block
4008 * end
4009 *
4010 * proc3 = make_proc {|x| x**2 }
4011 *
4012 * * Construct a proc with lambda semantics using the Kernel#lambda method
4013 * (see below for explanations about lambdas):
4014 *
4015 * lambda1 = lambda {|x| x**2 }
4016 *
4017 * * Use the {Lambda proc literal}[rdoc-ref:syntax/literals.rdoc@Lambda+Proc+Literals] syntax
4018 * (also constructs a proc with lambda semantics):
4019 *
4020 * lambda2 = ->(x) { x**2 }
4021 *
4022 * == Lambda and non-lambda semantics
4023 *
4024 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
4025 * Differences are:
4026 *
4027 * * In lambdas, +return+ and +break+ means exit from this lambda;
4028 * * In non-lambda procs, +return+ means exit from embracing method
4029 * (and will throw +LocalJumpError+ if invoked outside the method);
4030 * * In non-lambda procs, +break+ means exit from the method which the block given for.
4031 * (and will throw +LocalJumpError+ if invoked after the method returns);
4032 * * In lambdas, arguments are treated in the same way as in methods: strict,
4033 * with +ArgumentError+ for mismatching argument number,
4034 * and no additional argument processing;
4035 * * Regular procs accept arguments more generously: missing arguments
4036 * are filled with +nil+, single Array arguments are deconstructed if the
4037 * proc has multiple arguments, and there is no error raised on extra
4038 * arguments.
4039 *
4040 * Examples:
4041 *
4042 * # +return+ in non-lambda proc, +b+, exits +m2+.
4043 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
4044 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
4045 * #=> []
4046 *
4047 * # +break+ in non-lambda proc, +b+, exits +m1+.
4048 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
4049 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
4050 * #=> [:m2]
4051 *
4052 * # +next+ in non-lambda proc, +b+, exits the block.
4053 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
4054 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
4055 * #=> [:m1, :m2]
4056 *
4057 * # Using +proc+ method changes the behavior as follows because
4058 * # The block is given for +proc+ method and embraced by +m2+.
4059 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
4060 * #=> []
4061 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4062 * # break from proc-closure (LocalJumpError)
4063 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4064 * #=> [:m1, :m2]
4065 *
4066 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4067 * # (+lambda+ method behaves same.)
4068 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4069 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4070 * #=> [:m1, :m2]
4071 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4072 * #=> [:m1, :m2]
4073 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
4074 * #=> [:m1, :m2]
4075 *
4076 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4077 * p.call(1, 2) #=> "x=1, y=2"
4078 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4079 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4080 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4081 *
4082 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4083 * l.call(1, 2) #=> "x=1, y=2"
4084 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4085 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4086 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4087 *
4088 * def test_return
4089 * -> { return 3 }.call # just returns from lambda into method body
4090 * proc { return 4 }.call # returns from method
4091 * return 5
4092 * end
4093 *
4094 * test_return # => 4, return from proc
4095 *
4096 * Lambdas are useful as self-sufficient functions, in particular useful as
4097 * arguments to higher-order functions, behaving exactly like Ruby methods.
4098 *
4099 * Procs are useful for implementing iterators:
4100 *
4101 * def test
4102 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4103 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4104 * end
4105 *
4106 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4107 * which means that the internal arrays will be deconstructed to pairs of
4108 * arguments, and +return+ will exit from the method +test+. That would
4109 * not be possible with a stricter lambda.
4110 *
4111 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4112 *
4113 * Lambda semantics is typically preserved during the proc lifetime, including
4114 * <code>&</code>-deconstruction to a block of code:
4115 *
4116 * p = proc {|x, y| x }
4117 * l = lambda {|x, y| x }
4118 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4119 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4120 *
4121 * The only exception is dynamic method definition: even if defined by
4122 * passing a non-lambda proc, methods still have normal semantics of argument
4123 * checking.
4124 *
4125 * class C
4126 * define_method(:e, &proc {})
4127 * end
4128 * C.new.e(1,2) #=> ArgumentError
4129 * C.new.method(:e).to_proc.lambda? #=> true
4130 *
4131 * This exception ensures that methods never have unusual argument passing
4132 * conventions, and makes it easy to have wrappers defining methods that
4133 * behave as usual.
4134 *
4135 * class C
4136 * def self.def2(name, &body)
4137 * define_method(name, &body)
4138 * end
4139 *
4140 * def2(:f) {}
4141 * end
4142 * C.new.f(1,2) #=> ArgumentError
4143 *
4144 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4145 * yet defines a method which has normal semantics.
4146 *
4147 * == Conversion of other objects to procs
4148 *
4149 * Any object that implements the +to_proc+ method can be converted into
4150 * a proc by the <code>&</code> operator, and therefore can be
4151 * consumed by iterators.
4152 *
4153
4154 * class Greeter
4155 * def initialize(greeting)
4156 * @greeting = greeting
4157 * end
4158 *
4159 * def to_proc
4160 * proc {|name| "#{@greeting}, #{name}!" }
4161 * end
4162 * end
4163 *
4164 * hi = Greeter.new("Hi")
4165 * hey = Greeter.new("Hey")
4166 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4167 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4168 *
4169 * Of the Ruby core classes, this method is implemented by Symbol,
4170 * Method, and Hash.
4171 *
4172 * :to_s.to_proc.call(1) #=> "1"
4173 * [1, 2].map(&:to_s) #=> ["1", "2"]
4174 *
4175 * method(:puts).to_proc.call(1) # prints 1
4176 * [1, 2].each(&method(:puts)) # prints 1, 2
4177 *
4178 * {test: 1}.to_proc.call(:test) #=> 1
4179 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4180 *
4181 * == Orphaned Proc
4182 *
4183 * +return+ and +break+ in a block exit a method.
4184 * If a Proc object is generated from the block and the Proc object
4185 * survives until the method is returned, +return+ and +break+ cannot work.
4186 * In such case, +return+ and +break+ raises LocalJumpError.
4187 * A Proc object in such situation is called as orphaned Proc object.
4188 *
4189 * Note that the method to exit is different for +return+ and +break+.
4190 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4191 *
4192 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4193 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4194 *
4195 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4196 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4197 *
4198 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4199 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4200 *
4201 * Since +return+ and +break+ exits the block itself in lambdas,
4202 * lambdas cannot be orphaned.
4203 *
4204 * == Numbered parameters
4205 *
4206 * Numbered parameters are implicitly defined block parameters intended to
4207 * simplify writing short blocks:
4208 *
4209 * # Explicit parameter:
4210 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4211 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4212 *
4213 * # Implicit parameter:
4214 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4215 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4216 *
4217 * Parameter names from +_1+ to +_9+ are supported:
4218 *
4219 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4220 * # => [120, 150, 180]
4221 *
4222 * Though, it is advised to resort to them wisely, probably limiting
4223 * yourself to +_1+ and +_2+, and to one-line blocks.
4224 *
4225 * Numbered parameters can't be used together with explicitly named
4226 * ones:
4227 *
4228 * [10, 20, 30].map { |x| _1**2 }
4229 * # SyntaxError (ordinary parameter is defined)
4230 *
4231 * To avoid conflicts, naming local variables or method
4232 * arguments +_1+, +_2+ and so on, causes a warning.
4233 *
4234 * _1 = 'test'
4235 * # warning: `_1' is reserved as numbered parameter
4236 *
4237 * Using implicit numbered parameters affects block's arity:
4238 *
4239 * p = proc { _1 + _2 }
4240 * l = lambda { _1 + _2 }
4241 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4242 * p.arity # => 2
4243 * l.parameters # => [[:req, :_1], [:req, :_2]]
4244 * l.arity # => 2
4245 *
4246 * Blocks with numbered parameters can't be nested:
4247 *
4248 * %w[test me].each { _1.each_char { p _1 } }
4249 * # SyntaxError (numbered parameter is already used in outer block here)
4250 * # %w[test me].each { _1.each_char { p _1 } }
4251 * # ^~
4252 *
4253 * Numbered parameters were introduced in Ruby 2.7.
4254 */
4255
4256
4257void
4258Init_Proc(void)
4259{
4260#undef rb_intern
4261 /* Proc */
4262 rb_cProc = rb_define_class("Proc", rb_cObject);
4263 rb_undef_alloc_func(rb_cProc);
4264 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
4265
4266 rb_add_method_optimized(rb_cProc, idCall, OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4267 rb_add_method_optimized(rb_cProc, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4268 rb_add_method_optimized(rb_cProc, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4269 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4270
4271#if 0 /* for RDoc */
4272 rb_define_method(rb_cProc, "call", proc_call, -1);
4273 rb_define_method(rb_cProc, "[]", proc_call, -1);
4274 rb_define_method(rb_cProc, "===", proc_call, -1);
4275 rb_define_method(rb_cProc, "yield", proc_call, -1);
4276#endif
4277
4278 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
4279 rb_define_method(rb_cProc, "arity", proc_arity, 0);
4280 rb_define_method(rb_cProc, "clone", proc_clone, 0);
4281 rb_define_method(rb_cProc, "dup", rb_proc_dup, 0);
4282 rb_define_method(rb_cProc, "hash", proc_hash, 0);
4283 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
4284 rb_define_alias(rb_cProc, "inspect", "to_s");
4285 rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
4286 rb_define_method(rb_cProc, "binding", proc_binding, 0);
4287 rb_define_method(rb_cProc, "curry", proc_curry, -1);
4288 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
4289 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
4290 rb_define_method(rb_cProc, "==", proc_eq, 1);
4291 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
4292 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
4293 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, -1);
4294 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
4295 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4296
4297 /* Exceptions */
4298 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
4299 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
4300 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
4301
4302 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
4303 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
4304
4305 /* utility functions */
4306 rb_define_global_function("proc", f_proc, 0);
4307 rb_define_global_function("lambda", f_lambda, 0);
4308
4309 /* Method */
4310 rb_cMethod = rb_define_class("Method", rb_cObject);
4311 rb_undef_alloc_func(rb_cMethod);
4312 rb_undef_method(CLASS_OF(rb_cMethod), "new");
4313 rb_define_method(rb_cMethod, "==", method_eq, 1);
4314 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
4315 rb_define_method(rb_cMethod, "hash", method_hash, 0);
4316 rb_define_method(rb_cMethod, "clone", method_clone, 0);
4317 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
4318 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
4319 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
4320 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
4321 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
4322 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
4323 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
4324 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
4325 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
4326 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
4327 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
4328 rb_define_method(rb_cMethod, "name", method_name, 0);
4329 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
4330 rb_define_method(rb_cMethod, "owner", method_owner, 0);
4331 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
4332 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
4333 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
4334 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
4335 rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
4336 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
4337 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
4338
4339 /* UnboundMethod */
4340 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
4341 rb_undef_alloc_func(rb_cUnboundMethod);
4342 rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new");
4343 rb_define_method(rb_cUnboundMethod, "==", unbound_method_eq, 1);
4344 rb_define_method(rb_cUnboundMethod, "eql?", unbound_method_eq, 1);
4345 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
4346 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
4347 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
4348 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
4349 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
4350 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
4351 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
4352 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
4353 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
4354 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
4355 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
4356 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
4357 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
4358
4359 /* Module#*_method */
4360 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
4361 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
4362 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
4363
4364 /* Kernel */
4365 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
4366
4367 rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
4368 "define_method", top_define_method, -1);
4369}
4370
4371/*
4372 * Objects of class Binding encapsulate the execution context at some
4373 * particular place in the code and retain this context for future
4374 * use. The variables, methods, value of <code>self</code>, and
4375 * possibly an iterator block that can be accessed in this context
4376 * are all retained. Binding objects can be created using
4377 * Kernel#binding, and are made available to the callback of
4378 * Kernel#set_trace_func and instances of TracePoint.
4379 *
4380 * These binding objects can be passed as the second argument of the
4381 * Kernel#eval method, establishing an environment for the
4382 * evaluation.
4383 *
4384 * class Demo
4385 * def initialize(n)
4386 * @secret = n
4387 * end
4388 * def get_binding
4389 * binding
4390 * end
4391 * end
4392 *
4393 * k1 = Demo.new(99)
4394 * b1 = k1.get_binding
4395 * k2 = Demo.new(-3)
4396 * b2 = k2.get_binding
4397 *
4398 * eval("@secret", b1) #=> 99
4399 * eval("@secret", b2) #=> -3
4400 * eval("@secret") #=> nil
4401 *
4402 * Binding objects have no class-specific methods.
4403 *
4404 */
4405
4406void
4407Init_Binding(void)
4408{
4409 rb_cBinding = rb_define_class("Binding", rb_cObject);
4410 rb_undef_alloc_func(rb_cBinding);
4411 rb_undef_method(CLASS_OF(rb_cBinding), "new");
4412 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
4413 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
4414 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
4415 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
4416 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
4417 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
4418 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
4419 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
4420 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
4421 rb_define_global_function("binding", rb_f_binding, 0);
4422}
RBIMPL_ASSERT_OR_ASSUME
#define RBIMPL_ASSERT_OR_ASSUME(expr)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:229
RUBY_ASSERT
#define RUBY_ASSERT(expr)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:177
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_singleton_method
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition cxxanyargs.hpp:685
rb_define_private_method
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
Definition cxxanyargs.hpp:677
rb_define_global_function
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
Definition cxxanyargs.hpp:695
RB_FL_TEST
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
Definition fl_type.h:527
RB_FL_TEST_RAW
static VALUE RB_FL_TEST_RAW(VALUE obj, VALUE flags)
This is an implenentation detail of RB_FL_TEST().
Definition fl_type.h:501
RUBY_FL_PROMOTED1
@ RUBY_FL_PROMOTED1
This flag has something to do with our garbage collector.
Definition fl_type.h:240
RUBY_FL_PROMOTED0
@ RUBY_FL_PROMOTED0
This flag has something to do with our garbage collector.
Definition fl_type.h:223
RUBY_FL_EXIVAR
@ RUBY_FL_EXIVAR
This flag has something to do with instance variables.
Definition fl_type.h:345
RUBY_FL_FINALIZE
@ RUBY_FL_FINALIZE
This flag has something to do with finalisers.
Definition fl_type.h:271
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:923
rb_singleton_class_clone
VALUE rb_singleton_class_clone(VALUE obj)
Clones a singleton class.
Definition class.c:607
rb_singleton_class
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2241
rb_singleton_class_attached
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:672
rb_singleton_class_get
VALUE rb_singleton_class_get(VALUE obj)
Returns the singleton class of obj, or nil if obj is not a singleton object.
Definition class.c:2227
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2289
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2113
rb_scan_args
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:2579
rb_block_given_p
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:868
rb_get_kwargs
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2368
rb_str_new2
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1675
FL_SINGLETON
#define FL_SINGLETON
Old name of RUBY_FL_SINGLETON.
Definition fl_type.h:58
rb_str_buf_cat2
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1682
Qundef
#define Qundef
Old name of RUBY_Qundef.
Definition special_consts.h:62
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
ID2SYM
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
OBJ_FREEZE
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:143
UNREACHABLE_RETURN
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
SYM2ID
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
ZALLOC
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:396
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:203
rb_ary_new4
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:653
FIX2INT
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
T_MODULE
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
ASSUME
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
T_ICLASS
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
ALLOC_N
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:393
rb_ary_new3
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:652
CLONESETUP
#define CLONESETUP
Old name of rb_clone_setup.
Definition newobj.h:63
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
ST2FIX
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
T_CLASS
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
BUILTIN_TYPE
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
Check_TypedStruct
#define Check_TypedStruct(v, t)
Old name of rb_check_typeddata.
Definition rtypeddata.h:105
FL_TEST
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:139
CONST_ID
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
rb_ary_new2
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:651
rb_eLocalJumpError
VALUE rb_eLocalJumpError
LocalJumpError exception.
Definition eval.c:49
rb_raise
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition error.c:3150
rb_exc_raise
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:688
rb_typeddata_is_kind_of
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1041
rb_bug
void rb_bug(const char *fmt,...)
Interpreter panic switch.
Definition error.c:794
rb_eStandardError
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1088
rb_eRangeError
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1095
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1091
rb_warn
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports always regardless of runtime -W flag.
Definition error.c:411
rb_exc_new_str
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1142
rb_eArgError
VALUE rb_eArgError
ArgumentError exception.
Definition error.c:1092
rb_eException
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1083
rb_eSysStackError
VALUE rb_eSysStackError
SystemStackError exception.
Definition eval.c:50
rb_cUnboundMethod
VALUE rb_cUnboundMethod
UnboundMethod class.
Definition proc.c:49
rb_mKernel
VALUE rb_mKernel
Kernel module.
Definition object.c:51
rb_cBinding
VALUE rb_cBinding
Binding class.
Definition proc.c:51
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:191
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:601
rb_cModule
VALUE rb_cModule
Module class.
Definition object.c:53
rb_class_inherited_p
VALUE rb_class_inherited_p(VALUE scion, VALUE ascendant)
Determines if the given two modules are relatives.
Definition object.c:1611
rb_obj_is_kind_of
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:788
rb_class_search_ancestor
VALUE rb_class_search_ancestor(VALUE klass, VALUE super)
Internal header for Object.
Definition object.c:846
rb_cProc
VALUE rb_cProc
Proc class.
Definition proc.c:52
rb_cMethod
VALUE rb_cMethod
Method class.
Definition proc.c:50
rb_obj_setup
VALUE rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
Fills common fields in the object.
Definition object.c:102
RB_OBJ_WRITTEN
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition rgengc.h:232
RB_OBJ_WRITE
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition rgengc.h:220
rb_funcall
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1102
rb_funcall_with_block_kw
VALUE rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE procval, int kw_splat)
Identical to rb_funcallv_with_block(), except you can specify how to handle the last element of the g...
Definition vm_eval.c:1189
UNLIMITED_ARGUMENTS
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
rb_check_frozen
#define rb_check_frozen
Just another name of rb_check_frozen.
Definition error.h:264
rb_check_arity
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:280
rb_is_local_id
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1061
rb_method_call_with_block
VALUE rb_method_call_with_block(int argc, const VALUE *argv, VALUE recv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass a proc as a block.
Definition proc.c:2515
rb_obj_method_arity
int rb_obj_method_arity(VALUE obj, ID mid)
Identical to rb_mod_method_arity(), except it searches for singleton methods rather than instance met...
Definition proc.c:2891
rb_proc_call
VALUE rb_proc_call(VALUE recv, VALUE args)
Evaluates the passed proc with the passed arguments.
Definition proc.c:1003
rb_proc_call_with_block_kw
VALUE rb_proc_call_with_block_kw(VALUE recv, int argc, const VALUE *argv, VALUE proc, int kw_splat)
Identical to rb_proc_call_with_block(), except you can specify how to handle the last element of the ...
Definition proc.c:1015
rb_method_call_kw
VALUE rb_method_call_kw(int argc, const VALUE *argv, VALUE recv, int kw_splat)
Identical to rb_method_call(), except you can specify how to handle the last element of the given arr...
Definition proc.c:2472
rb_obj_method
VALUE rb_obj_method(VALUE recv, VALUE mid)
Creates a method object.
Definition proc.c:2075
rb_proc_lambda_p
VALUE rb_proc_lambda_p(VALUE recv)
Queries if the given object is a lambda.
Definition proc.c:293
rb_block_proc
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:848
rb_proc_call_with_block
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1027
rb_mod_method_arity
int rb_mod_method_arity(VALUE mod, ID mid)
Queries the number of mandatory arguments of the method defined in the given module.
Definition proc.c:2883
rb_method_call_with_block_kw
VALUE rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE recv, VALUE proc, int kw_splat)
Identical to rb_method_call_with_block(), except you can specify how to handle the last element of th...
Definition proc.c:2502
rb_obj_is_method
VALUE rb_obj_is_method(VALUE recv)
Queries if the given object is a method.
Definition proc.c:1637
rb_block_lambda
VALUE rb_block_lambda(void)
Identical to rb_proc_new(), except it returns a lambda.
Definition proc.c:867
rb_proc_call_kw
VALUE rb_proc_call_kw(VALUE recv, VALUE args, int kw_splat)
Identical to rb_proc_call(), except you can specify how to handle the last element of the given array...
Definition proc.c:988
rb_binding_new
VALUE rb_binding_new(void)
Snapshots the current execution context and turn it into an instance of rb_cBinding.
Definition proc.c:385
rb_proc_arity
int rb_proc_arity(VALUE recv)
Queries the number of mandatory arguments of the given Proc.
Definition proc.c:1134
rb_method_call
VALUE rb_method_call(int argc, const VALUE *argv, VALUE recv)
Evaluates the passed method with the passed arguments.
Definition proc.c:2479
rb_obj_is_proc
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:175
rb_hash_uint
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:942
rb_hash_end
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:945
rb_str_append
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3353
rb_str_buf_append
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:3319
rb_str_set_len
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3020
rb_hash_start
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1735
rb_str_cat_cstr
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1656
rb_str_intern
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:851
rb_ivar_get
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
rb_undef_alloc_func
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1142
rb_obj_respond_to
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:2789
rb_check_id
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1085
rb_intern
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition symbol.c:796
rb_to_id
ID rb_to_id(VALUE str)
Identical to rb_intern(), except it takes an instance of rb_cString.
Definition string.c:11914
rb_intern_str
ID rb_intern_str(VALUE str)
Identical to rb_intern(), except it takes an instance of rb_cString.
Definition symbol.c:802
rb_iv_get
VALUE rb_iv_get(VALUE obj, const char *name)
Obtains an instance variable.
Definition variable.c:3936
RB_INT2NUM
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
rb_sprintf
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition sprintf.c:1219
rb_str_catf
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
RB_BLOCK_CALL_FUNC_ARGLIST
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
rb_block_call_func_t
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
rb_block_call_func
VALUE rb_block_call_func(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
This is the type of a function that the interpreter expect for C-backended blocks.
Definition iterator.h:83
MEMCPY
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:366
RB_GC_GUARD
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:161
ruby::backward::cxxanyargs::rb_block_call
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
Definition cxxanyargs.hpp:232
ruby::backward::cxxanyargs::rb_proc_new
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
Definition cxxanyargs.hpp:394
rb_copy_generic_ivar
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:1740
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:68
RARRAY_ASET
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:566
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition rarray.h:583
RARRAY_CONST_PTR
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:69
RBASIC_CLASS
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:152
RCLASS_SUPER
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
DATA_PTR
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:71
RSTRING_LEN
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
Definition rstring.h:484
RUBY_TYPED_DEFAULT_FREE
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:79
TypedData_Get_Struct
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:507
TypedData_Make_Struct
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:489
rb_obj_classname
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:325
RB_PASS_CALLED_KEYWORDS
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
RB_NO_KEYWORDS
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
RB_SPECIAL_CONST_P
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
Definition special_consts.h:327
RTEST
#define RTEST
This is an old name of RB_TEST.
Definition special_consts.h:51
_
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
METHOD
Definition proc.c:37
cfunc_proc_t
Definition proc.c:142
rb_binding_t
Definition vm_core.h:1163
rb_block
Definition vm_core.h:809
rb_callable_method_entry_struct
Definition method.h:62
rb_captured_block
Definition vm_core.h:785
rb_control_frame_struct
Definition vm_core.h:818
rb_cref_struct
CREF (Class REFerence)
Definition method.h:44
rb_data_type_struct
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:190
rb_env_t
Definition vm_core.h:1150
rb_execution_context_struct
Definition vm_core.h:899
rb_iseq_struct
Definition vm_core.h:526
rb_method_definition_struct
Definition method.h:179
rb_method_entry_struct
Definition method.h:54
rb_method_iseq_struct::cref
rb_cref_t * cref
class reference, should be marked
Definition method.h:136
rb_method_iseq_struct::iseqptr
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:135
rb_proc_t
Definition vm_core.h:1137
rb_scope_visi_struct
Definition method.h:38
vm_ifunc_argc
Definition imemo.h:74
vm_ifunc
IFUNC (Internal FUNCtion)
Definition imemo.h:84
ID
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
SIZEOF_VALUE
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
RB_TYPE_P
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:375