Ruby: proc.c Source File

Ruby 3.4.7p58 (2025-10-08 revision 7a5688e2a27668e48f8d6ff4af5b2208b98a2f5e)

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