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