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