Ruby: proc.c Source File

Ruby 3.4.1p0 (2024-12-25 revision 48d4efcb85000e1ebae42004e963b5d0cedddcf2)

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