Ruby 3.5.0dev (2025-06-26 revision b1c09faf67a663bcda430931c987762521efd53a)
proc.c (b1c09faf67a663bcda430931c987762521efd53a)
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 }
1566 else {
1567 return sym_proc_new(rb_cProc, sym);
1568 }
1569}
1570
1571/*
1572 * call-seq:
1573 * prc.hash -> integer
1574 *
1575 * Returns a hash value corresponding to proc body.
1576 *
1577 * See also Object#hash.
1578 */
1579
1580static VALUE
1581proc_hash(VALUE self)
1582{
1583 st_index_t hash;
1584 hash = rb_hash_start(0);
1585 hash = rb_hash_proc(hash, self);
1586 hash = rb_hash_end(hash);
1587 return ST2FIX(hash);
1588}
1589
1590VALUE
1591rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
1592{
1593 VALUE cname = rb_obj_class(self);
1594 VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
1595
1596 again:
1597 switch (vm_block_type(block)) {
1598 case block_type_proc:
1599 block = vm_proc_block(block->as.proc);
1600 goto again;
1601 case block_type_iseq:
1602 {
1603 const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
1604 rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
1605 rb_iseq_path(iseq),
1606 ISEQ_BODY(iseq)->location.first_lineno);
1607 }
1608 break;
1609 case block_type_symbol:
1610 rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
1611 break;
1612 case block_type_ifunc:
1613 rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
1614 break;
1615 }
1616
1617 if (additional_info) rb_str_cat_cstr(str, additional_info);
1618 rb_str_cat_cstr(str, ">");
1619 return str;
1620}
1621
1622/*
1623 * call-seq:
1624 * prc.to_s -> string
1625 *
1626 * Returns the unique identifier for this proc, along with
1627 * an indication of where the proc was defined.
1628 */
1629
1630static VALUE
1631proc_to_s(VALUE self)
1632{
1633 const rb_proc_t *proc;
1634 GetProcPtr(self, proc);
1635 return rb_block_to_s(self, &proc->block, proc->is_lambda ? " (lambda)" : NULL);
1636}
1637
1638/*
1639 * call-seq:
1640 * prc.to_proc -> proc
1641 *
1642 * Part of the protocol for converting objects to Proc objects.
1643 * Instances of class Proc simply return themselves.
1644 */
1645
1646static VALUE
1647proc_to_proc(VALUE self)
1648{
1649 return self;
1650}
1651
1652static void
1653bm_mark_and_move(void *ptr)
1654{
1655 struct METHOD *data = ptr;
1656 rb_gc_mark_and_move((VALUE *)&data->recv);
1657 rb_gc_mark_and_move((VALUE *)&data->klass);
1658 rb_gc_mark_and_move((VALUE *)&data->iclass);
1659 rb_gc_mark_and_move((VALUE *)&data->owner);
1660 rb_gc_mark_and_move_ptr((rb_method_entry_t **)&data->me);
1661}
1662
1663static const rb_data_type_t method_data_type = {
1664 "method",
1665 {
1666 bm_mark_and_move,
1668 NULL, // No external memory to report,
1669 bm_mark_and_move,
1670 },
1671 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1672};
1673
1674VALUE
1676{
1677 return RBOOL(rb_typeddata_is_kind_of(m, &method_data_type));
1678}
1679
1680static int
1681respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
1682{
1683 /* TODO: merge with obj_respond_to() */
1684 ID rmiss = idRespond_to_missing;
1685
1686 if (UNDEF_P(obj)) return 0;
1687 if (rb_method_basic_definition_p(klass, rmiss)) return 0;
1688 return RTEST(rb_funcall(obj, rmiss, 2, sym, RBOOL(!scope)));
1689}
1690
1691
1692static VALUE
1693mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
1694{
1695 struct METHOD *data;
1696 VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1699
1700 RB_OBJ_WRITE(method, &data->recv, obj);
1701 RB_OBJ_WRITE(method, &data->klass, klass);
1702 RB_OBJ_WRITE(method, &data->owner, klass);
1703
1705 def->type = VM_METHOD_TYPE_MISSING;
1706 def->original_id = id;
1707
1708 me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
1709
1710 RB_OBJ_WRITE(method, &data->me, me);
1711
1712 return method;
1713}
1714
1715static VALUE
1716mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
1717{
1718 VALUE vid = rb_str_intern(*name);
1719 *name = vid;
1720 if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
1721 return mnew_missing(klass, obj, SYM2ID(vid), mclass);
1722}
1723
1724static VALUE
1725mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1726 VALUE obj, ID id, VALUE mclass, int scope, int error)
1727{
1728 struct METHOD *data;
1729 VALUE method;
1730 const rb_method_entry_t *original_me = me;
1731 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
1732
1733 again:
1734 if (UNDEFINED_METHOD_ENTRY_P(me)) {
1735 if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
1736 return mnew_missing(klass, obj, id, mclass);
1737 }
1738 if (!error) return Qnil;
1739 rb_print_undef(klass, id, METHOD_VISI_UNDEF);
1740 }
1741 if (visi == METHOD_VISI_UNDEF) {
1742 visi = METHOD_ENTRY_VISI(me);
1743 RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */
1744 if (scope && (visi != METHOD_VISI_PUBLIC)) {
1745 if (!error) return Qnil;
1746 rb_print_inaccessible(klass, id, visi);
1747 }
1748 }
1749 if (me->def->type == VM_METHOD_TYPE_ZSUPER) {
1750 if (me->defined_class) {
1751 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
1752 id = me->def->original_id;
1753 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1754 }
1755 else {
1756 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner));
1757 id = me->def->original_id;
1758 me = rb_method_entry_without_refinements(klass, id, &iclass);
1759 }
1760 goto again;
1761 }
1762
1763 method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1764
1765 if (UNDEF_P(obj)) {
1766 RB_OBJ_WRITE(method, &data->recv, Qundef);
1767 RB_OBJ_WRITE(method, &data->klass, Qundef);
1768 }
1769 else {
1770 RB_OBJ_WRITE(method, &data->recv, obj);
1771 RB_OBJ_WRITE(method, &data->klass, klass);
1772 }
1773 RB_OBJ_WRITE(method, &data->iclass, iclass);
1774 RB_OBJ_WRITE(method, &data->owner, original_me->owner);
1775 RB_OBJ_WRITE(method, &data->me, me);
1776
1777 return method;
1778}
1779
1780static VALUE
1781mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
1782 VALUE obj, ID id, VALUE mclass, int scope)
1783{
1784 return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
1785}
1786
1787static VALUE
1788mnew_callable(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
1789{
1790 const rb_method_entry_t *me;
1791 VALUE iclass = Qnil;
1792
1793 ASSUME(!UNDEF_P(obj));
1794 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
1795 return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
1796}
1797
1798static VALUE
1799mnew_unbound(VALUE klass, ID id, VALUE mclass, int scope)
1800{
1801 const rb_method_entry_t *me;
1802 VALUE iclass = Qnil;
1803
1804 me = rb_method_entry_with_refinements(klass, id, &iclass);
1805 return mnew_from_me(me, klass, iclass, Qundef, id, mclass, scope);
1806}
1807
1808static inline VALUE
1809method_entry_defined_class(const rb_method_entry_t *me)
1810{
1811 VALUE defined_class = me->defined_class;
1812 return defined_class ? defined_class : me->owner;
1813}
1814
1815/**********************************************************************
1816 *
1817 * Document-class: Method
1818 *
1819 * +Method+ objects are created by Object#method, and are associated
1820 * with a particular object (not just with a class). They may be
1821 * used to invoke the method within the object, and as a block
1822 * associated with an iterator. They may also be unbound from one
1823 * object (creating an UnboundMethod) and bound to another.
1824 *
1825 * class Thing
1826 * def square(n)
1827 * n*n
1828 * end
1829 * end
1830 * thing = Thing.new
1831 * meth = thing.method(:square)
1832 *
1833 * meth.call(9) #=> 81
1834 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1835 *
1836 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
1837 *
1838 * require 'date'
1839 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
1840 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
1841 */
1842
1843/*
1844 * call-seq:
1845 * meth.eql?(other_meth) -> true or false
1846 * meth == other_meth -> true or false
1847 *
1848 * Two method objects are equal if they are bound to the same
1849 * object and refer to the same method definition and the classes
1850 * defining the methods are the same class or module.
1851 */
1852
1853static VALUE
1854method_eq(VALUE method, VALUE other)
1855{
1856 struct METHOD *m1, *m2;
1857 VALUE klass1, klass2;
1858
1859 if (!rb_obj_is_method(other))
1860 return Qfalse;
1861 if (CLASS_OF(method) != CLASS_OF(other))
1862 return Qfalse;
1863
1864 Check_TypedStruct(method, &method_data_type);
1865 m1 = (struct METHOD *)RTYPEDDATA_GET_DATA(method);
1866 m2 = (struct METHOD *)RTYPEDDATA_GET_DATA(other);
1867
1868 klass1 = method_entry_defined_class(m1->me);
1869 klass2 = method_entry_defined_class(m2->me);
1870
1871 if (!rb_method_entry_eq(m1->me, m2->me) ||
1872 klass1 != klass2 ||
1873 m1->klass != m2->klass ||
1874 m1->recv != m2->recv) {
1875 return Qfalse;
1876 }
1877
1878 return Qtrue;
1879}
1880
1881/*
1882 * call-seq:
1883 * meth.eql?(other_meth) -> true or false
1884 * meth == other_meth -> true or false
1885 *
1886 * Two unbound method objects are equal if they refer to the same
1887 * method definition.
1888 *
1889 * Array.instance_method(:each_slice) == Enumerable.instance_method(:each_slice)
1890 * #=> true
1891 *
1892 * Array.instance_method(:sum) == Enumerable.instance_method(:sum)
1893 * #=> false, Array redefines the method for efficiency
1894 */
1895#define unbound_method_eq method_eq
1896
1897/*
1898 * call-seq:
1899 * meth.hash -> integer
1900 *
1901 * Returns a hash value corresponding to the method object.
1902 *
1903 * See also Object#hash.
1904 */
1905
1906static VALUE
1907method_hash(VALUE method)
1908{
1909 struct METHOD *m;
1910 st_index_t hash;
1911
1912 TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
1913 hash = rb_hash_start((st_index_t)m->recv);
1914 hash = rb_hash_method_entry(hash, m->me);
1915 hash = rb_hash_end(hash);
1916
1917 return ST2FIX(hash);
1918}
1919
1920/*
1921 * call-seq:
1922 * meth.unbind -> unbound_method
1923 *
1924 * Dissociates <i>meth</i> from its current receiver. The resulting
1925 * UnboundMethod can subsequently be bound to a new object of the
1926 * same class (see UnboundMethod).
1927 */
1928
1929static VALUE
1930method_unbind(VALUE obj)
1931{
1932 VALUE method;
1933 struct METHOD *orig, *data;
1934
1935 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
1937 &method_data_type, data);
1938 RB_OBJ_WRITE(method, &data->recv, Qundef);
1939 RB_OBJ_WRITE(method, &data->klass, Qundef);
1940 RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
1941 RB_OBJ_WRITE(method, &data->owner, orig->me->owner);
1942 RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
1943
1944 return method;
1945}
1946
1947/*
1948 * call-seq:
1949 * meth.receiver -> object
1950 *
1951 * Returns the bound receiver of the method object.
1952 *
1953 * (1..3).method(:map).receiver # => 1..3
1954 */
1955
1956static VALUE
1957method_receiver(VALUE obj)
1958{
1959 struct METHOD *data;
1960
1961 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1962 return data->recv;
1963}
1964
1965/*
1966 * call-seq:
1967 * meth.name -> symbol
1968 *
1969 * Returns the name of the method.
1970 */
1971
1972static VALUE
1973method_name(VALUE obj)
1974{
1975 struct METHOD *data;
1976
1977 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1978 return ID2SYM(data->me->called_id);
1979}
1980
1981/*
1982 * call-seq:
1983 * meth.original_name -> symbol
1984 *
1985 * Returns the original name of the method.
1986 *
1987 * class C
1988 * def foo; end
1989 * alias bar foo
1990 * end
1991 * C.instance_method(:bar).original_name # => :foo
1992 */
1993
1994static VALUE
1995method_original_name(VALUE obj)
1996{
1997 struct METHOD *data;
1998
1999 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2000 return ID2SYM(data->me->def->original_id);
2001}
2002
2003/*
2004 * call-seq:
2005 * meth.owner -> class_or_module
2006 *
2007 * Returns the class or module on which this method is defined.
2008 * In other words,
2009 *
2010 * meth.owner.instance_methods(false).include?(meth.name) # => true
2011 *
2012 * holds as long as the method is not removed/undefined/replaced,
2013 * (with private_instance_methods instead of instance_methods if the method
2014 * is private).
2015 *
2016 * See also Method#receiver.
2017 *
2018 * (1..3).method(:map).owner #=> Enumerable
2019 */
2020
2021static VALUE
2022method_owner(VALUE obj)
2023{
2024 struct METHOD *data;
2025 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2026 return data->owner;
2027}
2028
2029static VALUE
2030method_namespace(VALUE obj)
2031{
2032 struct METHOD *data;
2033 const rb_namespace_t *ns;
2034
2035 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2036 ns = data->me->def->ns;
2037 if (!ns) return Qfalse;
2038 if (ns->ns_object) return ns->ns_object;
2039 // This should not happen
2040 rb_bug("Unexpected namespace on the method definition: %p", (void*) ns);
2041 return Qtrue;
2042}
2043
2044void
2045rb_method_name_error(VALUE klass, VALUE str)
2046{
2047#define MSG(s) rb_fstring_lit("undefined method '%1$s' for"s" '%2$s'")
2048 VALUE c = klass;
2049 VALUE s = Qundef;
2050
2051 if (RCLASS_SINGLETON_P(c)) {
2052 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
2053
2054 switch (BUILTIN_TYPE(obj)) {
2055 case T_MODULE:
2056 case T_CLASS:
2057 c = obj;
2058 break;
2059 default:
2060 break;
2061 }
2062 }
2063 else if (RB_TYPE_P(c, T_MODULE)) {
2064 s = MSG(" module");
2065 }
2066 if (UNDEF_P(s)) {
2067 s = MSG(" class");
2068 }
2069 rb_name_err_raise_str(s, c, str);
2070#undef MSG
2071}
2072
2073static VALUE
2074obj_method(VALUE obj, VALUE vid, int scope)
2075{
2076 ID id = rb_check_id(&vid);
2077 const VALUE klass = CLASS_OF(obj);
2078 const VALUE mclass = rb_cMethod;
2079
2080 if (!id) {
2081 VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
2082 if (m) return m;
2083 rb_method_name_error(klass, vid);
2084 }
2085 return mnew_callable(klass, obj, id, mclass, scope);
2086}
2087
2088/*
2089 * call-seq:
2090 * obj.method(sym) -> method
2091 *
2092 * Looks up the named method as a receiver in <i>obj</i>, returning a
2093 * +Method+ object (or raising NameError). The +Method+ object acts as a
2094 * closure in <i>obj</i>'s object instance, so instance variables and
2095 * the value of <code>self</code> remain available.
2096 *
2097 * class Demo
2098 * def initialize(n)
2099 * @iv = n
2100 * end
2101 * def hello()
2102 * "Hello, @iv = #{@iv}"
2103 * end
2104 * end
2105 *
2106 * k = Demo.new(99)
2107 * m = k.method(:hello)
2108 * m.call #=> "Hello, @iv = 99"
2109 *
2110 * l = Demo.new('Fred')
2111 * m = l.method("hello")
2112 * m.call #=> "Hello, @iv = Fred"
2113 *
2114 * Note that +Method+ implements <code>to_proc</code> method, which
2115 * means it can be used with iterators.
2116 *
2117 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
2118 *
2119 * out = File.open('test.txt', 'w')
2120 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
2121 *
2122 * require 'date'
2123 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
2124 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2125 */
2126
2127VALUE
2129{
2130 return obj_method(obj, vid, FALSE);
2131}
2132
2133/*
2134 * call-seq:
2135 * obj.public_method(sym) -> method
2136 *
2137 * Similar to _method_, searches public method only.
2138 */
2139
2140VALUE
2141rb_obj_public_method(VALUE obj, VALUE vid)
2142{
2143 return obj_method(obj, vid, TRUE);
2144}
2145
2146static VALUE
2147rb_obj_singleton_method_lookup(VALUE arg)
2148{
2149 VALUE *args = (VALUE *)arg;
2150 return rb_obj_method(args[0], args[1]);
2151}
2152
2153static VALUE
2154rb_obj_singleton_method_lookup_fail(VALUE arg1, VALUE arg2)
2155{
2156 return Qfalse;
2157}
2158
2159/*
2160 * call-seq:
2161 * obj.singleton_method(sym) -> method
2162 *
2163 * Similar to _method_, searches singleton method only.
2164 *
2165 * class Demo
2166 * def initialize(n)
2167 * @iv = n
2168 * end
2169 * def hello()
2170 * "Hello, @iv = #{@iv}"
2171 * end
2172 * end
2173 *
2174 * k = Demo.new(99)
2175 * def k.hi
2176 * "Hi, @iv = #{@iv}"
2177 * end
2178 * m = k.singleton_method(:hi)
2179 * m.call #=> "Hi, @iv = 99"
2180 * m = k.singleton_method(:hello) #=> NameError
2181 */
2182
2183VALUE
2184rb_obj_singleton_method(VALUE obj, VALUE vid)
2185{
2186 VALUE sc = rb_singleton_class_get(obj);
2187 VALUE klass;
2188 ID id = rb_check_id(&vid);
2189
2190 if (NIL_P(sc) ||
2191 NIL_P(klass = RCLASS_ORIGIN(sc)) ||
2192 !NIL_P(rb_special_singleton_class(obj))) {
2193 /* goto undef; */
2194 }
2195 else if (! id) {
2196 VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
2197 if (m) return m;
2198 /* else goto undef; */
2199 }
2200 else {
2201 VALUE args[2] = {obj, vid};
2202 VALUE ruby_method = rb_rescue(rb_obj_singleton_method_lookup, (VALUE)args, rb_obj_singleton_method_lookup_fail, Qfalse);
2203 if (ruby_method) {
2204 struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(ruby_method);
2205 VALUE lookup_class = RBASIC_CLASS(obj);
2206 VALUE stop_class = rb_class_superclass(sc);
2207 VALUE method_class = method->iclass;
2208
2209 /* Determine if method is in singleton class, or module included in or prepended to it */
2210 do {
2211 if (lookup_class == method_class) {
2212 return ruby_method;
2213 }
2214 lookup_class = RCLASS_SUPER(lookup_class);
2215 } while (lookup_class && lookup_class != stop_class);
2216 }
2217 }
2218
2219 /* undef: */
2220 vid = ID2SYM(id);
2221 rb_name_err_raise("undefined singleton method '%1$s' for '%2$s'",
2222 obj, vid);
2224}
2225
2226/*
2227 * call-seq:
2228 * mod.instance_method(symbol) -> unbound_method
2229 *
2230 * Returns an +UnboundMethod+ representing the given
2231 * instance method in _mod_.
2232 *
2233 * class Interpreter
2234 * def do_a() print "there, "; end
2235 * def do_d() print "Hello "; end
2236 * def do_e() print "!\n"; end
2237 * def do_v() print "Dave"; end
2238 * Dispatcher = {
2239 * "a" => instance_method(:do_a),
2240 * "d" => instance_method(:do_d),
2241 * "e" => instance_method(:do_e),
2242 * "v" => instance_method(:do_v)
2243 * }
2244 * def interpret(string)
2245 * string.each_char {|b| Dispatcher[b].bind(self).call }
2246 * end
2247 * end
2248 *
2249 * interpreter = Interpreter.new
2250 * interpreter.interpret('dave')
2251 *
2252 * <em>produces:</em>
2253 *
2254 * Hello there, Dave!
2255 */
2256
2257static VALUE
2258rb_mod_instance_method(VALUE mod, VALUE vid)
2259{
2260 ID id = rb_check_id(&vid);
2261 if (!id) {
2262 rb_method_name_error(mod, vid);
2263 }
2264 return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
2265}
2266
2267/*
2268 * call-seq:
2269 * mod.public_instance_method(symbol) -> unbound_method
2270 *
2271 * Similar to _instance_method_, searches public method only.
2272 */
2273
2274static VALUE
2275rb_mod_public_instance_method(VALUE mod, VALUE vid)
2276{
2277 ID id = rb_check_id(&vid);
2278 if (!id) {
2279 rb_method_name_error(mod, vid);
2280 }
2281 return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
2282}
2283
2284static VALUE
2285rb_mod_define_method_with_visibility(int argc, VALUE *argv, VALUE mod, const struct rb_scope_visi_struct* scope_visi)
2286{
2287 ID id;
2288 VALUE body;
2289 VALUE name;
2290 int is_method = FALSE;
2291
2292 rb_check_arity(argc, 1, 2);
2293 name = argv[0];
2294 id = rb_check_id(&name);
2295 if (argc == 1) {
2296 body = rb_block_lambda();
2297 }
2298 else {
2299 body = argv[1];
2300
2301 if (rb_obj_is_method(body)) {
2302 is_method = TRUE;
2303 }
2304 else if (rb_obj_is_proc(body)) {
2305 is_method = FALSE;
2306 }
2307 else {
2308 rb_raise(rb_eTypeError,
2309 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
2310 rb_obj_classname(body));
2311 }
2312 }
2313 if (!id) id = rb_to_id(name);
2314
2315 if (is_method) {
2316 struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(body);
2317 if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
2318 !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
2319 if (RCLASS_SINGLETON_P(method->me->owner)) {
2320 rb_raise(rb_eTypeError,
2321 "can't bind singleton method to a different class");
2322 }
2323 else {
2324 rb_raise(rb_eTypeError,
2325 "bind argument must be a subclass of % "PRIsVALUE,
2326 method->me->owner);
2327 }
2328 }
2329 rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
2330 if (scope_visi->module_func) {
2331 rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
2332 }
2333 RB_GC_GUARD(body);
2334 }
2335 else {
2336 VALUE procval = rb_proc_dup(body);
2337 if (vm_proc_iseq(procval) != NULL) {
2338 rb_proc_t *proc;
2339 GetProcPtr(procval, proc);
2340 proc->is_lambda = TRUE;
2341 proc->is_from_method = TRUE;
2342 }
2343 rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
2344 if (scope_visi->module_func) {
2345 rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
2346 }
2347 }
2348
2349 return ID2SYM(id);
2350}
2351
2352/*
2353 * call-seq:
2354 * define_method(symbol, method) -> symbol
2355 * define_method(symbol) { block } -> symbol
2356 *
2357 * Defines an instance method in the receiver. The _method_
2358 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2359 * If a block is specified, it is used as the method body.
2360 * If a block or the _method_ parameter has parameters,
2361 * they're used as method parameters.
2362 * This block is evaluated using #instance_eval.
2363 *
2364 * class A
2365 * def fred
2366 * puts "In Fred"
2367 * end
2368 * def create_method(name, &block)
2369 * self.class.define_method(name, &block)
2370 * end
2371 * define_method(:wilma) { puts "Charge it!" }
2372 * define_method(:flint) {|name| puts "I'm #{name}!"}
2373 * end
2374 * class B < A
2375 * define_method(:barney, instance_method(:fred))
2376 * end
2377 * a = B.new
2378 * a.barney
2379 * a.wilma
2380 * a.flint('Dino')
2381 * a.create_method(:betty) { p self }
2382 * a.betty
2383 *
2384 * <em>produces:</em>
2385 *
2386 * In Fred
2387 * Charge it!
2388 * I'm Dino!
2389 * #<B:0x401b39e8>
2390 */
2391
2392static VALUE
2393rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
2394{
2395 const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
2396 const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2397 const rb_scope_visibility_t *scope_visi = &default_scope_visi;
2398
2399 if (cref) {
2400 scope_visi = CREF_SCOPE_VISI(cref);
2401 }
2402
2403 return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
2404}
2405
2406/*
2407 * call-seq:
2408 * define_singleton_method(symbol, method) -> symbol
2409 * define_singleton_method(symbol) { block } -> symbol
2410 *
2411 * Defines a public singleton method in the receiver. The _method_
2412 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
2413 * If a block is specified, it is used as the method body.
2414 * If a block or a method has parameters, they're used as method parameters.
2415 *
2416 * class A
2417 * class << self
2418 * def class_name
2419 * to_s
2420 * end
2421 * end
2422 * end
2423 * A.define_singleton_method(:who_am_i) do
2424 * "I am: #{class_name}"
2425 * end
2426 * A.who_am_i # ==> "I am: A"
2427 *
2428 * guy = "Bob"
2429 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
2430 * guy.hello #=> "Bob: Hello there!"
2431 *
2432 * chris = "Chris"
2433 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
2434 * chris.greet("Hi") #=> "Hi, I'm Chris!"
2435 */
2436
2437static VALUE
2438rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
2439{
2440 VALUE klass = rb_singleton_class(obj);
2441 const rb_scope_visibility_t scope_visi = {METHOD_VISI_PUBLIC, FALSE};
2442
2443 return rb_mod_define_method_with_visibility(argc, argv, klass, &scope_visi);
2444}
2445
2446/*
2447 * define_method(symbol, method) -> symbol
2448 * define_method(symbol) { block } -> symbol
2449 *
2450 * Defines a global function by _method_ or the block.
2451 */
2452
2453static VALUE
2454top_define_method(int argc, VALUE *argv, VALUE obj)
2455{
2456 return rb_mod_define_method(argc, argv, rb_top_main_class("define_method"));
2457}
2458
2459/*
2460 * call-seq:
2461 * method.clone -> new_method
2462 *
2463 * Returns a clone of this method.
2464 *
2465 * class A
2466 * def foo
2467 * return "bar"
2468 * end
2469 * end
2470 *
2471 * m = A.new.method(:foo)
2472 * m.call # => "bar"
2473 * n = m.clone.call # => "bar"
2474 */
2475
2476static VALUE
2477method_clone(VALUE self)
2478{
2479 VALUE clone;
2480 struct METHOD *orig, *data;
2481
2482 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2483 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2484 rb_obj_clone_setup(self, clone, Qnil);
2485 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2486 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2487 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2488 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
2489 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2490 return clone;
2491}
2492
2493/* :nodoc: */
2494static VALUE
2495method_dup(VALUE self)
2496{
2497 VALUE clone;
2498 struct METHOD *orig, *data;
2499
2500 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
2501 clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
2502 rb_obj_dup_setup(self, clone);
2503 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
2504 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
2505 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
2506 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
2507 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
2508 return clone;
2509}
2510
2511/* Document-method: Method#===
2512 *
2513 * call-seq:
2514 * method === obj -> result_of_method
2515 *
2516 * Invokes the method with +obj+ as the parameter like #call.
2517 * This allows a method object to be the target of a +when+ clause
2518 * in a case statement.
2519 *
2520 * require 'prime'
2521 *
2522 * case 1373
2523 * when Prime.method(:prime?)
2524 * # ...
2525 * end
2526 */
2527
2528
2529/* Document-method: Method#[]
2530 *
2531 * call-seq:
2532 * meth[args, ...] -> obj
2533 *
2534 * Invokes the <i>meth</i> with the specified arguments, returning the
2535 * method's return value, like #call.
2536 *
2537 * m = 12.method("+")
2538 * m[3] #=> 15
2539 * m[20] #=> 32
2540 */
2541
2542/*
2543 * call-seq:
2544 * meth.call(args, ...) -> obj
2545 *
2546 * Invokes the <i>meth</i> with the specified arguments, returning the
2547 * method's return value.
2548 *
2549 * m = 12.method("+")
2550 * m.call(3) #=> 15
2551 * m.call(20) #=> 32
2552 */
2553
2554static VALUE
2555rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
2556{
2557 return rb_method_call_kw(argc, argv, method, RB_PASS_CALLED_KEYWORDS);
2558}
2559
2560VALUE
2561rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
2562{
2563 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2564 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
2565}
2566
2567VALUE
2568rb_method_call(int argc, const VALUE *argv, VALUE method)
2569{
2570 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2571 return rb_method_call_with_block(argc, argv, method, procval);
2572}
2573
2574static const rb_callable_method_entry_t *
2575method_callable_method_entry(const struct METHOD *data)
2576{
2577 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
2578 return (const rb_callable_method_entry_t *)data->me;
2579}
2580
2581static inline VALUE
2582call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
2583 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
2584{
2585 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2586 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
2587 method_callable_method_entry(data), kw_splat);
2588}
2589
2590VALUE
2591rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
2592{
2593 const struct METHOD *data;
2594 rb_execution_context_t *ec = GET_EC();
2595
2596 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2597 if (UNDEF_P(data->recv)) {
2598 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
2599 }
2600 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
2601}
2602
2603VALUE
2604rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
2605{
2606 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
2607}
2608
2609/**********************************************************************
2610 *
2611 * Document-class: UnboundMethod
2612 *
2613 * Ruby supports two forms of objectified methods. Class +Method+ is
2614 * used to represent methods that are associated with a particular
2615 * object: these method objects are bound to that object. Bound
2616 * method objects for an object can be created using Object#method.
2617 *
2618 * Ruby also supports unbound methods; methods objects that are not
2619 * associated with a particular object. These can be created either
2620 * by calling Module#instance_method or by calling #unbind on a bound
2621 * method object. The result of both of these is an UnboundMethod
2622 * object.
2623 *
2624 * Unbound methods can only be called after they are bound to an
2625 * object. That object must be a kind_of? the method's original
2626 * class.
2627 *
2628 * class Square
2629 * def area
2630 * @side * @side
2631 * end
2632 * def initialize(side)
2633 * @side = side
2634 * end
2635 * end
2636 *
2637 * area_un = Square.instance_method(:area)
2638 *
2639 * s = Square.new(12)
2640 * area = area_un.bind(s)
2641 * area.call #=> 144
2642 *
2643 * Unbound methods are a reference to the method at the time it was
2644 * objectified: subsequent changes to the underlying class will not
2645 * affect the unbound method.
2646 *
2647 * class Test
2648 * def test
2649 * :original
2650 * end
2651 * end
2652 * um = Test.instance_method(:test)
2653 * class Test
2654 * def test
2655 * :modified
2656 * end
2657 * end
2658 * t = Test.new
2659 * t.test #=> :modified
2660 * um.bind(t).call #=> :original
2661 *
2662 */
2663
2664static void
2665convert_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)
2666{
2667 VALUE methclass = data->owner;
2668 VALUE iclass = data->me->defined_class;
2669 VALUE klass = CLASS_OF(recv);
2670
2671 if (RB_TYPE_P(methclass, T_MODULE)) {
2672 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
2673 if (!NIL_P(refined_class)) methclass = refined_class;
2674 }
2675 if (!RB_TYPE_P(methclass, T_MODULE) && !RTEST(rb_obj_is_kind_of(recv, methclass))) {
2676 if (RCLASS_SINGLETON_P(methclass)) {
2677 rb_raise(rb_eTypeError,
2678 "singleton method called for a different object");
2679 }
2680 else {
2681 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
2682 methclass);
2683 }
2684 }
2685
2686 const rb_method_entry_t *me;
2687 if (clone) {
2688 me = rb_method_entry_clone(data->me);
2689 }
2690 else {
2691 me = data->me;
2692 }
2693
2694 if (RB_TYPE_P(me->owner, T_MODULE)) {
2695 if (!clone) {
2696 // if we didn't previously clone the method entry, then we need to clone it now
2697 // because this branch manipulates it in rb_method_entry_complement_defined_class
2698 me = rb_method_entry_clone(me);
2699 }
2700 VALUE ic = rb_class_search_ancestor(klass, me->owner);
2701 if (ic) {
2702 klass = ic;
2703 iclass = ic;
2704 }
2705 else {
2706 klass = rb_include_class_new(methclass, klass);
2707 }
2708 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
2709 }
2710
2711 *methclass_out = methclass;
2712 *klass_out = klass;
2713 *iclass_out = iclass;
2714 *me_out = me;
2715}
2716
2717/*
2718 * call-seq:
2719 * umeth.bind(obj) -> method
2720 *
2721 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
2722 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
2723 * be true.
2724 *
2725 * class A
2726 * def test
2727 * puts "In test, class = #{self.class}"
2728 * end
2729 * end
2730 * class B < A
2731 * end
2732 * class C < B
2733 * end
2734 *
2735 *
2736 * um = B.instance_method(:test)
2737 * bm = um.bind(C.new)
2738 * bm.call
2739 * bm = um.bind(B.new)
2740 * bm.call
2741 * bm = um.bind(A.new)
2742 * bm.call
2743 *
2744 * <em>produces:</em>
2745 *
2746 * In test, class = C
2747 * In test, class = B
2748 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
2749 * from prog.rb:16
2750 */
2751
2752static VALUE
2753umethod_bind(VALUE method, VALUE recv)
2754{
2755 VALUE methclass, klass, iclass;
2756 const rb_method_entry_t *me;
2757 const struct METHOD *data;
2758 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2759 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, true);
2760
2761 struct METHOD *bound;
2762 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
2763 RB_OBJ_WRITE(method, &bound->recv, recv);
2764 RB_OBJ_WRITE(method, &bound->klass, klass);
2765 RB_OBJ_WRITE(method, &bound->iclass, iclass);
2766 RB_OBJ_WRITE(method, &bound->owner, methclass);
2767 RB_OBJ_WRITE(method, &bound->me, me);
2768
2769 return method;
2770}
2771
2772/*
2773 * call-seq:
2774 * umeth.bind_call(recv, args, ...) -> obj
2775 *
2776 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
2777 * specified arguments.
2778 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
2779 */
2780static VALUE
2781umethod_bind_call(int argc, VALUE *argv, VALUE method)
2782{
2784 VALUE recv = argv[0];
2785 argc--;
2786 argv++;
2787
2788 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
2789 rb_execution_context_t *ec = GET_EC();
2790
2791 const struct METHOD *data;
2792 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2793
2794 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
2795 if (data->me == (const rb_method_entry_t *)cme) {
2796 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
2797 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
2798 }
2799 else {
2800 VALUE methclass, klass, iclass;
2801 const rb_method_entry_t *me;
2802 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, false);
2803 struct METHOD bound = { recv, klass, 0, methclass, me };
2804
2805 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
2806 }
2807}
2808
2809/*
2810 * Returns the number of required parameters and stores the maximum
2811 * number of parameters in max, or UNLIMITED_ARGUMENTS
2812 * if there is no maximum.
2813 */
2814static int
2815method_def_min_max_arity(const rb_method_definition_t *def, int *max)
2816{
2817 again:
2818 if (!def) return *max = 0;
2819 switch (def->type) {
2820 case VM_METHOD_TYPE_CFUNC:
2821 if (def->body.cfunc.argc < 0) {
2822 *max = UNLIMITED_ARGUMENTS;
2823 return 0;
2824 }
2825 return *max = check_argc(def->body.cfunc.argc);
2826 case VM_METHOD_TYPE_ZSUPER:
2827 *max = UNLIMITED_ARGUMENTS;
2828 return 0;
2829 case VM_METHOD_TYPE_ATTRSET:
2830 return *max = 1;
2831 case VM_METHOD_TYPE_IVAR:
2832 return *max = 0;
2833 case VM_METHOD_TYPE_ALIAS:
2834 def = def->body.alias.original_me->def;
2835 goto again;
2836 case VM_METHOD_TYPE_BMETHOD:
2837 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
2838 case VM_METHOD_TYPE_ISEQ:
2839 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
2840 case VM_METHOD_TYPE_UNDEF:
2841 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2842 return *max = 0;
2843 case VM_METHOD_TYPE_MISSING:
2844 *max = UNLIMITED_ARGUMENTS;
2845 return 0;
2846 case VM_METHOD_TYPE_OPTIMIZED: {
2847 switch (def->body.optimized.type) {
2848 case OPTIMIZED_METHOD_TYPE_SEND:
2849 *max = UNLIMITED_ARGUMENTS;
2850 return 0;
2851 case OPTIMIZED_METHOD_TYPE_CALL:
2852 *max = UNLIMITED_ARGUMENTS;
2853 return 0;
2854 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
2855 *max = UNLIMITED_ARGUMENTS;
2856 return 0;
2857 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
2858 *max = 0;
2859 return 0;
2860 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
2861 *max = 1;
2862 return 1;
2863 default:
2864 break;
2865 }
2866 break;
2867 }
2868 case VM_METHOD_TYPE_REFINED:
2869 *max = UNLIMITED_ARGUMENTS;
2870 return 0;
2871 }
2872 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
2874}
2875
2876static int
2877method_def_arity(const rb_method_definition_t *def)
2878{
2879 int max, min = method_def_min_max_arity(def, &max);
2880 return min == max ? min : -min-1;
2881}
2882
2883int
2884rb_method_entry_arity(const rb_method_entry_t *me)
2885{
2886 return method_def_arity(me->def);
2887}
2888
2889/*
2890 * call-seq:
2891 * meth.arity -> integer
2892 *
2893 * Returns an indication of the number of arguments accepted by a
2894 * method. Returns a nonnegative integer for methods that take a fixed
2895 * number of arguments. For Ruby methods that take a variable number of
2896 * arguments, returns -n-1, where n is the number of required arguments.
2897 * Keyword arguments will be considered as a single additional argument,
2898 * that argument being mandatory if any keyword argument is mandatory.
2899 * For methods written in C, returns -1 if the call takes a
2900 * variable number of arguments.
2901 *
2902 * class C
2903 * def one; end
2904 * def two(a); end
2905 * def three(*a); end
2906 * def four(a, b); end
2907 * def five(a, b, *c); end
2908 * def six(a, b, *c, &d); end
2909 * def seven(a, b, x:0); end
2910 * def eight(x:, y:); end
2911 * def nine(x:, y:, **z); end
2912 * def ten(*a, x:, y:); end
2913 * end
2914 * c = C.new
2915 * c.method(:one).arity #=> 0
2916 * c.method(:two).arity #=> 1
2917 * c.method(:three).arity #=> -1
2918 * c.method(:four).arity #=> 2
2919 * c.method(:five).arity #=> -3
2920 * c.method(:six).arity #=> -3
2921 * c.method(:seven).arity #=> -3
2922 * c.method(:eight).arity #=> 1
2923 * c.method(:nine).arity #=> 1
2924 * c.method(:ten).arity #=> -2
2925 *
2926 * "cat".method(:size).arity #=> 0
2927 * "cat".method(:replace).arity #=> 1
2928 * "cat".method(:squeeze).arity #=> -1
2929 * "cat".method(:count).arity #=> -1
2930 */
2931
2932static VALUE
2933method_arity_m(VALUE method)
2934{
2935 int n = method_arity(method);
2936 return INT2FIX(n);
2937}
2938
2939static int
2940method_arity(VALUE method)
2941{
2942 struct METHOD *data;
2943
2944 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2945 return rb_method_entry_arity(data->me);
2946}
2947
2948static const rb_method_entry_t *
2949original_method_entry(VALUE mod, ID id)
2950{
2951 const rb_method_entry_t *me;
2952
2953 while ((me = rb_method_entry(mod, id)) != 0) {
2954 const rb_method_definition_t *def = me->def;
2955 if (def->type != VM_METHOD_TYPE_ZSUPER) break;
2956 mod = RCLASS_SUPER(me->owner);
2957 id = def->original_id;
2958 }
2959 return me;
2960}
2961
2962static int
2963method_min_max_arity(VALUE method, int *max)
2964{
2965 const struct METHOD *data;
2966
2967 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
2968 return method_def_min_max_arity(data->me->def, max);
2969}
2970
2971int
2973{
2974 const rb_method_entry_t *me = original_method_entry(mod, id);
2975 if (!me) return 0; /* should raise? */
2976 return rb_method_entry_arity(me);
2977}
2978
2979int
2981{
2982 return rb_mod_method_arity(CLASS_OF(obj), id);
2983}
2984
2985VALUE
2986rb_callable_receiver(VALUE callable)
2987{
2988 if (rb_obj_is_proc(callable)) {
2989 VALUE binding = proc_binding(callable);
2990 return rb_funcall(binding, rb_intern("receiver"), 0);
2991 }
2992 else if (rb_obj_is_method(callable)) {
2993 return method_receiver(callable);
2994 }
2995 else {
2996 return Qundef;
2997 }
2998}
2999
3001rb_method_def(VALUE method)
3002{
3003 const struct METHOD *data;
3004
3005 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3006 return data->me->def;
3007}
3008
3009static const rb_iseq_t *
3010method_def_iseq(const rb_method_definition_t *def)
3011{
3012 switch (def->type) {
3013 case VM_METHOD_TYPE_ISEQ:
3014 return rb_iseq_check(def->body.iseq.iseqptr);
3015 case VM_METHOD_TYPE_BMETHOD:
3016 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
3017 case VM_METHOD_TYPE_ALIAS:
3018 return method_def_iseq(def->body.alias.original_me->def);
3019 case VM_METHOD_TYPE_CFUNC:
3020 case VM_METHOD_TYPE_ATTRSET:
3021 case VM_METHOD_TYPE_IVAR:
3022 case VM_METHOD_TYPE_ZSUPER:
3023 case VM_METHOD_TYPE_UNDEF:
3024 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3025 case VM_METHOD_TYPE_OPTIMIZED:
3026 case VM_METHOD_TYPE_MISSING:
3027 case VM_METHOD_TYPE_REFINED:
3028 break;
3029 }
3030 return NULL;
3031}
3032
3033const rb_iseq_t *
3034rb_method_iseq(VALUE method)
3035{
3036 return method_def_iseq(rb_method_def(method));
3037}
3038
3039static const rb_cref_t *
3040method_cref(VALUE method)
3041{
3042 const rb_method_definition_t *def = rb_method_def(method);
3043
3044 again:
3045 switch (def->type) {
3046 case VM_METHOD_TYPE_ISEQ:
3047 return def->body.iseq.cref;
3048 case VM_METHOD_TYPE_ALIAS:
3049 def = def->body.alias.original_me->def;
3050 goto again;
3051 default:
3052 return NULL;
3053 }
3054}
3055
3056static VALUE
3057method_def_location(const rb_method_definition_t *def)
3058{
3059 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
3060 if (!def->body.attr.location)
3061 return Qnil;
3062 return rb_ary_dup(def->body.attr.location);
3063 }
3064 return iseq_location(method_def_iseq(def));
3065}
3066
3067VALUE
3068rb_method_entry_location(const rb_method_entry_t *me)
3069{
3070 if (!me) return Qnil;
3071 return method_def_location(me->def);
3072}
3073
3074/*
3075 * call-seq:
3076 * meth.source_location -> [String, Integer, Integer, Integer, Integer]
3077 *
3078 * Returns the location where the method was defined.
3079 * The returned Array contains:
3080 * (1) the Ruby source filename
3081 * (2) the line number where the definition starts
3082 * (3) the column number where the definition starts
3083 * (4) the line number where the definition ends
3084 * (5) the column number where the definitions ends
3085 *
3086 * This method will return +nil+ if the method was not defined in Ruby (i.e. native).
3087 */
3088
3089VALUE
3090rb_method_location(VALUE method)
3091{
3092 return method_def_location(rb_method_def(method));
3093}
3094
3095static const rb_method_definition_t *
3096vm_proc_method_def(VALUE procval)
3097{
3098 const rb_proc_t *proc;
3099 const struct rb_block *block;
3100 const struct vm_ifunc *ifunc;
3101
3102 GetProcPtr(procval, proc);
3103 block = &proc->block;
3104
3105 if (vm_block_type(block) == block_type_ifunc &&
3106 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
3107 return rb_method_def((VALUE)ifunc->data);
3108 }
3109 else {
3110 return NULL;
3111 }
3112}
3113
3114static VALUE
3115method_def_parameters(const rb_method_definition_t *def)
3116{
3117 const rb_iseq_t *iseq;
3118 const rb_method_definition_t *bmethod_def;
3119
3120 switch (def->type) {
3121 case VM_METHOD_TYPE_ISEQ:
3122 iseq = method_def_iseq(def);
3123 return rb_iseq_parameters(iseq, 0);
3124 case VM_METHOD_TYPE_BMETHOD:
3125 if ((iseq = method_def_iseq(def)) != NULL) {
3126 return rb_iseq_parameters(iseq, 0);
3127 }
3128 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
3129 return method_def_parameters(bmethod_def);
3130 }
3131 break;
3132
3133 case VM_METHOD_TYPE_ALIAS:
3134 return method_def_parameters(def->body.alias.original_me->def);
3135
3136 case VM_METHOD_TYPE_OPTIMIZED:
3137 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
3138 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
3139 return rb_ary_new_from_args(1, param);
3140 }
3141 break;
3142
3143 case VM_METHOD_TYPE_CFUNC:
3144 case VM_METHOD_TYPE_ATTRSET:
3145 case VM_METHOD_TYPE_IVAR:
3146 case VM_METHOD_TYPE_ZSUPER:
3147 case VM_METHOD_TYPE_UNDEF:
3148 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3149 case VM_METHOD_TYPE_MISSING:
3150 case VM_METHOD_TYPE_REFINED:
3151 break;
3152 }
3153
3154 return rb_unnamed_parameters(method_def_arity(def));
3155
3156}
3157
3158/*
3159 * call-seq:
3160 * meth.parameters -> array
3161 *
3162 * Returns the parameter information of this method.
3163 *
3164 * def foo(bar); end
3165 * method(:foo).parameters #=> [[:req, :bar]]
3166 *
3167 * def foo(bar, baz, bat, &blk); end
3168 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
3169 *
3170 * def foo(bar, *args); end
3171 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
3172 *
3173 * def foo(bar, baz, *args, &blk); end
3174 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
3175 */
3176
3177static VALUE
3178rb_method_parameters(VALUE method)
3179{
3180 return method_def_parameters(rb_method_def(method));
3181}
3182
3183/*
3184 * call-seq:
3185 * meth.to_s -> string
3186 * meth.inspect -> string
3187 *
3188 * Returns a human-readable description of the underlying method.
3189 *
3190 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3191 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
3192 *
3193 * In the latter case, the method description includes the "owner" of the
3194 * original method (+Enumerable+ module, which is included into +Range+).
3195 *
3196 * +inspect+ also provides, when possible, method argument names (call
3197 * sequence) and source location.
3198 *
3199 * require 'net/http'
3200 * Net::HTTP.method(:get).inspect
3201 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
3202 *
3203 * <code>...</code> in argument definition means argument is optional (has
3204 * some default value).
3205 *
3206 * For methods defined in C (language core and extensions), location and
3207 * argument names can't be extracted, and only generic information is provided
3208 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
3209 * positional argument).
3210 *
3211 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
3212 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
3213
3214 */
3215
3216static VALUE
3217method_inspect(VALUE method)
3218{
3219 struct METHOD *data;
3220 VALUE str;
3221 const char *sharp = "#";
3222 VALUE mklass;
3223 VALUE defined_class;
3224
3225 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3226 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
3227
3228 mklass = data->iclass;
3229 if (!mklass) mklass = data->klass;
3230
3231 if (RB_TYPE_P(mklass, T_ICLASS)) {
3232 /* TODO: I'm not sure why mklass is T_ICLASS.
3233 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
3234 * but not sure it is needed.
3235 */
3236 mklass = RBASIC_CLASS(mklass);
3237 }
3238
3239 if (data->me->def->type == VM_METHOD_TYPE_ALIAS) {
3240 defined_class = data->me->def->body.alias.original_me->owner;
3241 }
3242 else {
3243 defined_class = method_entry_defined_class(data->me);
3244 }
3245
3246 if (RB_TYPE_P(defined_class, T_ICLASS)) {
3247 defined_class = RBASIC_CLASS(defined_class);
3248 }
3249
3250 if (UNDEF_P(data->recv)) {
3251 // UnboundMethod
3252 rb_str_buf_append(str, rb_inspect(defined_class));
3253 }
3254 else if (RCLASS_SINGLETON_P(mklass)) {
3255 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
3256
3257 if (UNDEF_P(data->recv)) {
3258 rb_str_buf_append(str, rb_inspect(mklass));
3259 }
3260 else if (data->recv == v) {
3262 sharp = ".";
3263 }
3264 else {
3265 rb_str_buf_append(str, rb_inspect(data->recv));
3266 rb_str_buf_cat2(str, "(");
3268 rb_str_buf_cat2(str, ")");
3269 sharp = ".";
3270 }
3271 }
3272 else {
3273 mklass = data->klass;
3274 if (RCLASS_SINGLETON_P(mklass)) {
3275 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
3276 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
3277 do {
3278 mklass = RCLASS_SUPER(mklass);
3279 } while (RB_TYPE_P(mklass, T_ICLASS));
3280 }
3281 }
3282 rb_str_buf_append(str, rb_inspect(mklass));
3283 if (defined_class != mklass) {
3284 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
3285 }
3286 }
3287 rb_str_buf_cat2(str, sharp);
3288 rb_str_append(str, rb_id2str(data->me->called_id));
3289 if (data->me->called_id != data->me->def->original_id) {
3290 rb_str_catf(str, "(%"PRIsVALUE")",
3291 rb_id2str(data->me->def->original_id));
3292 }
3293 if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
3294 rb_str_buf_cat2(str, " (not-implemented)");
3295 }
3296
3297 // parameter information
3298 {
3299 VALUE params = rb_method_parameters(method);
3300 VALUE pair, name, kind;
3301 const VALUE req = ID2SYM(rb_intern("req"));
3302 const VALUE opt = ID2SYM(rb_intern("opt"));
3303 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
3304 const VALUE key = ID2SYM(rb_intern("key"));
3305 const VALUE rest = ID2SYM(rb_intern("rest"));
3306 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
3307 const VALUE block = ID2SYM(rb_intern("block"));
3308 const VALUE nokey = ID2SYM(rb_intern("nokey"));
3309 int forwarding = 0;
3310
3311 rb_str_buf_cat2(str, "(");
3312
3313 if (RARRAY_LEN(params) == 3 &&
3314 RARRAY_AREF(RARRAY_AREF(params, 0), 0) == rest &&
3315 RARRAY_AREF(RARRAY_AREF(params, 0), 1) == ID2SYM('*') &&
3316 RARRAY_AREF(RARRAY_AREF(params, 1), 0) == keyrest &&
3317 RARRAY_AREF(RARRAY_AREF(params, 1), 1) == ID2SYM(idPow) &&
3318 RARRAY_AREF(RARRAY_AREF(params, 2), 0) == block &&
3319 RARRAY_AREF(RARRAY_AREF(params, 2), 1) == ID2SYM('&')) {
3320 forwarding = 1;
3321 }
3322
3323 for (int i = 0; i < RARRAY_LEN(params); i++) {
3324 pair = RARRAY_AREF(params, i);
3325 kind = RARRAY_AREF(pair, 0);
3326 name = RARRAY_AREF(pair, 1);
3327 // FIXME: in tests it turns out that kind, name = [:req] produces name to be false. Why?..
3328 if (NIL_P(name) || name == Qfalse) {
3329 // FIXME: can it be reduced to switch/case?
3330 if (kind == req || kind == opt) {
3331 name = rb_str_new2("_");
3332 }
3333 else if (kind == rest || kind == keyrest) {
3334 name = rb_str_new2("");
3335 }
3336 else if (kind == block) {
3337 name = rb_str_new2("block");
3338 }
3339 else if (kind == nokey) {
3340 name = rb_str_new2("nil");
3341 }
3342 }
3343
3344 if (kind == req) {
3345 rb_str_catf(str, "%"PRIsVALUE, name);
3346 }
3347 else if (kind == opt) {
3348 rb_str_catf(str, "%"PRIsVALUE"=...", name);
3349 }
3350 else if (kind == keyreq) {
3351 rb_str_catf(str, "%"PRIsVALUE":", name);
3352 }
3353 else if (kind == key) {
3354 rb_str_catf(str, "%"PRIsVALUE": ...", name);
3355 }
3356 else if (kind == rest) {
3357 if (name == ID2SYM('*')) {
3358 rb_str_cat_cstr(str, forwarding ? "..." : "*");
3359 }
3360 else {
3361 rb_str_catf(str, "*%"PRIsVALUE, name);
3362 }
3363 }
3364 else if (kind == keyrest) {
3365 if (name != ID2SYM(idPow)) {
3366 rb_str_catf(str, "**%"PRIsVALUE, name);
3367 }
3368 else if (i > 0) {
3369 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3370 }
3371 else {
3372 rb_str_cat_cstr(str, "**");
3373 }
3374 }
3375 else if (kind == block) {
3376 if (name == ID2SYM('&')) {
3377 if (forwarding) {
3378 rb_str_set_len(str, RSTRING_LEN(str) - 2);
3379 }
3380 else {
3381 rb_str_cat_cstr(str, "...");
3382 }
3383 }
3384 else {
3385 rb_str_catf(str, "&%"PRIsVALUE, name);
3386 }
3387 }
3388 else if (kind == nokey) {
3389 rb_str_buf_cat2(str, "**nil");
3390 }
3391
3392 if (i < RARRAY_LEN(params) - 1) {
3393 rb_str_buf_cat2(str, ", ");
3394 }
3395 }
3396 rb_str_buf_cat2(str, ")");
3397 }
3398
3399 { // source location
3400 VALUE loc = rb_method_location(method);
3401 if (!NIL_P(loc)) {
3402 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
3403 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
3404 }
3405 }
3406
3407 rb_str_buf_cat2(str, ">");
3408
3409 return str;
3410}
3411
3412static VALUE
3413bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
3414{
3415 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
3416}
3417
3418VALUE
3421 VALUE val)
3422{
3423 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
3424 return procval;
3425}
3426
3427/*
3428 * call-seq:
3429 * meth.to_proc -> proc
3430 *
3431 * Returns a Proc object corresponding to this method.
3432 */
3433
3434static VALUE
3435method_to_proc(VALUE method)
3436{
3437 VALUE procval;
3438 rb_proc_t *proc;
3439
3440 /*
3441 * class Method
3442 * def to_proc
3443 * lambda{|*args|
3444 * self.call(*args)
3445 * }
3446 * end
3447 * end
3448 */
3449 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
3450 GetProcPtr(procval, proc);
3451 proc->is_from_method = 1;
3452 return procval;
3453}
3454
3455extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
3456
3457/*
3458 * call-seq:
3459 * meth.super_method -> method
3460 *
3461 * Returns a +Method+ of superclass which would be called when super is used
3462 * or nil if there is no method on superclass.
3463 */
3464
3465static VALUE
3466method_super_method(VALUE method)
3467{
3468 const struct METHOD *data;
3469 VALUE super_class, iclass;
3470 ID mid;
3471 const rb_method_entry_t *me;
3472
3473 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3474 iclass = data->iclass;
3475 if (!iclass) return Qnil;
3476 if (data->me->def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
3477 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
3478 data->me->def->body.alias.original_me->owner));
3479 mid = data->me->def->body.alias.original_me->def->original_id;
3480 }
3481 else {
3482 super_class = RCLASS_SUPER(RCLASS_ORIGIN(iclass));
3483 mid = data->me->def->original_id;
3484 }
3485 if (!super_class) return Qnil;
3486 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(super_class, mid, &iclass);
3487 if (!me) return Qnil;
3488 return mnew_internal(me, me->owner, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
3489}
3490
3491/*
3492 * call-seq:
3493 * local_jump_error.exit_value -> obj
3494 *
3495 * Returns the exit value associated with this +LocalJumpError+.
3496 */
3497static VALUE
3498localjump_xvalue(VALUE exc)
3499{
3500 return rb_iv_get(exc, "@exit_value");
3501}
3502
3503/*
3504 * call-seq:
3505 * local_jump_error.reason -> symbol
3506 *
3507 * The reason this block was terminated:
3508 * :break, :redo, :retry, :next, :return, or :noreason.
3509 */
3510
3511static VALUE
3512localjump_reason(VALUE exc)
3513{
3514 return rb_iv_get(exc, "@reason");
3515}
3516
3517rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
3518
3519static const rb_env_t *
3520env_clone(const rb_env_t *env, const rb_cref_t *cref)
3521{
3522 VALUE *new_ep;
3523 VALUE *new_body;
3524 const rb_env_t *new_env;
3525
3526 VM_ASSERT(env->ep > env->env);
3527 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
3528
3529 if (cref == NULL) {
3530 cref = rb_vm_cref_new_toplevel();
3531 }
3532
3533 new_body = ALLOC_N(VALUE, env->env_size);
3534 new_ep = &new_body[env->ep - env->env];
3535 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
3536
3537 /* The memcpy has to happen after the vm_env_new because it can trigger a
3538 * GC compaction which can move the objects in the env. */
3539 MEMCPY(new_body, env->env, VALUE, env->env_size);
3540 /* VM_ENV_DATA_INDEX_ENV is set in vm_env_new but will get overwritten
3541 * by the memcpy above. */
3542 new_ep[VM_ENV_DATA_INDEX_ENV] = (VALUE)new_env;
3543 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
3544 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
3545 return new_env;
3546}
3547
3548/*
3549 * call-seq:
3550 * prc.binding -> binding
3551 *
3552 * Returns the binding associated with <i>prc</i>.
3553 *
3554 * def fred(param)
3555 * proc {}
3556 * end
3557 *
3558 * b = fred(99)
3559 * eval("param", b.binding) #=> 99
3560 */
3561static VALUE
3562proc_binding(VALUE self)
3563{
3564 VALUE bindval, binding_self = Qundef;
3565 rb_binding_t *bind;
3566 const rb_proc_t *proc;
3567 const rb_iseq_t *iseq = NULL;
3568 const struct rb_block *block;
3569 const rb_env_t *env = NULL;
3570
3571 GetProcPtr(self, proc);
3572 block = &proc->block;
3573
3574 if (proc->is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
3575
3576 again:
3577 switch (vm_block_type(block)) {
3578 case block_type_iseq:
3579 iseq = block->as.captured.code.iseq;
3580 binding_self = block->as.captured.self;
3581 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3582 break;
3583 case block_type_proc:
3584 GetProcPtr(block->as.proc, proc);
3585 block = &proc->block;
3586 goto again;
3587 case block_type_ifunc:
3588 {
3589 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
3590 if (IS_METHOD_PROC_IFUNC(ifunc)) {
3591 VALUE method = (VALUE)ifunc->data;
3592 VALUE name = rb_fstring_lit("<empty_iseq>");
3593 rb_iseq_t *empty;
3594 binding_self = method_receiver(method);
3595 iseq = rb_method_iseq(method);
3596 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
3597 env = env_clone(env, method_cref(method));
3598 /* set empty iseq */
3599 empty = rb_iseq_new(Qnil, name, name, Qnil, 0, ISEQ_TYPE_TOP);
3600 RB_OBJ_WRITE(env, &env->iseq, empty);
3601 break;
3602 }
3603 }
3604 /* FALLTHROUGH */
3605 case block_type_symbol:
3606 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
3608 }
3609
3610 bindval = rb_binding_alloc(rb_cBinding);
3611 GetBindingPtr(bindval, bind);
3612 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
3613 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
3614 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
3615 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
3616
3617 if (iseq) {
3618 rb_iseq_check(iseq);
3619 RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(iseq)->location.pathobj);
3620 bind->first_lineno = ISEQ_BODY(iseq)->location.first_lineno;
3621 }
3622 else {
3623 RB_OBJ_WRITE(bindval, &bind->pathobj,
3624 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil));
3625 bind->first_lineno = 1;
3626 }
3627
3628 return bindval;
3629}
3630
3631static rb_block_call_func curry;
3632
3633static VALUE
3634make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
3635{
3636 VALUE args = rb_ary_new3(3, proc, passed, arity);
3637 rb_proc_t *procp;
3638 int is_lambda;
3639
3640 GetProcPtr(proc, procp);
3641 is_lambda = procp->is_lambda;
3642 rb_ary_freeze(passed);
3643 rb_ary_freeze(args);
3644 proc = rb_proc_new(curry, args);
3645 GetProcPtr(proc, procp);
3646 procp->is_lambda = is_lambda;
3647 return proc;
3648}
3649
3650static VALUE
3651curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3652{
3653 VALUE proc, passed, arity;
3654 proc = RARRAY_AREF(args, 0);
3655 passed = RARRAY_AREF(args, 1);
3656 arity = RARRAY_AREF(args, 2);
3657
3658 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
3659 rb_ary_freeze(passed);
3660
3661 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
3662 if (!NIL_P(blockarg)) {
3663 rb_warn("given block not used");
3664 }
3665 arity = make_curry_proc(proc, passed, arity);
3666 return arity;
3667 }
3668 else {
3669 return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
3670 }
3671}
3672
3673 /*
3674 * call-seq:
3675 * prc.curry -> a_proc
3676 * prc.curry(arity) -> a_proc
3677 *
3678 * Returns a curried proc. If the optional <i>arity</i> argument is given,
3679 * it determines the number of arguments.
3680 * A curried proc receives some arguments. If a sufficient number of
3681 * arguments are supplied, it passes the supplied arguments to the original
3682 * proc and returns the result. Otherwise, returns another curried proc that
3683 * takes the rest of arguments.
3684 *
3685 * The optional <i>arity</i> argument should be supplied when currying procs with
3686 * variable arguments to determine how many arguments are needed before the proc is
3687 * called.
3688 *
3689 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
3690 * p b.curry[1][2][3] #=> 6
3691 * p b.curry[1, 2][3, 4] #=> 6
3692 * p b.curry(5)[1][2][3][4][5] #=> 6
3693 * p b.curry(5)[1, 2][3, 4][5] #=> 6
3694 * p b.curry(1)[1] #=> 1
3695 *
3696 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3697 * p b.curry[1][2][3] #=> 6
3698 * p b.curry[1, 2][3, 4] #=> 10
3699 * p b.curry(5)[1][2][3][4][5] #=> 15
3700 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3701 * p b.curry(1)[1] #=> 1
3702 *
3703 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
3704 * p b.curry[1][2][3] #=> 6
3705 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
3706 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
3707 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3708 *
3709 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
3710 * p b.curry[1][2][3] #=> 6
3711 * p b.curry[1, 2][3, 4] #=> 10
3712 * p b.curry(5)[1][2][3][4][5] #=> 15
3713 * p b.curry(5)[1, 2][3, 4][5] #=> 15
3714 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
3715 *
3716 * b = proc { :foo }
3717 * p b.curry[] #=> :foo
3718 */
3719static VALUE
3720proc_curry(int argc, const VALUE *argv, VALUE self)
3721{
3722 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
3723 VALUE arity;
3724
3725 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
3726 arity = INT2FIX(min_arity);
3727 }
3728 else {
3729 sarity = FIX2INT(arity);
3730 if (rb_proc_lambda_p(self)) {
3731 rb_check_arity(sarity, min_arity, max_arity);
3732 }
3733 }
3734
3735 return make_curry_proc(self, rb_ary_new(), arity);
3736}
3737
3738/*
3739 * call-seq:
3740 * meth.curry -> proc
3741 * meth.curry(arity) -> proc
3742 *
3743 * Returns a curried proc based on the method. When the proc is called with a number of
3744 * arguments that is lower than the method's arity, then another curried proc is returned.
3745 * Only when enough arguments have been supplied to satisfy the method signature, will the
3746 * method actually be called.
3747 *
3748 * The optional <i>arity</i> argument should be supplied when currying methods with
3749 * variable arguments to determine how many arguments are needed before the method is
3750 * called.
3751 *
3752 * def foo(a,b,c)
3753 * [a, b, c]
3754 * end
3755 *
3756 * proc = self.method(:foo).curry
3757 * proc2 = proc.call(1, 2) #=> #<Proc>
3758 * proc2.call(3) #=> [1,2,3]
3759 *
3760 * def vararg(*args)
3761 * args
3762 * end
3763 *
3764 * proc = self.method(:vararg).curry(4)
3765 * proc2 = proc.call(:x) #=> #<Proc>
3766 * proc3 = proc2.call(:y, :z) #=> #<Proc>
3767 * proc3.call(:a) #=> [:x, :y, :z, :a]
3768 */
3769
3770static VALUE
3771rb_method_curry(int argc, const VALUE *argv, VALUE self)
3772{
3773 VALUE proc = method_to_proc(self);
3774 return proc_curry(argc, argv, proc);
3775}
3776
3777static VALUE
3778compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
3779{
3780 VALUE f, g, fargs;
3781 f = RARRAY_AREF(args, 0);
3782 g = RARRAY_AREF(args, 1);
3783
3784 if (rb_obj_is_proc(g))
3785 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3786 else
3787 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
3788
3789 if (rb_obj_is_proc(f))
3790 return rb_proc_call(f, rb_ary_new3(1, fargs));
3791 else
3792 return rb_funcallv(f, idCall, 1, &fargs);
3793}
3794
3795static VALUE
3796to_callable(VALUE f)
3797{
3798 VALUE mesg;
3799
3800 if (rb_obj_is_proc(f)) return f;
3801 if (rb_obj_is_method(f)) return f;
3802 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
3803 mesg = rb_fstring_lit("callable object is expected");
3805}
3806
3807static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
3808static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
3809
3810/*
3811 * call-seq:
3812 * prc << g -> a_proc
3813 *
3814 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3815 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3816 * then calls this proc with the result.
3817 *
3818 * f = proc {|x| x * x }
3819 * g = proc {|x| x + x }
3820 * p (f << g).call(2) #=> 16
3821 *
3822 * See Proc#>> for detailed explanations.
3823 */
3824static VALUE
3825proc_compose_to_left(VALUE self, VALUE g)
3826{
3827 return rb_proc_compose_to_left(self, to_callable(g));
3828}
3829
3830static VALUE
3831rb_proc_compose_to_left(VALUE self, VALUE g)
3832{
3833 VALUE proc, args, procs[2];
3834 rb_proc_t *procp;
3835 int is_lambda;
3836
3837 procs[0] = self;
3838 procs[1] = g;
3839 args = rb_ary_tmp_new_from_values(0, 2, procs);
3840
3841 if (rb_obj_is_proc(g)) {
3842 GetProcPtr(g, procp);
3843 is_lambda = procp->is_lambda;
3844 }
3845 else {
3846 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
3847 is_lambda = 1;
3848 }
3849
3850 proc = rb_proc_new(compose, args);
3851 GetProcPtr(proc, procp);
3852 procp->is_lambda = is_lambda;
3853
3854 return proc;
3855}
3856
3857/*
3858 * call-seq:
3859 * prc >> g -> a_proc
3860 *
3861 * Returns a proc that is the composition of this proc and the given <i>g</i>.
3862 * The returned proc takes a variable number of arguments, calls this proc with them
3863 * then calls <i>g</i> with the result.
3864 *
3865 * f = proc {|x| x * x }
3866 * g = proc {|x| x + x }
3867 * p (f >> g).call(2) #=> 8
3868 *
3869 * <i>g</i> could be other Proc, or Method, or any other object responding to
3870 * +call+ method:
3871 *
3872 * class Parser
3873 * def self.call(text)
3874 * # ...some complicated parsing logic...
3875 * end
3876 * end
3877 *
3878 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
3879 * pipeline.call('data.json')
3880 *
3881 * See also Method#>> and Method#<<.
3882 */
3883static VALUE
3884proc_compose_to_right(VALUE self, VALUE g)
3885{
3886 return rb_proc_compose_to_right(self, to_callable(g));
3887}
3888
3889static VALUE
3890rb_proc_compose_to_right(VALUE self, VALUE g)
3891{
3892 VALUE proc, args, procs[2];
3893 rb_proc_t *procp;
3894 int is_lambda;
3895
3896 procs[0] = g;
3897 procs[1] = self;
3898 args = rb_ary_tmp_new_from_values(0, 2, procs);
3899
3900 GetProcPtr(self, procp);
3901 is_lambda = procp->is_lambda;
3902
3903 proc = rb_proc_new(compose, args);
3904 GetProcPtr(proc, procp);
3905 procp->is_lambda = is_lambda;
3906
3907 return proc;
3908}
3909
3910/*
3911 * call-seq:
3912 * meth << g -> a_proc
3913 *
3914 * Returns a proc that is the composition of this method and the given <i>g</i>.
3915 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
3916 * then calls this method with the result.
3917 *
3918 * def f(x)
3919 * x * x
3920 * end
3921 *
3922 * f = self.method(:f)
3923 * g = proc {|x| x + x }
3924 * p (f << g).call(2) #=> 16
3925 */
3926static VALUE
3927rb_method_compose_to_left(VALUE self, VALUE g)
3928{
3929 g = to_callable(g);
3930 self = method_to_proc(self);
3931 return proc_compose_to_left(self, g);
3932}
3933
3934/*
3935 * call-seq:
3936 * meth >> g -> a_proc
3937 *
3938 * Returns a proc that is the composition of this method and the given <i>g</i>.
3939 * The returned proc takes a variable number of arguments, calls this method
3940 * with them then calls <i>g</i> with the result.
3941 *
3942 * def f(x)
3943 * x * x
3944 * end
3945 *
3946 * f = self.method(:f)
3947 * g = proc {|x| x + x }
3948 * p (f >> g).call(2) #=> 8
3949 */
3950static VALUE
3951rb_method_compose_to_right(VALUE self, VALUE g)
3952{
3953 g = to_callable(g);
3954 self = method_to_proc(self);
3955 return proc_compose_to_right(self, g);
3956}
3957
3958/*
3959 * call-seq:
3960 * proc.ruby2_keywords -> proc
3961 *
3962 * Marks the proc as passing keywords through a normal argument splat.
3963 * This should only be called on procs that accept an argument splat
3964 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
3965 * marks the proc such that if the proc is called with keyword arguments,
3966 * the final hash argument is marked with a special flag such that if it
3967 * is the final element of a normal argument splat to another method call,
3968 * and that method call does not include explicit keywords or a keyword
3969 * splat, the final element is interpreted as keywords. In other words,
3970 * keywords will be passed through the proc to other methods.
3971 *
3972 * This should only be used for procs that delegate keywords to another
3973 * method, and only for backwards compatibility with Ruby versions before
3974 * 2.7.
3975 *
3976 * This method will probably be removed at some point, as it exists only
3977 * for backwards compatibility. As it does not exist in Ruby versions
3978 * before 2.7, check that the proc responds to this method before calling
3979 * it. Also, be aware that if this method is removed, the behavior of the
3980 * proc will change so that it does not pass through keywords.
3981 *
3982 * module Mod
3983 * foo = ->(meth, *args, &block) do
3984 * send(:"do_#{meth}", *args, &block)
3985 * end
3986 * foo.ruby2_keywords if foo.respond_to?(:ruby2_keywords)
3987 * end
3988 */
3989
3990static VALUE
3991proc_ruby2_keywords(VALUE procval)
3992{
3993 rb_proc_t *proc;
3994 GetProcPtr(procval, proc);
3995
3996 rb_check_frozen(procval);
3997
3998 if (proc->is_from_method) {
3999 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
4000 return procval;
4001 }
4002
4003 switch (proc->block.type) {
4004 case block_type_iseq:
4005 if (ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_rest &&
4006 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kw &&
4007 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kwrest) {
4008 ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.ruby2_keywords = 1;
4009 }
4010 else {
4011 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or proc does not accept argument splat)");
4012 }
4013 break;
4014 default:
4015 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
4016 break;
4017 }
4018
4019 return procval;
4020}
4021
4022/*
4023 * Document-class: LocalJumpError
4024 *
4025 * Raised when Ruby can't yield as requested.
4026 *
4027 * A typical scenario is attempting to yield when no block is given:
4028 *
4029 * def call_block
4030 * yield 42
4031 * end
4032 * call_block
4033 *
4034 * <em>raises the exception:</em>
4035 *
4036 * LocalJumpError: no block given (yield)
4037 *
4038 * A more subtle example:
4039 *
4040 * def get_me_a_return
4041 * Proc.new { return 42 }
4042 * end
4043 * get_me_a_return.call
4044 *
4045 * <em>raises the exception:</em>
4046 *
4047 * LocalJumpError: unexpected return
4048 */
4049
4050/*
4051 * Document-class: SystemStackError
4052 *
4053 * Raised in case of a stack overflow.
4054 *
4055 * def me_myself_and_i
4056 * me_myself_and_i
4057 * end
4058 * me_myself_and_i
4059 *
4060 * <em>raises the exception:</em>
4061 *
4062 * SystemStackError: stack level too deep
4063 */
4064
4065/*
4066 * Document-class: Proc
4067 *
4068 * A +Proc+ object is an encapsulation of a block of code, which can be stored
4069 * in a local variable, passed to a method or another Proc, and can be called.
4070 * Proc is an essential concept in Ruby and a core of its functional
4071 * programming features.
4072 *
4073 * square = Proc.new {|x| x**2 }
4074 *
4075 * square.call(3) #=> 9
4076 * # shorthands:
4077 * square.(3) #=> 9
4078 * square[3] #=> 9
4079 *
4080 * Proc objects are _closures_, meaning they remember and can use the entire
4081 * context in which they were created.
4082 *
4083 * def gen_times(factor)
4084 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
4085 * end
4086 *
4087 * times3 = gen_times(3)
4088 * times5 = gen_times(5)
4089 *
4090 * times3.call(12) #=> 36
4091 * times5.call(5) #=> 25
4092 * times3.call(times5.call(4)) #=> 60
4093 *
4094 * == Creation
4095 *
4096 * There are several methods to create a Proc
4097 *
4098 * * Use the Proc class constructor:
4099 *
4100 * proc1 = Proc.new {|x| x**2 }
4101 *
4102 * * Use the Kernel#proc method as a shorthand of Proc.new:
4103 *
4104 * proc2 = proc {|x| x**2 }
4105 *
4106 * * Receiving a block of code into proc argument (note the <code>&</code>):
4107 *
4108 * def make_proc(&block)
4109 * block
4110 * end
4111 *
4112 * proc3 = make_proc {|x| x**2 }
4113 *
4114 * * Construct a proc with lambda semantics using the Kernel#lambda method
4115 * (see below for explanations about lambdas):
4116 *
4117 * lambda1 = lambda {|x| x**2 }
4118 *
4119 * * Use the {Lambda proc literal}[rdoc-ref:syntax/literals.rdoc@Lambda+Proc+Literals] syntax
4120 * (also constructs a proc with lambda semantics):
4121 *
4122 * lambda2 = ->(x) { x**2 }
4123 *
4124 * == Lambda and non-lambda semantics
4125 *
4126 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
4127 * Differences are:
4128 *
4129 * * In lambdas, +return+ and +break+ means exit from this lambda;
4130 * * In non-lambda procs, +return+ means exit from embracing method
4131 * (and will throw +LocalJumpError+ if invoked outside the method);
4132 * * In non-lambda procs, +break+ means exit from the method which the block given for.
4133 * (and will throw +LocalJumpError+ if invoked after the method returns);
4134 * * In lambdas, arguments are treated in the same way as in methods: strict,
4135 * with +ArgumentError+ for mismatching argument number,
4136 * and no additional argument processing;
4137 * * Regular procs accept arguments more generously: missing arguments
4138 * are filled with +nil+, single Array arguments are deconstructed if the
4139 * proc has multiple arguments, and there is no error raised on extra
4140 * arguments.
4141 *
4142 * Examples:
4143 *
4144 * # +return+ in non-lambda proc, +b+, exits +m2+.
4145 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
4146 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
4147 * #=> []
4148 *
4149 * # +break+ in non-lambda proc, +b+, exits +m1+.
4150 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
4151 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
4152 * #=> [:m2]
4153 *
4154 * # +next+ in non-lambda proc, +b+, exits the block.
4155 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
4156 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
4157 * #=> [:m1, :m2]
4158 *
4159 * # Using +proc+ method changes the behavior as follows because
4160 * # The block is given for +proc+ method and embraced by +m2+.
4161 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
4162 * #=> []
4163 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
4164 * # break from proc-closure (LocalJumpError)
4165 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
4166 * #=> [:m1, :m2]
4167 *
4168 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
4169 * # (+lambda+ method behaves same.)
4170 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
4171 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
4172 * #=> [:m1, :m2]
4173 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
4174 * #=> [:m1, :m2]
4175 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
4176 * #=> [:m1, :m2]
4177 *
4178 * p = proc {|x, y| "x=#{x}, y=#{y}" }
4179 * p.call(1, 2) #=> "x=1, y=2"
4180 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
4181 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
4182 * p.call(1) #=> "x=1, y=", nil substituted instead of error
4183 *
4184 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
4185 * l.call(1, 2) #=> "x=1, y=2"
4186 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
4187 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
4188 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
4189 *
4190 * def test_return
4191 * -> { return 3 }.call # just returns from lambda into method body
4192 * proc { return 4 }.call # returns from method
4193 * return 5
4194 * end
4195 *
4196 * test_return # => 4, return from proc
4197 *
4198 * Lambdas are useful as self-sufficient functions, in particular useful as
4199 * arguments to higher-order functions, behaving exactly like Ruby methods.
4200 *
4201 * Procs are useful for implementing iterators:
4202 *
4203 * def test
4204 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
4205 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4206 * end
4207 *
4208 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
4209 * which means that the internal arrays will be deconstructed to pairs of
4210 * arguments, and +return+ will exit from the method +test+. That would
4211 * not be possible with a stricter lambda.
4212 *
4213 * You can tell a lambda from a regular proc by using the #lambda? instance method.
4214 *
4215 * Lambda semantics is typically preserved during the proc lifetime, including
4216 * <code>&</code>-deconstruction to a block of code:
4217 *
4218 * p = proc {|x, y| x }
4219 * l = lambda {|x, y| x }
4220 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
4221 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
4222 *
4223 * The only exception is dynamic method definition: even if defined by
4224 * passing a non-lambda proc, methods still have normal semantics of argument
4225 * checking.
4226 *
4227 * class C
4228 * define_method(:e, &proc {})
4229 * end
4230 * C.new.e(1,2) #=> ArgumentError
4231 * C.new.method(:e).to_proc.lambda? #=> true
4232 *
4233 * This exception ensures that methods never have unusual argument passing
4234 * conventions, and makes it easy to have wrappers defining methods that
4235 * behave as usual.
4236 *
4237 * class C
4238 * def self.def2(name, &body)
4239 * define_method(name, &body)
4240 * end
4241 *
4242 * def2(:f) {}
4243 * end
4244 * C.new.f(1,2) #=> ArgumentError
4245 *
4246 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
4247 * yet defines a method which has normal semantics.
4248 *
4249 * == Conversion of other objects to procs
4250 *
4251 * Any object that implements the +to_proc+ method can be converted into
4252 * a proc by the <code>&</code> operator, and therefore can be
4253 * consumed by iterators.
4254 *
4255 * class Greeter
4256 * def initialize(greeting)
4257 * @greeting = greeting
4258 * end
4259 *
4260 * def to_proc
4261 * proc {|name| "#{@greeting}, #{name}!" }
4262 * end
4263 * end
4264 *
4265 * hi = Greeter.new("Hi")
4266 * hey = Greeter.new("Hey")
4267 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
4268 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
4269 *
4270 * Of the Ruby core classes, this method is implemented by +Symbol+,
4271 * +Method+, and +Hash+.
4272 *
4273 * :to_s.to_proc.call(1) #=> "1"
4274 * [1, 2].map(&:to_s) #=> ["1", "2"]
4275 *
4276 * method(:puts).to_proc.call(1) # prints 1
4277 * [1, 2].each(&method(:puts)) # prints 1, 2
4278 *
4279 * {test: 1}.to_proc.call(:test) #=> 1
4280 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
4281 *
4282 * == Orphaned Proc
4283 *
4284 * +return+ and +break+ in a block exit a method.
4285 * If a Proc object is generated from the block and the Proc object
4286 * survives until the method is returned, +return+ and +break+ cannot work.
4287 * In such case, +return+ and +break+ raises LocalJumpError.
4288 * A Proc object in such situation is called as orphaned Proc object.
4289 *
4290 * Note that the method to exit is different for +return+ and +break+.
4291 * There is a situation that orphaned for +break+ but not orphaned for +return+.
4292 *
4293 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
4294 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
4295 *
4296 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
4297 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
4298 *
4299 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
4300 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
4301 *
4302 * Since +return+ and +break+ exits the block itself in lambdas,
4303 * lambdas cannot be orphaned.
4304 *
4305 * == Anonymous block parameters
4306 *
4307 * To simplify writing short blocks, Ruby provides two different types of
4308 * anonymous parameters: +it+ (single parameter) and numbered ones: <tt>_1</tt>,
4309 * <tt>_2</tt> and so on.
4310 *
4311 * # Explicit parameter:
4312 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
4313 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
4314 *
4315 * # it:
4316 * %w[test me please].each { puts it.upcase } # prints TEST, ME, PLEASE
4317 * (1..5).map { it**2 } # => [1, 4, 9, 16, 25]
4318 *
4319 * # Numbered parameter:
4320 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4321 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
4322 *
4323 * === +it+
4324 *
4325 * +it+ is a name that is available inside a block when no explicit parameters
4326 * defined, as shown above.
4327 *
4328 * %w[test me please].each { puts it.upcase } # prints TEST, ME, PLEASE
4329 * (1..5).map { it**2 } # => [1, 4, 9, 16, 25]
4330 *
4331 * +it+ is a "soft keyword": it is not a reserved name, and can be used as
4332 * a name for methods and local variables:
4333 *
4334 * it = 5 # no warnings
4335 * def it(&block) # RSpec-like API, no warnings
4336 * # ...
4337 * end
4338 *
4339 * +it+ can be used as a local variable even in blocks that use it as an
4340 * implicit parameter (though this style is obviously confusing):
4341 *
4342 * [1, 2, 3].each {
4343 * # takes a value of implicit parameter "it" and uses it to
4344 * # define a local variable with the same name
4345 * it = it**2
4346 * p it
4347 * }
4348 *
4349 * In a block with explicit parameters defined +it+ usage raises an exception:
4350 *
4351 * [1, 2, 3].each { |x| p it }
4352 * # syntax error found (SyntaxError)
4353 * # [1, 2, 3].each { |x| p it }
4354 * # ^~ 'it' is not allowed when an ordinary parameter is defined
4355 *
4356 * But if a local name (variable or method) is available, it would be used:
4357 *
4358 * it = 5
4359 * [1, 2, 3].each { |x| p it }
4360 * # Prints 5, 5, 5
4361 *
4362 * Blocks using +it+ can be nested:
4363 *
4364 * %w[test me].each { it.each_char { p it } }
4365 * # Prints "t", "e", "s", "t", "m", "e"
4366 *
4367 * Blocks using +it+ are considered to have one parameter:
4368 *
4369 * p = proc { it**2 }
4370 * l = lambda { it**2 }
4371 * p.parameters # => [[:opt]]
4372 * p.arity # => 1
4373 * l.parameters # => [[:req]]
4374 * l.arity # => 1
4375 *
4376 * === Numbered parameters
4377 *
4378 * Numbered parameters are another way to name block parameters implicitly.
4379 * Unlike +it+, numbered parameters allow to refer to several parameters
4380 * in one block.
4381 *
4382 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
4383 * {a: 100, b: 200}.map { "#{_1} = #{_2}" } # => "a = 100", "b = 200"
4384 *
4385 * Parameter names from +_1+ to +_9+ are supported:
4386 *
4387 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
4388 * # => [120, 150, 180]
4389 *
4390 * Though, it is advised to resort to them wisely, probably limiting
4391 * yourself to +_1+ and +_2+, and to one-line blocks.
4392 *
4393 * Numbered parameters can't be used together with explicitly named
4394 * ones:
4395 *
4396 * [10, 20, 30].map { |x| _1**2 }
4397 * # SyntaxError (ordinary parameter is defined)
4398 *
4399 * Numbered parameters can't be mixed with +it+ either:
4400 *
4401 * [10, 20, 30].map { _1 + it }
4402 * # SyntaxError: 'it' is not allowed when a numbered parameter is already used
4403 *
4404 * To avoid conflicts, naming local variables or method
4405 * arguments +_1+, +_2+ and so on, causes an error.
4406 *
4407 * _1 = 'test'
4408 * # ^~ _1 is reserved for numbered parameters (SyntaxError)
4409 *
4410 * Using implicit numbered parameters affects block's arity:
4411 *
4412 * p = proc { _1 + _2 }
4413 * l = lambda { _1 + _2 }
4414 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
4415 * p.arity # => 2
4416 * l.parameters # => [[:req, :_1], [:req, :_2]]
4417 * l.arity # => 2
4418 *
4419 * Blocks with numbered parameters can't be nested:
4420 *
4421 * %w[test me].each { _1.each_char { p _1 } }
4422 * # numbered parameter is already used in outer block (SyntaxError)
4423 * # %w[test me].each { _1.each_char { p _1 } }
4424 * # ^~
4425 *
4426 */
4427
4428void
4429Init_Proc(void)
4430{
4431#undef rb_intern
4432 /* Proc */
4433 rb_cProc = rb_define_class("Proc", rb_cObject);
4435 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
4436
4437 rb_add_method_optimized(rb_cProc, idCall, 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("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4440 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
4441
4442#if 0 /* for RDoc */
4443 rb_define_method(rb_cProc, "call", proc_call, -1);
4444 rb_define_method(rb_cProc, "[]", proc_call, -1);
4445 rb_define_method(rb_cProc, "===", proc_call, -1);
4446 rb_define_method(rb_cProc, "yield", proc_call, -1);
4447#endif
4448
4449 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
4450 rb_define_method(rb_cProc, "arity", proc_arity, 0);
4451 rb_define_method(rb_cProc, "clone", proc_clone, 0);
4452 rb_define_method(rb_cProc, "dup", proc_dup, 0);
4453 rb_define_method(rb_cProc, "hash", proc_hash, 0);
4454 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
4455 rb_define_alias(rb_cProc, "inspect", "to_s");
4457 rb_define_method(rb_cProc, "binding", proc_binding, 0);
4458 rb_define_method(rb_cProc, "curry", proc_curry, -1);
4459 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
4460 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
4461 rb_define_method(rb_cProc, "==", proc_eq, 1);
4462 rb_define_method(rb_cProc, "eql?", proc_eq, 1);
4463 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
4464 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, -1);
4465 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
4466 // rb_define_method(rb_cProc, "isolate", rb_proc_isolate, 0); is not accepted.
4467
4468 /* Exceptions */
4470 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
4471 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
4472
4473 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
4474 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
4475
4476 /* utility functions */
4477 rb_define_global_function("proc", f_proc, 0);
4478 rb_define_global_function("lambda", f_lambda, 0);
4479
4480 /* Method */
4481 rb_cMethod = rb_define_class("Method", rb_cObject);
4484 rb_define_method(rb_cMethod, "==", method_eq, 1);
4485 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
4486 rb_define_method(rb_cMethod, "hash", method_hash, 0);
4487 rb_define_method(rb_cMethod, "clone", method_clone, 0);
4488 rb_define_method(rb_cMethod, "dup", method_dup, 0);
4489 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
4490 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
4491 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
4492 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
4493 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
4494 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
4495 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
4496 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
4497 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
4498 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
4499 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
4500 rb_define_method(rb_cMethod, "name", method_name, 0);
4501 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
4502 rb_define_method(rb_cMethod, "owner", method_owner, 0);
4503 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
4504 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
4505 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
4506 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
4508 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
4509 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
4510
4511 rb_define_method(rb_cMethod, "namespace", method_namespace, 0);
4512
4513 /* UnboundMethod */
4514 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
4517 rb_define_method(rb_cUnboundMethod, "==", unbound_method_eq, 1);
4518 rb_define_method(rb_cUnboundMethod, "eql?", unbound_method_eq, 1);
4519 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
4520 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
4521 rb_define_method(rb_cUnboundMethod, "dup", method_dup, 0);
4522 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
4523 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
4524 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
4525 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
4526 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
4527 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
4528 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
4529 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
4530 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
4531 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
4532 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
4533
4534 /* Module#*_method */
4535 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
4536 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
4537 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
4538
4539 /* Kernel */
4540 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
4541
4543 "define_method", top_define_method, -1);
4544}
4545
4546/*
4547 * Objects of class Binding encapsulate the execution context at some
4548 * particular place in the code and retain this context for future
4549 * use. The variables, methods, value of <code>self</code>, and
4550 * possibly an iterator block that can be accessed in this context
4551 * are all retained. Binding objects can be created using
4552 * Kernel#binding, and are made available to the callback of
4553 * Kernel#set_trace_func and instances of TracePoint.
4554 *
4555 * These binding objects can be passed as the second argument of the
4556 * Kernel#eval method, establishing an environment for the
4557 * evaluation.
4558 *
4559 * class Demo
4560 * def initialize(n)
4561 * @secret = n
4562 * end
4563 * def get_binding
4564 * binding
4565 * end
4566 * end
4567 *
4568 * k1 = Demo.new(99)
4569 * b1 = k1.get_binding
4570 * k2 = Demo.new(-3)
4571 * b2 = k2.get_binding
4572 *
4573 * eval("@secret", b1) #=> 99
4574 * eval("@secret", b2) #=> -3
4575 * eval("@secret") #=> nil
4576 *
4577 * Binding objects have no class-specific methods.
4578 *
4579 */
4580
4581void
4582Init_Binding(void)
4583{
4584 rb_gc_register_address(&sym_proc_cache);
4585
4586 rb_cBinding = rb_define_class("Binding", rb_cObject);
4589 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
4590 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
4591 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
4592 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
4593 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
4594 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
4595 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
4596 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
4597 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
4598 rb_define_global_function("binding", rb_f_binding, 0);
4599}
#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:1484
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2800
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:2786
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2848
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2668
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:3138
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:943
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2927
#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:682
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:2181
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:243
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:657
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:1807
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:880
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:2604
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:2980
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:2561
VALUE rb_obj_method(VALUE recv, VALUE mid)
Creates a method object.
Definition proc.c:2128
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:2972
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:2591
VALUE rb_obj_is_method(VALUE recv)
Queries if the given object is a method.
Definition proc.c:1675
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:2568
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:4102
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:4068
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3692
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1762
#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:1419
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:3078
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:13000
VALUE rb_iv_get(VALUE obj, const char *name)
Obtains an instance variable.
Definition variable.c:4673
#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:87
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