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