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