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