Ruby 2.7.0p0(2019-12-25revision647ee6f091eafcce70ffb75ddf7e121e192ab217)

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