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