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