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