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