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