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