Ruby  2.0.0p195(2013-05-14revision40734)
proc.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  proc.c - Proc, Binding, Env
4 
5  $Author: nagachika $
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 "iseq.h"
16 
17 struct METHOD {
21  ID id;
24 };
25 
30 
31 static VALUE bmcall(VALUE, VALUE);
32 static int method_arity(VALUE);
33 static int method_min_max_arity(VALUE, int *max);
34 static ID attached;
35 
36 /* Proc */
37 
38 #define IS_METHOD_PROC_NODE(node) (nd_type(node) == NODE_IFUNC && (node)->nd_cfnc == bmcall)
39 
40 static void
41 proc_free(void *ptr)
42 {
43  RUBY_FREE_ENTER("proc");
44  if (ptr) {
45  ruby_xfree(ptr);
46  }
47  RUBY_FREE_LEAVE("proc");
48 }
49 
50 static void
51 proc_mark(void *ptr)
52 {
53  rb_proc_t *proc;
54  RUBY_MARK_ENTER("proc");
55  if (ptr) {
56  proc = ptr;
61  if (proc->block.iseq && RUBY_VM_IFUNC_P(proc->block.iseq)) {
63  }
64  }
65  RUBY_MARK_LEAVE("proc");
66 }
67 
68 static size_t
69 proc_memsize(const void *ptr)
70 {
71  return ptr ? sizeof(rb_proc_t) : 0;
72 }
73 
75  "proc",
76  {
77  proc_mark,
78  proc_free,
80  },
81 };
82 
83 VALUE
85 {
86  rb_proc_t *proc;
87  return TypedData_Make_Struct(klass, rb_proc_t, &proc_data_type, proc);
88 }
89 
90 VALUE
92 {
93  if (rb_typeddata_is_kind_of(proc, &proc_data_type)) {
94  return Qtrue;
95  }
96  else {
97  return Qfalse;
98  }
99 }
100 
101 /* :nodoc: */
102 static VALUE
104 {
105  VALUE procval = rb_proc_alloc(rb_cProc);
106  rb_proc_t *src, *dst;
107  GetProcPtr(self, src);
108  GetProcPtr(procval, dst);
109 
110  dst->block = src->block;
111  dst->block.proc = procval;
112  dst->blockprocval = src->blockprocval;
113  dst->envval = src->envval;
114  dst->safe_level = src->safe_level;
115  dst->is_lambda = src->is_lambda;
116 
117  return procval;
118 }
119 
120 /* :nodoc: */
121 static VALUE
123 {
124  VALUE procval = proc_dup(self);
125  CLONESETUP(procval, self);
126  return procval;
127 }
128 
129 /*
130  * call-seq:
131  * prc.lambda? -> true or false
132  *
133  * Returns +true+ for a Proc object for which argument handling is rigid.
134  * Such procs are typically generated by +lambda+.
135  *
136  * A Proc object generated by +proc+ ignores extra arguments.
137  *
138  * proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
139  *
140  * It provides +nil+ for missing arguments.
141  *
142  * proc {|a,b| [a,b] }.call(1) #=> [1,nil]
143  *
144  * It expands a single array argument.
145  *
146  * proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
147  *
148  * A Proc object generated by +lambda+ doesn't have such tricks.
149  *
150  * lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError
151  * lambda {|a,b| [a,b] }.call(1) #=> ArgumentError
152  * lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
153  *
154  * Proc#lambda? is a predicate for the tricks.
155  * It returns +true+ if no tricks apply.
156  *
157  * lambda {}.lambda? #=> true
158  * proc {}.lambda? #=> false
159  *
160  * Proc.new is the same as +proc+.
161  *
162  * Proc.new {}.lambda? #=> false
163  *
164  * +lambda+, +proc+ and Proc.new preserve the tricks of
165  * a Proc object given by <code>&</code> argument.
166  *
167  * lambda(&lambda {}).lambda? #=> true
168  * proc(&lambda {}).lambda? #=> true
169  * Proc.new(&lambda {}).lambda? #=> true
170  *
171  * lambda(&proc {}).lambda? #=> false
172  * proc(&proc {}).lambda? #=> false
173  * Proc.new(&proc {}).lambda? #=> false
174  *
175  * A Proc object generated by <code>&</code> argument has the tricks
176  *
177  * def n(&b) b.lambda? end
178  * n {} #=> false
179  *
180  * The <code>&</code> argument preserves the tricks if a Proc object
181  * is given by <code>&</code> argument.
182  *
183  * n(&lambda {}) #=> true
184  * n(&proc {}) #=> false
185  * n(&Proc.new {}) #=> false
186  *
187  * A Proc object converted from a method has no tricks.
188  *
189  * def m() end
190  * method(:m).to_proc.lambda? #=> true
191  *
192  * n(&method(:m)) #=> true
193  * n(&method(:m).to_proc) #=> true
194  *
195  * +define_method+ is treated the same as method definition.
196  * The defined method has no tricks.
197  *
198  * class C
199  * define_method(:d) {}
200  * end
201  * C.new.d(1,2) #=> ArgumentError
202  * C.new.method(:d).to_proc.lambda? #=> true
203  *
204  * +define_method+ always defines a method without the tricks,
205  * even if a non-lambda Proc object is given.
206  * This is the only exception for which the tricks are not preserved.
207  *
208  * class C
209  * define_method(:e, &proc {})
210  * end
211  * C.new.e(1,2) #=> ArgumentError
212  * C.new.method(:e).to_proc.lambda? #=> true
213  *
214  * This exception insures that methods never have tricks
215  * and makes it easy to have wrappers to define methods that behave as usual.
216  *
217  * class C
218  * def self.def2(name, &body)
219  * define_method(name, &body)
220  * end
221  *
222  * def2(:f) {}
223  * end
224  * C.new.f(1,2) #=> ArgumentError
225  *
226  * The wrapper <i>def2</i> defines a method which has no tricks.
227  *
228  */
229 
230 VALUE
232 {
233  rb_proc_t *proc;
234  GetProcPtr(procval, proc);
235 
236  return proc->is_lambda ? Qtrue : Qfalse;
237 }
238 
239 /* Binding */
240 
241 static void
242 binding_free(void *ptr)
243 {
244  rb_binding_t *bind;
245  RUBY_FREE_ENTER("binding");
246  if (ptr) {
247  bind = ptr;
248  ruby_xfree(bind);
249  }
250  RUBY_FREE_LEAVE("binding");
251 }
252 
253 static void
254 binding_mark(void *ptr)
255 {
256  rb_binding_t *bind;
257  RUBY_MARK_ENTER("binding");
258  if (ptr) {
259  bind = ptr;
260  RUBY_MARK_UNLESS_NULL(bind->env);
262  }
263  RUBY_MARK_LEAVE("binding");
264 }
265 
266 static size_t
267 binding_memsize(const void *ptr)
268 {
269  return ptr ? sizeof(rb_binding_t) : 0;
270 }
271 
273  "binding",
274  {
275  binding_mark,
276  binding_free,
278  },
279 };
280 
281 static VALUE
283 {
284  VALUE obj;
285  rb_binding_t *bind;
286  obj = TypedData_Make_Struct(klass, rb_binding_t, &binding_data_type, bind);
287  return obj;
288 }
289 
290 /* :nodoc: */
291 static VALUE
293 {
294  VALUE bindval = binding_alloc(rb_cBinding);
295  rb_binding_t *src, *dst;
296  GetBindingPtr(self, src);
297  GetBindingPtr(bindval, dst);
298  dst->env = src->env;
299  dst->path = src->path;
300  dst->first_lineno = src->first_lineno;
301  return bindval;
302 }
303 
304 /* :nodoc: */
305 static VALUE
307 {
308  VALUE bindval = binding_dup(self);
309  CLONESETUP(bindval, self);
310  return bindval;
311 }
312 
313 VALUE
315 {
317  rb_control_frame_t *ruby_level_cfp = rb_vm_get_ruby_level_next_cfp(th, src_cfp);
318  VALUE bindval, envval;
319  rb_binding_t *bind;
320 
321  if (cfp == 0 || ruby_level_cfp == 0) {
322  rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber.");
323  }
324 
325  while (1) {
326  envval = rb_vm_make_env_object(th, cfp);
327  if (cfp == ruby_level_cfp) {
328  break;
329  }
331  }
332 
333  bindval = binding_alloc(rb_cBinding);
334  GetBindingPtr(bindval, bind);
335  bind->env = envval;
336  bind->path = ruby_level_cfp->iseq->location.path;
337  bind->first_lineno = rb_vm_get_sourceline(ruby_level_cfp);
338 
339  return bindval;
340 }
341 
342 VALUE
344 {
345  rb_thread_t *th = GET_THREAD();
346  return rb_binding_new_with_cfp(th, th->cfp);
347 }
348 
349 /*
350  * call-seq:
351  * binding -> a_binding
352  *
353  * Returns a +Binding+ object, describing the variable and
354  * method bindings at the point of call. This object can be used when
355  * calling +eval+ to execute the evaluated command in this
356  * environment. See also the description of class +Binding+.
357  *
358  * def get_binding(param)
359  * return binding
360  * end
361  * b = get_binding("hello")
362  * eval("param", b) #=> "hello"
363  */
364 
365 static VALUE
367 {
368  return rb_binding_new();
369 }
370 
371 /*
372  * call-seq:
373  * binding.eval(string [, filename [,lineno]]) -> obj
374  *
375  * Evaluates the Ruby expression(s) in <em>string</em>, in the
376  * <em>binding</em>'s context. If the optional <em>filename</em> and
377  * <em>lineno</em> parameters are present, they will be used when
378  * reporting syntax errors.
379  *
380  * def get_binding(param)
381  * return binding
382  * end
383  * b = get_binding("hello")
384  * b.eval("param") #=> "hello"
385  */
386 
387 static VALUE
388 bind_eval(int argc, VALUE *argv, VALUE bindval)
389 {
390  VALUE args[4];
391 
392  rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
393  args[1] = bindval;
394  return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
395 }
396 
397 static VALUE
398 proc_new(VALUE klass, int is_lambda)
399 {
400  VALUE procval = Qnil;
401  rb_thread_t *th = GET_THREAD();
402  rb_control_frame_t *cfp = th->cfp;
403  rb_block_t *block;
404 
405  if ((block = rb_vm_control_frame_block_ptr(cfp)) != 0) {
406  /* block found */
407  }
408  else {
410 
411  if ((block = rb_vm_control_frame_block_ptr(cfp)) != 0) {
412  if (is_lambda) {
413  rb_warn("tried to create Proc object without a block");
414  }
415  }
416  else {
418  "tried to create Proc object without a block");
419  }
420  }
421 
422  procval = block->proc;
423 
424  if (procval) {
425  if (RBASIC(procval)->klass == klass) {
426  return procval;
427  }
428  else {
429  VALUE newprocval = proc_dup(procval);
430  RBASIC(newprocval)->klass = klass;
431  return newprocval;
432  }
433  }
434 
435  procval = rb_vm_make_proc(th, block, klass);
436 
437  if (is_lambda) {
438  rb_proc_t *proc;
439  GetProcPtr(procval, proc);
440  proc->is_lambda = TRUE;
441  }
442  return procval;
443 }
444 
445 /*
446  * call-seq:
447  * Proc.new {|...| block } -> a_proc
448  * Proc.new -> a_proc
449  *
450  * Creates a new <code>Proc</code> object, bound to the current
451  * context. <code>Proc::new</code> may be called without a block only
452  * within a method with an attached block, in which case that block is
453  * converted to the <code>Proc</code> object.
454  *
455  * def proc_from
456  * Proc.new
457  * end
458  * proc = proc_from { "hello" }
459  * proc.call #=> "hello"
460  */
461 
462 static VALUE
464 {
465  VALUE block = proc_new(klass, FALSE);
466 
467  rb_obj_call_init(block, argc, argv);
468  return block;
469 }
470 
471 /*
472  * call-seq:
473  * proc { |...| block } -> a_proc
474  *
475  * Equivalent to <code>Proc.new</code>.
476  */
477 
478 VALUE
480 {
481  return proc_new(rb_cProc, FALSE);
482 }
483 
484 VALUE
486 {
487  return proc_new(rb_cProc, TRUE);
488 }
489 
490 VALUE
492 {
493  rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead");
494  return rb_block_lambda();
495 }
496 
497 /*
498  * call-seq:
499  * lambda { |...| block } -> a_proc
500  *
501  * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
502  * check the number of parameters passed when called.
503  */
504 
505 static VALUE
507 {
508  return rb_block_lambda();
509 }
510 
511 /* Document-method: ===
512  *
513  * call-seq:
514  * proc === obj -> result_of_proc
515  *
516  * Invokes the block with +obj+ as the proc's parameter like Proc#call. It
517  * is to allow a proc object to be a target of +when+ clause in a case
518  * statement.
519  */
520 
521 /* CHECKME: are the argument checking semantics correct? */
522 
523 /*
524  * call-seq:
525  * prc.call(params,...) -> obj
526  * prc[params,...] -> obj
527  * prc.(params,...) -> obj
528  *
529  * Invokes the block, setting the block's parameters to the values in
530  * <i>params</i> using something close to method calling semantics.
531  * Generates a warning if multiple values are passed to a proc that
532  * expects just one (previously this silently converted the parameters
533  * to an array). Note that prc.() invokes prc.call() with the parameters
534  * given. It's a syntax sugar to hide "call".
535  *
536  * For procs created using <code>lambda</code> or <code>->()</code> an error
537  * is generated if the wrong number of parameters are passed to a Proc with
538  * multiple parameters. For procs created using <code>Proc.new</code> or
539  * <code>Kernel.proc</code>, extra parameters are silently discarded.
540  *
541  * Returns the value of the last expression evaluated in the block. See
542  * also <code>Proc#yield</code>.
543  *
544  * a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
545  * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
546  * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
547  * a_proc = lambda {|a,b| a}
548  * a_proc.call(1,2,3)
549  *
550  * <em>produces:</em>
551  *
552  * prog.rb:4:in `block in <main>': wrong number of arguments (3 for 2) (ArgumentError)
553  * from prog.rb:5:in `call'
554  * from prog.rb:5:in `<main>'
555  *
556  */
557 
558 static VALUE
559 proc_call(int argc, VALUE *argv, VALUE procval)
560 {
561  VALUE vret;
562  rb_proc_t *proc;
563  rb_block_t *blockptr = 0;
564  rb_iseq_t *iseq;
565  VALUE passed_procval;
566  GetProcPtr(procval, proc);
567 
568  iseq = proc->block.iseq;
569  if (BUILTIN_TYPE(iseq) == T_NODE || iseq->arg_block != -1) {
570  if (rb_block_given_p()) {
571  rb_proc_t *passed_proc;
572  RB_GC_GUARD(passed_procval) = rb_block_proc();
573  GetProcPtr(passed_procval, passed_proc);
574  blockptr = &passed_proc->block;
575  }
576  }
577 
578  vret = rb_vm_invoke_proc(GET_THREAD(), proc, argc, argv, blockptr);
579  RB_GC_GUARD(procval);
580  return vret;
581 }
582 
583 #if SIZEOF_LONG > SIZEOF_INT
584 static inline int
585 check_argc(long argc)
586 {
587  if (argc > INT_MAX || argc < 0) {
588  rb_raise(rb_eArgError, "too many arguments (%lu)",
589  (unsigned long)argc);
590  }
591  return (int)argc;
592 }
593 #else
594 #define check_argc(argc) (argc)
595 #endif
596 
597 VALUE
599 {
600  VALUE vret;
601  rb_proc_t *proc;
602  GetProcPtr(self, proc);
603  vret = rb_vm_invoke_proc(GET_THREAD(), proc,
604  check_argc(RARRAY_LEN(args)), RARRAY_PTR(args), 0);
605  RB_GC_GUARD(self);
606  RB_GC_GUARD(args);
607  return vret;
608 }
609 
610 VALUE
611 rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval)
612 {
613  VALUE vret;
614  rb_proc_t *proc;
615  rb_block_t *block = 0;
616  GetProcPtr(self, proc);
617 
618  if (!NIL_P(pass_procval)) {
619  rb_proc_t *pass_proc;
620  GetProcPtr(pass_procval, pass_proc);
621  block = &pass_proc->block;
622  }
623 
624  vret = rb_vm_invoke_proc(GET_THREAD(), proc, argc, argv, block);
625  RB_GC_GUARD(self);
626  RB_GC_GUARD(pass_procval);
627  return vret;
628 }
629 
630 /*
631  * call-seq:
632  * prc.arity -> fixnum
633  *
634  * Returns the number of arguments that would not be ignored. If the block
635  * is declared to take no arguments, returns 0. If the block is known
636  * to take exactly n arguments, returns n. If the block has optional
637  * arguments, return -n-1, where n is the number of mandatory
638  * arguments. A <code>proc</code> with no argument declarations
639  * is the same a block declaring <code>||</code> as its arguments.
640  *
641  * proc {}.arity #=> 0
642  * proc {||}.arity #=> 0
643  * proc {|a|}.arity #=> 1
644  * proc {|a,b|}.arity #=> 2
645  * proc {|a,b,c|}.arity #=> 3
646  * proc {|*a|}.arity #=> -1
647  * proc {|a,*b|}.arity #=> -2
648  * proc {|a,*b, c|}.arity #=> -3
649  *
650  * proc { |x = 0| }.arity #=> 0
651  * lambda { |a = 0| }.arity #=> -1
652  * proc { |x=0, y| }.arity #=> 0
653  * lambda { |x=0, y| }.arity #=> -2
654  * proc { |x=0, y=0| }.arity #=> 0
655  * lambda { |x=0, y=0| }.arity #=> -1
656  * proc { |x, y=0| }.arity #=> 1
657  * lambda { |x, y=0| }.arity #=> -2
658  * proc { |(x, y), z=0| }.arity #=> 1
659  * lambda { |(x, y), z=0| }.arity #=> -2
660  */
661 
662 static VALUE
664 {
665  int arity = rb_proc_arity(self);
666  return INT2FIX(arity);
667 }
668 
669 static inline int
671 {
672  *max = iseq->arg_rest == -1 ?
673  iseq->argc + iseq->arg_post_len + iseq->arg_opts - (iseq->arg_opts > 0)
675  return iseq->argc + iseq->arg_post_len;
676 }
677 
678 /*
679  * Returns the number of required parameters and stores the maximum
680  * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
681  * For non-lambda procs, the maximum is the number of non-ignored
682  * parameters even though there is no actual limit to the number of parameters
683  */
684 static int
686 {
687  rb_proc_t *proc;
688  rb_iseq_t *iseq;
689  GetProcPtr(self, proc);
690  iseq = proc->block.iseq;
691  if (iseq) {
692  if (BUILTIN_TYPE(iseq) != T_NODE) {
693  return rb_iseq_min_max_arity(iseq, max);
694  }
695  else {
696  NODE *node = (NODE *)iseq;
697  if (IS_METHOD_PROC_NODE(node)) {
698  /* e.g. method(:foo).to_proc.arity */
699  return method_min_max_arity(node->nd_tval, max);
700  }
701  }
702  }
703  *max = UNLIMITED_ARGUMENTS;
704  return 0;
705 }
706 
707 int
709 {
710  rb_proc_t *proc;
711  int max, min = rb_proc_min_max_arity(self, &max);
712  GetProcPtr(self, proc);
713  return (proc->is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
714 }
715 
716 #define get_proc_iseq rb_proc_get_iseq
717 
718 rb_iseq_t *
719 rb_proc_get_iseq(VALUE self, int *is_proc)
720 {
721  rb_proc_t *proc;
722  rb_iseq_t *iseq;
723 
724  GetProcPtr(self, proc);
725  iseq = proc->block.iseq;
726  if (is_proc) *is_proc = !proc->is_lambda;
727  if (!RUBY_VM_NORMAL_ISEQ_P(iseq)) {
728  NODE *node = (NODE *)iseq;
729  iseq = 0;
730  if (IS_METHOD_PROC_NODE(node)) {
731  /* method(:foo).to_proc */
732  iseq = rb_method_get_iseq(node->nd_tval);
733  if (is_proc) *is_proc = 0;
734  }
735  }
736  return iseq;
737 }
738 
739 static VALUE
741 {
742  VALUE loc[2];
743 
744  if (!iseq) return Qnil;
745  loc[0] = iseq->location.path;
746  if (iseq->line_info_table) {
747  loc[1] = INT2FIX(rb_iseq_first_lineno(iseq));
748  }
749  else {
750  loc[1] = Qnil;
751  }
752  return rb_ary_new4(2, loc);
753 }
754 
755 /*
756  * call-seq:
757  * prc.source_location -> [String, Fixnum]
758  *
759  * Returns the Ruby source filename and line number containing this proc
760  * or +nil+ if this proc was not defined in Ruby (i.e. native)
761  */
762 
763 VALUE
765 {
766  return iseq_location(get_proc_iseq(self, 0));
767 }
768 
769 static VALUE
771 {
772  VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
773  int n = (arity < 0) ? ~arity : arity;
774  ID req, rest;
775  CONST_ID(req, "req");
776  a = rb_ary_new3(1, ID2SYM(req));
777  OBJ_FREEZE(a);
778  for (; n; --n) {
779  rb_ary_push(param, a);
780  }
781  if (arity < 0) {
782  CONST_ID(rest, "rest");
783  rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
784  }
785  return param;
786 }
787 
788 /*
789  * call-seq:
790  * prc.parameters -> array
791  *
792  * Returns the parameter information of this proc.
793  *
794  * prc = lambda{|x, y=42, *other|}
795  * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
796  */
797 
798 static VALUE
800 {
801  int is_proc;
802  rb_iseq_t *iseq = get_proc_iseq(self, &is_proc);
803  if (!iseq) {
804  return unnamed_parameters(rb_proc_arity(self));
805  }
806  return rb_iseq_parameters(iseq, is_proc);
807 }
808 
811 {
812  rb_proc_t *proc;
813  GetProcPtr(prc, proc);
814  hash = rb_hash_uint(hash, (st_index_t)proc->block.iseq);
815  hash = rb_hash_uint(hash, (st_index_t)proc->envval);
816  return rb_hash_uint(hash, (st_index_t)proc->block.ep >> 16);
817 }
818 
819 /*
820  * call-seq:
821  * prc.hash -> integer
822  *
823  * Returns a hash value corresponding to proc body.
824  */
825 
826 static VALUE
828 {
830  hash = rb_hash_start(0);
831  hash = rb_hash_proc(hash, self);
832  hash = rb_hash_end(hash);
833  return LONG2FIX(hash);
834 }
835 
836 /*
837  * call-seq:
838  * prc.to_s -> string
839  *
840  * Returns the unique identifier for this proc, along with
841  * an indication of where the proc was defined.
842  */
843 
844 static VALUE
846 {
847  VALUE str = 0;
848  rb_proc_t *proc;
849  const char *cname = rb_obj_classname(self);
850  rb_iseq_t *iseq;
851  const char *is_lambda;
852 
853  GetProcPtr(self, proc);
854  iseq = proc->block.iseq;
855  is_lambda = proc->is_lambda ? " (lambda)" : "";
856 
857  if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
858  int first_lineno = 0;
859 
860  if (iseq->line_info_table) {
861  first_lineno = rb_iseq_first_lineno(iseq);
862  }
863  str = rb_sprintf("#<%s:%p@%s:%d%s>", cname, (void *)self,
864  RSTRING_PTR(iseq->location.path),
865  first_lineno, is_lambda);
866  }
867  else {
868  str = rb_sprintf("#<%s:%p%s>", cname, (void *)proc->block.iseq,
869  is_lambda);
870  }
871 
872  if (OBJ_TAINTED(self)) {
873  OBJ_TAINT(str);
874  }
875  return str;
876 }
877 
878 /*
879  * call-seq:
880  * prc.to_proc -> prc
881  *
882  * Part of the protocol for converting objects to <code>Proc</code>
883  * objects. Instances of class <code>Proc</code> simply return
884  * themselves.
885  */
886 
887 static VALUE
889 {
890  return self;
891 }
892 
893 static void
894 bm_mark(void *ptr)
895 {
896  struct METHOD *data = ptr;
897  rb_gc_mark(data->defined_class);
898  rb_gc_mark(data->rclass);
899  rb_gc_mark(data->recv);
900  if (data->me) rb_mark_method_entry(data->me);
901 }
902 
903 static void
904 bm_free(void *ptr)
905 {
906  struct METHOD *data = ptr;
907  struct unlinked_method_entry_list_entry *ume = data->ume;
908  data->me->mark = 0;
909  ume->me = data->me;
910  ume->next = GET_VM()->unlinked_method_entry_list;
911  GET_VM()->unlinked_method_entry_list = ume;
912  xfree(ptr);
913 }
914 
915 static size_t
916 bm_memsize(const void *ptr)
917 {
918  return ptr ? sizeof(struct METHOD) : 0;
919 }
920 
922  "method",
923  {
924  bm_mark,
925  bm_free,
926  bm_memsize,
927  },
928 };
929 
930 VALUE
932 {
934  return Qtrue;
935  }
936  else {
937  return Qfalse;
938  }
939 }
940 
941 static VALUE
942 mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
943 {
944  VALUE method;
945  VALUE rclass = klass, defined_class;
946  ID rid = id;
947  struct METHOD *data;
948  rb_method_entry_t *me, meb;
949  rb_method_definition_t *def = 0;
951 
952  again:
953  me = rb_method_entry_without_refinements(klass, id, &defined_class);
954  if (UNDEFINED_METHOD_ENTRY_P(me)) {
955  ID rmiss = rb_intern("respond_to_missing?");
956  VALUE sym = ID2SYM(id);
957 
958  if (obj != Qundef && !rb_method_basic_definition_p(klass, rmiss)) {
959  if (RTEST(rb_funcall(obj, rmiss, 2, sym, scope ? Qfalse : Qtrue))) {
962  def->original_id = id;
963  def->alias_count = 0;
964 
965  meb.flag = 0;
966  meb.mark = 0;
967  meb.called_id = id;
968  meb.klass = klass;
969  meb.def = def;
970  me = &meb;
971  def = 0;
972 
973  goto gen_method;
974  }
975  }
976  rb_print_undef(klass, id, 0);
977  }
978  def = me->def;
979  if (flag == NOEX_UNDEF) {
980  flag = me->flag;
981  if (scope && (flag & NOEX_MASK) != NOEX_PUBLIC) {
982  const char *v = "";
983  switch (flag & NOEX_MASK) {
984  case NOEX_PRIVATE: v = "private"; break;
985  case NOEX_PROTECTED: v = "protected"; break;
986  }
987  rb_name_error(id, "method `%s' for %s `%s' is %s",
988  rb_id2name(id),
989  (RB_TYPE_P(klass, T_MODULE)) ? "module" : "class",
990  rb_class2name(klass),
991  v);
992  }
993  }
994  if (def && def->type == VM_METHOD_TYPE_ZSUPER) {
995  klass = RCLASS_SUPER(defined_class);
996  id = def->original_id;
997  goto again;
998  }
999 
1000  klass = defined_class;
1001 
1002  while (rclass != klass &&
1003  (FL_TEST(rclass, FL_SINGLETON) || RB_TYPE_P(rclass, T_ICLASS))) {
1004  rclass = RCLASS_SUPER(rclass);
1005  }
1006 
1007  if (RB_TYPE_P(klass, T_ICLASS)) {
1008  klass = RBASIC(klass)->klass;
1009  }
1010 
1011  gen_method:
1012  method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
1013 
1014  data->recv = obj;
1015  data->rclass = rclass;
1016  data->defined_class = defined_class;
1017  data->id = rid;
1018  data->me = ALLOC(rb_method_entry_t);
1019  *data->me = *me;
1020  data->me->def->alias_count++;
1021  data->ume = ALLOC(struct unlinked_method_entry_list_entry);
1022 
1023  OBJ_INFECT(method, klass);
1024 
1025  return method;
1026 }
1027 
1028 
1029 /**********************************************************************
1030  *
1031  * Document-class : Method
1032  *
1033  * Method objects are created by <code>Object#method</code>, and are
1034  * associated with a particular object (not just with a class). They
1035  * may be used to invoke the method within the object, and as a block
1036  * associated with an iterator. They may also be unbound from one
1037  * object (creating an <code>UnboundMethod</code>) and bound to
1038  * another.
1039  *
1040  * class Thing
1041  * def square(n)
1042  * n*n
1043  * end
1044  * end
1045  * thing = Thing.new
1046  * meth = thing.method(:square)
1047  *
1048  * meth.call(9) #=> 81
1049  * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
1050  *
1051  */
1052 
1053 /*
1054  * call-seq:
1055  * meth == other_meth -> true or false
1056  *
1057  * Two method objects are equal if they are bound to the same
1058  * object and refer to the same method definition and their owners are the
1059  * same class or module.
1060  */
1061 
1062 static VALUE
1063 method_eq(VALUE method, VALUE other)
1064 {
1065  struct METHOD *m1, *m2;
1066 
1067  if (!rb_obj_is_method(other))
1068  return Qfalse;
1069  if (CLASS_OF(method) != CLASS_OF(other))
1070  return Qfalse;
1071 
1073  m1 = (struct METHOD *)DATA_PTR(method);
1074  m2 = (struct METHOD *)DATA_PTR(other);
1075 
1076  if (!rb_method_entry_eq(m1->me, m2->me) ||
1077  m1->rclass != m2->rclass ||
1078  m1->recv != m2->recv) {
1079  return Qfalse;
1080  }
1081 
1082  return Qtrue;
1083 }
1084 
1085 /*
1086  * call-seq:
1087  * meth.hash -> integer
1088  *
1089  * Returns a hash value corresponding to the method object.
1090  */
1091 
1092 static VALUE
1094 {
1095  struct METHOD *m;
1096  st_index_t hash;
1097 
1098  TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
1099  hash = rb_hash_start((st_index_t)m->rclass);
1100  hash = rb_hash_uint(hash, (st_index_t)m->recv);
1101  hash = rb_hash_method_entry(hash, m->me);
1102  hash = rb_hash_end(hash);
1103 
1104  return INT2FIX(hash);
1105 }
1106 
1107 /*
1108  * call-seq:
1109  * meth.unbind -> unbound_method
1110  *
1111  * Dissociates <i>meth</i> from its current receiver. The resulting
1112  * <code>UnboundMethod</code> can subsequently be bound to a new object
1113  * of the same class (see <code>UnboundMethod</code>).
1114  */
1115 
1116 static VALUE
1118 {
1119  VALUE method;
1120  struct METHOD *orig, *data;
1121 
1122  TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
1124  &method_data_type, data);
1125  data->recv = Qundef;
1126  data->id = orig->id;
1127  data->me = ALLOC(rb_method_entry_t);
1128  *data->me = *orig->me;
1129  if (orig->me->def) orig->me->def->alias_count++;
1130  data->rclass = orig->rclass;
1131  data->defined_class = orig->defined_class;
1132  data->ume = ALLOC(struct unlinked_method_entry_list_entry);
1133  OBJ_INFECT(method, obj);
1134 
1135  return method;
1136 }
1137 
1138 /*
1139  * call-seq:
1140  * meth.receiver -> object
1141  *
1142  * Returns the bound receiver of the method object.
1143  */
1144 
1145 static VALUE
1147 {
1148  struct METHOD *data;
1149 
1150  TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1151  return data->recv;
1152 }
1153 
1154 /*
1155  * call-seq:
1156  * meth.name -> symbol
1157  *
1158  * Returns the name of the method.
1159  */
1160 
1161 static VALUE
1163 {
1164  struct METHOD *data;
1165 
1166  TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1167  return ID2SYM(data->id);
1168 }
1169 
1170 /*
1171  * call-seq:
1172  * meth.owner -> class_or_module
1173  *
1174  * Returns the class or module that defines the method.
1175  */
1176 
1177 static VALUE
1179 {
1180  struct METHOD *data;
1181 
1182  TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
1183  return data->me->klass;
1184 }
1185 
1186 void
1188 {
1189  const char *s0 = " class";
1190  VALUE c = klass;
1191 
1192  if (FL_TEST(c, FL_SINGLETON)) {
1193  VALUE obj = rb_ivar_get(klass, attached);
1194 
1195  switch (TYPE(obj)) {
1196  case T_MODULE:
1197  case T_CLASS:
1198  c = obj;
1199  s0 = "";
1200  }
1201  }
1202  else if (RB_TYPE_P(c, T_MODULE)) {
1203  s0 = " module";
1204  }
1205  rb_name_error_str(str, "undefined method `%"PRIsVALUE"' for%s `%"PRIsVALUE"'",
1206  QUOTE(str), s0, rb_class_name(c));
1207 }
1208 
1209 /*
1210  * call-seq:
1211  * obj.method(sym) -> method
1212  *
1213  * Looks up the named method as a receiver in <i>obj</i>, returning a
1214  * <code>Method</code> object (or raising <code>NameError</code>). The
1215  * <code>Method</code> object acts as a closure in <i>obj</i>'s object
1216  * instance, so instance variables and the value of <code>self</code>
1217  * remain available.
1218  *
1219  * class Demo
1220  * def initialize(n)
1221  * @iv = n
1222  * end
1223  * def hello()
1224  * "Hello, @iv = #{@iv}"
1225  * end
1226  * end
1227  *
1228  * k = Demo.new(99)
1229  * m = k.method(:hello)
1230  * m.call #=> "Hello, @iv = 99"
1231  *
1232  * l = Demo.new('Fred')
1233  * m = l.method("hello")
1234  * m.call #=> "Hello, @iv = Fred"
1235  */
1236 
1237 VALUE
1239 {
1240  ID id = rb_check_id(&vid);
1241  if (!id) {
1242  rb_method_name_error(CLASS_OF(obj), vid);
1243  }
1244  return mnew(CLASS_OF(obj), obj, id, rb_cMethod, FALSE);
1245 }
1246 
1247 /*
1248  * call-seq:
1249  * obj.public_method(sym) -> method
1250  *
1251  * Similar to _method_, searches public method only.
1252  */
1253 
1254 VALUE
1256 {
1257  ID id = rb_check_id(&vid);
1258  if (!id) {
1259  rb_method_name_error(CLASS_OF(obj), vid);
1260  }
1261  return mnew(CLASS_OF(obj), obj, id, rb_cMethod, TRUE);
1262 }
1263 
1264 /*
1265  * call-seq:
1266  * mod.instance_method(symbol) -> unbound_method
1267  *
1268  * Returns an +UnboundMethod+ representing the given
1269  * instance method in _mod_.
1270  *
1271  * class Interpreter
1272  * def do_a() print "there, "; end
1273  * def do_d() print "Hello "; end
1274  * def do_e() print "!\n"; end
1275  * def do_v() print "Dave"; end
1276  * Dispatcher = {
1277  * "a" => instance_method(:do_a),
1278  * "d" => instance_method(:do_d),
1279  * "e" => instance_method(:do_e),
1280  * "v" => instance_method(:do_v)
1281  * }
1282  * def interpret(string)
1283  * string.each_char {|b| Dispatcher[b].bind(self).call }
1284  * end
1285  * end
1286  *
1287  * interpreter = Interpreter.new
1288  * interpreter.interpret('dave')
1289  *
1290  * <em>produces:</em>
1291  *
1292  * Hello there, Dave!
1293  */
1294 
1295 static VALUE
1297 {
1298  ID id = rb_check_id(&vid);
1299  if (!id) {
1300  rb_method_name_error(mod, vid);
1301  }
1302  return mnew(mod, Qundef, id, rb_cUnboundMethod, FALSE);
1303 }
1304 
1305 /*
1306  * call-seq:
1307  * mod.public_instance_method(symbol) -> unbound_method
1308  *
1309  * Similar to _instance_method_, searches public method only.
1310  */
1311 
1312 static VALUE
1314 {
1315  ID id = rb_check_id(&vid);
1316  if (!id) {
1317  rb_method_name_error(mod, vid);
1318  }
1319  return mnew(mod, Qundef, id, rb_cUnboundMethod, TRUE);
1320 }
1321 
1322 /*
1323  * call-seq:
1324  * define_method(symbol, method) -> new_method
1325  * define_method(symbol) { block } -> proc
1326  *
1327  * Defines an instance method in the receiver. The _method_
1328  * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
1329  * If a block is specified, it is used as the method body. This block
1330  * is evaluated using <code>instance_eval</code>, a point that is
1331  * tricky to demonstrate because <code>define_method</code> is private.
1332  * (This is why we resort to the +send+ hack in this example.)
1333  *
1334  * class A
1335  * def fred
1336  * puts "In Fred"
1337  * end
1338  * def create_method(name, &block)
1339  * self.class.send(:define_method, name, &block)
1340  * end
1341  * define_method(:wilma) { puts "Charge it!" }
1342  * end
1343  * class B < A
1344  * define_method(:barney, instance_method(:fred))
1345  * end
1346  * a = B.new
1347  * a.barney
1348  * a.wilma
1349  * a.create_method(:betty) { p self }
1350  * a.betty
1351  *
1352  * <em>produces:</em>
1353  *
1354  * In Fred
1355  * Charge it!
1356  * #<B:0x401b39e8>
1357  */
1358 
1359 static VALUE
1361 {
1362  ID id;
1363  VALUE body;
1364  int noex = NOEX_PUBLIC;
1365 
1366  if (argc == 1) {
1367  id = rb_to_id(argv[0]);
1368  body = rb_block_lambda();
1369  }
1370  else {
1371  rb_check_arity(argc, 1, 2);
1372  id = rb_to_id(argv[0]);
1373  body = argv[1];
1374  if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) {
1376  "wrong argument type %s (expected Proc/Method)",
1377  rb_obj_classname(body));
1378  }
1379  }
1380 
1381  if (rb_obj_is_method(body)) {
1382  struct METHOD *method = (struct METHOD *)DATA_PTR(body);
1383  VALUE rclass = method->rclass;
1384  if (rclass != mod && !RB_TYPE_P(rclass, T_MODULE) &&
1385  !RTEST(rb_class_inherited_p(mod, rclass))) {
1386  if (FL_TEST(rclass, FL_SINGLETON)) {
1388  "can't bind singleton method to a different class");
1389  }
1390  else {
1392  "bind argument must be a subclass of %s",
1393  rb_class2name(rclass));
1394  }
1395  }
1396  rb_method_entry_set(mod, id, method->me, noex);
1397  }
1398  else if (rb_obj_is_proc(body)) {
1399  rb_proc_t *proc;
1400  body = proc_dup(body);
1401  GetProcPtr(body, proc);
1402  if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) {
1403  proc->block.iseq->defined_method_id = id;
1404  proc->block.iseq->klass = mod;
1405  proc->is_lambda = TRUE;
1406  proc->is_from_method = TRUE;
1407  proc->block.klass = mod;
1408  }
1409  rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)body, noex);
1410  }
1411  else {
1412  /* type error */
1413  rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
1414  }
1415 
1416  return body;
1417 }
1418 
1419 /*
1420  * call-seq:
1421  * define_singleton_method(symbol, method) -> new_method
1422  * define_singleton_method(symbol) { block } -> proc
1423  *
1424  * Defines a singleton method in the receiver. The _method_
1425  * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
1426  * If a block is specified, it is used as the method body.
1427  *
1428  * class A
1429  * class << self
1430  * def class_name
1431  * to_s
1432  * end
1433  * end
1434  * end
1435  * A.define_singleton_method(:who_am_i) do
1436  * "I am: #{class_name}"
1437  * end
1438  * A.who_am_i # ==> "I am: A"
1439  *
1440  * guy = "Bob"
1441  * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
1442  * guy.hello #=> "Bob: Hello there!"
1443  */
1444 
1445 static VALUE
1447 {
1448  VALUE klass = rb_singleton_class(obj);
1449 
1450  return rb_mod_define_method(argc, argv, klass);
1451 }
1452 
1453 /*
1454  * define_method(symbol, method) -> new_method
1455  * define_method(symbol) { block } -> proc
1456  *
1457  * Defines a global function by _method_ or the block.
1458  */
1459 
1460 static VALUE
1462 {
1463  rb_thread_t *th = GET_THREAD();
1464  VALUE klass;
1465 
1466  rb_secure(4);
1467  klass = th->top_wrapper;
1468  if (klass) {
1469  rb_warning("main.define_method in the wrapped load is effective only in wrapper module");
1470  }
1471  else {
1472  klass = rb_cObject;
1473  }
1474  return rb_mod_define_method(argc, argv, klass);
1475 }
1476 
1477 /*
1478  * call-seq:
1479  * method.clone -> new_method
1480  *
1481  * Returns a clone of this method.
1482  *
1483  * class A
1484  * def foo
1485  * return "bar"
1486  * end
1487  * end
1488  *
1489  * m = A.new.method(:foo)
1490  * m.call # => "bar"
1491  * n = m.clone.call # => "bar"
1492  */
1493 
1494 static VALUE
1496 {
1497  VALUE clone;
1498  struct METHOD *orig, *data;
1499 
1500  TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
1501  clone = TypedData_Make_Struct(CLASS_OF(self), struct METHOD, &method_data_type, data);
1502  CLONESETUP(clone, self);
1503  *data = *orig;
1504  data->me = ALLOC(rb_method_entry_t);
1505  *data->me = *orig->me;
1506  if (data->me->def) data->me->def->alias_count++;
1507  data->ume = ALLOC(struct unlinked_method_entry_list_entry);
1508 
1509  return clone;
1510 }
1511 
1512 /*
1513  * call-seq:
1514  * meth.call(args, ...) -> obj
1515  * meth[args, ...] -> obj
1516  *
1517  * Invokes the <i>meth</i> with the specified arguments, returning the
1518  * method's return value.
1519  *
1520  * m = 12.method("+")
1521  * m.call(3) #=> 15
1522  * m.call(20) #=> 32
1523  */
1524 
1525 VALUE
1526 rb_method_call(int argc, VALUE *argv, VALUE method)
1527 {
1528  VALUE result = Qnil; /* OK */
1529  struct METHOD *data;
1530  int state;
1531  volatile int safe = -1;
1532 
1533  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1534  if (data->recv == Qundef) {
1535  rb_raise(rb_eTypeError, "can't call unbound method; bind first");
1536  }
1537  PUSH_TAG();
1538  if (OBJ_TAINTED(method)) {
1539  const int safe_level_to_run = 4 /*SAFE_LEVEL_MAX*/;
1540  safe = rb_safe_level();
1541  if (rb_safe_level() < safe_level_to_run) {
1542  rb_set_safe_level_force(safe_level_to_run);
1543  }
1544  }
1545  if ((state = EXEC_TAG()) == 0) {
1546  rb_thread_t *th = GET_THREAD();
1547 
1549  result = rb_vm_call(th, data->recv, data->id, argc, argv, data->me, data->defined_class);
1550  }
1551  POP_TAG();
1552  if (safe >= 0)
1554  if (state)
1555  JUMP_TAG(state);
1556  return result;
1557 }
1558 
1559 /**********************************************************************
1560  *
1561  * Document-class: UnboundMethod
1562  *
1563  * Ruby supports two forms of objectified methods. Class
1564  * <code>Method</code> is used to represent methods that are associated
1565  * with a particular object: these method objects are bound to that
1566  * object. Bound method objects for an object can be created using
1567  * <code>Object#method</code>.
1568  *
1569  * Ruby also supports unbound methods; methods objects that are not
1570  * associated with a particular object. These can be created either by
1571  * calling <code>Module#instance_method</code> or by calling
1572  * <code>unbind</code> on a bound method object. The result of both of
1573  * these is an <code>UnboundMethod</code> object.
1574  *
1575  * Unbound methods can only be called after they are bound to an
1576  * object. That object must be be a kind_of? the method's original
1577  * class.
1578  *
1579  * class Square
1580  * def area
1581  * @side * @side
1582  * end
1583  * def initialize(side)
1584  * @side = side
1585  * end
1586  * end
1587  *
1588  * area_un = Square.instance_method(:area)
1589  *
1590  * s = Square.new(12)
1591  * area = area_un.bind(s)
1592  * area.call #=> 144
1593  *
1594  * Unbound methods are a reference to the method at the time it was
1595  * objectified: subsequent changes to the underlying class will not
1596  * affect the unbound method.
1597  *
1598  * class Test
1599  * def test
1600  * :original
1601  * end
1602  * end
1603  * um = Test.instance_method(:test)
1604  * class Test
1605  * def test
1606  * :modified
1607  * end
1608  * end
1609  * t = Test.new
1610  * t.test #=> :modified
1611  * um.bind(t).call #=> :original
1612  *
1613  */
1614 
1615 /*
1616  * call-seq:
1617  * umeth.bind(obj) -> method
1618  *
1619  * Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
1620  * from which <i>umeth</i> was obtained,
1621  * <code>obj.kind_of?(Klass)</code> must be true.
1622  *
1623  * class A
1624  * def test
1625  * puts "In test, class = #{self.class}"
1626  * end
1627  * end
1628  * class B < A
1629  * end
1630  * class C < B
1631  * end
1632  *
1633  *
1634  * um = B.instance_method(:test)
1635  * bm = um.bind(C.new)
1636  * bm.call
1637  * bm = um.bind(B.new)
1638  * bm.call
1639  * bm = um.bind(A.new)
1640  * bm.call
1641  *
1642  * <em>produces:</em>
1643  *
1644  * In test, class = C
1645  * In test, class = B
1646  * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
1647  * from prog.rb:16
1648  */
1649 
1650 static VALUE
1652 {
1653  struct METHOD *data, *bound;
1654 
1655  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1656 
1657  if (!RB_TYPE_P(data->rclass, T_MODULE) &&
1658  data->rclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, data->rclass)) {
1659  if (FL_TEST(data->rclass, FL_SINGLETON)) {
1661  "singleton method called for a different object");
1662  }
1663  else {
1664  rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
1665  rb_class2name(data->rclass));
1666  }
1667  }
1668 
1669  method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
1670  *bound = *data;
1671  bound->me = ALLOC(rb_method_entry_t);
1672  *bound->me = *data->me;
1673  if (bound->me->def) bound->me->def->alias_count++;
1674  bound->recv = recv;
1675  bound->rclass = CLASS_OF(recv);
1676  data->ume = ALLOC(struct unlinked_method_entry_list_entry);
1677 
1678  return method;
1679 }
1680 
1681 /*
1682  * Returns the number of required parameters and stores the maximum
1683  * number of parameters in max, or UNLIMITED_ARGUMENTS
1684  * if there is no maximum.
1685  */
1686 static int
1688 {
1689  const rb_method_definition_t *def = me->def;
1690  if (!def) return *max = 0;
1691  switch (def->type) {
1692  case VM_METHOD_TYPE_CFUNC:
1693  if (def->body.cfunc.argc < 0) {
1694  *max = UNLIMITED_ARGUMENTS;
1695  return 0;
1696  }
1697  return *max = check_argc(def->body.cfunc.argc);
1698  case VM_METHOD_TYPE_ZSUPER:
1699  *max = UNLIMITED_ARGUMENTS;
1700  return 0;
1702  return *max = 1;
1703  case VM_METHOD_TYPE_IVAR:
1704  return *max = 0;
1706  return rb_proc_min_max_arity(def->body.proc, max);
1707  case VM_METHOD_TYPE_ISEQ: {
1708  rb_iseq_t *iseq = def->body.iseq;
1709  return rb_iseq_min_max_arity(iseq, max);
1710  }
1711  case VM_METHOD_TYPE_UNDEF:
1713  return *max = 0;
1715  *max = UNLIMITED_ARGUMENTS;
1716  return 0;
1717  case VM_METHOD_TYPE_OPTIMIZED: {
1718  switch (def->body.optimize_type) {
1719  case OPTIMIZED_METHOD_TYPE_SEND:
1720  *max = UNLIMITED_ARGUMENTS;
1721  return 0;
1722  default:
1723  break;
1724  }
1725  }
1727  *max = UNLIMITED_ARGUMENTS;
1728  return 0;
1729  }
1730  rb_bug("rb_method_entry_min_max_arity: invalid method entry type (%d)", def->type);
1731  UNREACHABLE;
1732 }
1733 
1734 int
1736 {
1737  int max, min = rb_method_entry_min_max_arity(me, &max);
1738  return min == max ? min : -min-1;
1739 }
1740 
1741 /*
1742  * call-seq:
1743  * meth.arity -> fixnum
1744  *
1745  * Returns an indication of the number of arguments accepted by a
1746  * method. Returns a nonnegative integer for methods that take a fixed
1747  * number of arguments. For Ruby methods that take a variable number of
1748  * arguments, returns -n-1, where n is the number of required
1749  * arguments. For methods written in C, returns -1 if the call takes a
1750  * variable number of arguments.
1751  *
1752  * class C
1753  * def one; end
1754  * def two(a); end
1755  * def three(*a); end
1756  * def four(a, b); end
1757  * def five(a, b, *c); end
1758  * def six(a, b, *c, &d); end
1759  * end
1760  * c = C.new
1761  * c.method(:one).arity #=> 0
1762  * c.method(:two).arity #=> 1
1763  * c.method(:three).arity #=> -1
1764  * c.method(:four).arity #=> 2
1765  * c.method(:five).arity #=> -3
1766  * c.method(:six).arity #=> -3
1767  *
1768  * "cat".method(:size).arity #=> 0
1769  * "cat".method(:replace).arity #=> 1
1770  * "cat".method(:squeeze).arity #=> -1
1771  * "cat".method(:count).arity #=> -1
1772  */
1773 
1774 static VALUE
1776 {
1777  int n = method_arity(method);
1778  return INT2FIX(n);
1779 }
1780 
1781 static int
1783 {
1784  struct METHOD *data;
1785 
1786  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1787  return rb_method_entry_arity(data->me);
1788 }
1789 
1790 static rb_method_entry_t *
1792 {
1793  VALUE rclass;
1795  while ((me = rb_method_entry(mod, id, &rclass)) != 0) {
1796  rb_method_definition_t *def = me->def;
1797  if (!def) break;
1798  if (def->type != VM_METHOD_TYPE_ZSUPER) break;
1799  mod = RCLASS_SUPER(rclass);
1800  id = def->original_id;
1801  }
1802  return me;
1803 }
1804 
1805 static int
1807 {
1808  struct METHOD *data;
1809 
1810  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1811  return rb_method_entry_min_max_arity(data->me, max);
1812 }
1813 
1814 int
1816 {
1818  if (!me) return 0; /* should raise? */
1819  return rb_method_entry_arity(me);
1820 }
1821 
1822 int
1824 {
1825  return rb_mod_method_arity(CLASS_OF(obj), id);
1826 }
1827 
1828 static inline rb_method_definition_t *
1830 {
1831  struct METHOD *data;
1832 
1833  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1834  return data->me->def;
1835 }
1836 
1837 static rb_iseq_t *
1839 {
1840  switch (def->type) {
1842  return get_proc_iseq(def->body.proc, 0);
1843  case VM_METHOD_TYPE_ISEQ:
1844  return def->body.iseq;
1845  default:
1846  return 0;
1847  }
1848 }
1849 
1850 rb_iseq_t *
1852 {
1853  return method_get_iseq(method_get_def(method));
1854 }
1855 
1856 static VALUE
1858 {
1859  if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
1860  if (!def->body.attr.location)
1861  return Qnil;
1862  return rb_ary_dup(def->body.attr.location);
1863  }
1864  return iseq_location(method_get_iseq(def));
1865 }
1866 
1867 VALUE
1869 {
1870  if (!me || !me->def) return Qnil;
1871  return method_def_location(me->def);
1872 }
1873 
1874 VALUE
1876 {
1878  return rb_method_entry_location(me);
1879 }
1880 
1881 VALUE
1883 {
1884  return rb_mod_method_location(CLASS_OF(obj), id);
1885 }
1886 
1887 /*
1888  * call-seq:
1889  * meth.source_location -> [String, Fixnum]
1890  *
1891  * Returns the Ruby source filename and line number containing this method
1892  * or nil if this method was not defined in Ruby (i.e. native)
1893  */
1894 
1895 VALUE
1897 {
1898  rb_method_definition_t *def = method_get_def(method);
1899  return method_def_location(def);
1900 }
1901 
1902 /*
1903  * call-seq:
1904  * meth.parameters -> array
1905  *
1906  * Returns the parameter information of this method.
1907  */
1908 
1909 static VALUE
1911 {
1912  rb_iseq_t *iseq = rb_method_get_iseq(method);
1913  if (!iseq) {
1914  return unnamed_parameters(method_arity(method));
1915  }
1916  return rb_iseq_parameters(iseq, 0);
1917 }
1918 
1919 /*
1920  * call-seq:
1921  * meth.to_s -> string
1922  * meth.inspect -> string
1923  *
1924  * Returns the name of the underlying method.
1925  *
1926  * "cat".method(:count).inspect #=> "#<Method: String#count>"
1927  */
1928 
1929 static VALUE
1931 {
1932  struct METHOD *data;
1933  VALUE str;
1934  const char *s;
1935  const char *sharp = "#";
1936 
1937  TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
1938  str = rb_str_buf_new2("#<");
1939  s = rb_obj_classname(method);
1940  rb_str_buf_cat2(str, s);
1941  rb_str_buf_cat2(str, ": ");
1942 
1943  if (FL_TEST(data->me->klass, FL_SINGLETON)) {
1944  VALUE v = rb_ivar_get(data->me->klass, attached);
1945 
1946  if (data->recv == Qundef) {
1947  rb_str_buf_append(str, rb_inspect(data->me->klass));
1948  }
1949  else if (data->recv == v) {
1950  rb_str_buf_append(str, rb_inspect(v));
1951  sharp = ".";
1952  }
1953  else {
1954  rb_str_buf_append(str, rb_inspect(data->recv));
1955  rb_str_buf_cat2(str, "(");
1956  rb_str_buf_append(str, rb_inspect(v));
1957  rb_str_buf_cat2(str, ")");
1958  sharp = ".";
1959  }
1960  }
1961  else {
1962  rb_str_buf_cat2(str, rb_class2name(data->rclass));
1963  if (data->rclass != data->me->klass) {
1964  rb_str_buf_cat2(str, "(");
1965  rb_str_buf_cat2(str, rb_class2name(data->me->klass));
1966  rb_str_buf_cat2(str, ")");
1967  }
1968  }
1969  rb_str_buf_cat2(str, sharp);
1970  rb_str_append(str, rb_id2str(data->me->def->original_id));
1971  if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
1972  rb_str_buf_cat2(str, " (not-implemented)");
1973  }
1974  rb_str_buf_cat2(str, ">");
1975 
1976  return str;
1977 }
1978 
1979 static VALUE
1980 mproc(VALUE method)
1981 {
1982  return rb_funcall(Qnil, rb_intern("proc"), 0);
1983 }
1984 
1985 static VALUE
1987 {
1988  return rb_funcall(Qnil, rb_intern("lambda"), 0);
1989 }
1990 
1991 static VALUE
1993 {
1994  volatile VALUE a;
1995  VALUE ret;
1996  int argc;
1997 
1998  if (CLASS_OF(args) != rb_cArray) {
1999  args = rb_ary_new3(1, args);
2000  argc = 1;
2001  }
2002  else {
2003  argc = check_argc(RARRAY_LEN(args));
2004  }
2005  ret = rb_method_call(argc, RARRAY_PTR(args), method);
2006  RB_GC_GUARD(a) = args;
2007  return ret;
2008 }
2009 
2010 VALUE
2012  VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */
2013  VALUE val)
2014 {
2015  VALUE procval = rb_iterate(mproc, 0, func, val);
2016  return procval;
2017 }
2018 
2019 /*
2020  * call-seq:
2021  * meth.to_proc -> prc
2022  *
2023  * Returns a <code>Proc</code> object corresponding to this method.
2024  */
2025 
2026 static VALUE
2028 {
2029  VALUE procval;
2030  rb_proc_t *proc;
2031  /*
2032  * class Method
2033  * def to_proc
2034  * proc{|*args|
2035  * self.call(*args)
2036  * }
2037  * end
2038  * end
2039  */
2040  procval = rb_iterate(mlambda, 0, bmcall, method);
2041  GetProcPtr(procval, proc);
2042  proc->is_from_method = 1;
2043  return procval;
2044 }
2045 
2046 /*
2047  * call_seq:
2048  * local_jump_error.exit_value -> obj
2049  *
2050  * Returns the exit value associated with this +LocalJumpError+.
2051  */
2052 static VALUE
2054 {
2055  return rb_iv_get(exc, "@exit_value");
2056 }
2057 
2058 /*
2059  * call-seq:
2060  * local_jump_error.reason -> symbol
2061  *
2062  * The reason this block was terminated:
2063  * :break, :redo, :retry, :next, :return, or :noreason.
2064  */
2065 
2066 static VALUE
2068 {
2069  return rb_iv_get(exc, "@reason");
2070 }
2071 
2072 /*
2073  * call-seq:
2074  * prc.binding -> binding
2075  *
2076  * Returns the binding associated with <i>prc</i>. Note that
2077  * <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
2078  * <code>Binding</code> object as its second parameter.
2079  *
2080  * def fred(param)
2081  * proc {}
2082  * end
2083  *
2084  * b = fred(99)
2085  * eval("param", b.binding) #=> 99
2086  */
2087 static VALUE
2089 {
2090  rb_proc_t *proc;
2091  VALUE bindval;
2092  rb_binding_t *bind;
2093 
2094  GetProcPtr(self, proc);
2095  if (RB_TYPE_P((VALUE)proc->block.iseq, T_NODE)) {
2096  if (!IS_METHOD_PROC_NODE((NODE *)proc->block.iseq)) {
2097  rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
2098  }
2099  }
2100 
2101  bindval = binding_alloc(rb_cBinding);
2102  GetBindingPtr(bindval, bind);
2103  bind->env = proc->envval;
2104  if (RUBY_VM_NORMAL_ISEQ_P(proc->block.iseq)) {
2105  bind->path = proc->block.iseq->location.path;
2107  }
2108  else {
2109  bind->path = Qnil;
2110  bind->first_lineno = 0;
2111  }
2112  return bindval;
2113 }
2114 
2115 static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc);
2116 
2117 static VALUE
2118 make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
2119 {
2120  VALUE args = rb_ary_new3(3, proc, passed, arity);
2121  rb_proc_t *procp;
2122  int is_lambda;
2123 
2124  GetProcPtr(proc, procp);
2125  is_lambda = procp->is_lambda;
2126  rb_ary_freeze(passed);
2127  rb_ary_freeze(args);
2128  proc = rb_proc_new(curry, args);
2129  GetProcPtr(proc, procp);
2130  procp->is_lambda = is_lambda;
2131  return proc;
2132 }
2133 
2134 static VALUE
2135 curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc)
2136 {
2137  VALUE proc, passed, arity;
2138  proc = RARRAY_PTR(args)[0];
2139  passed = RARRAY_PTR(args)[1];
2140  arity = RARRAY_PTR(args)[2];
2141 
2142  passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
2143  rb_ary_freeze(passed);
2144 
2145  if (RARRAY_LEN(passed) < FIX2INT(arity)) {
2146  if (!NIL_P(passed_proc)) {
2147  rb_warn("given block not used");
2148  }
2149  arity = make_curry_proc(proc, passed, arity);
2150  return arity;
2151  }
2152  else {
2153  return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)),
2154  RARRAY_PTR(passed), passed_proc);
2155  }
2156 }
2157 
2158  /*
2159  * call-seq:
2160  * prc.curry -> a_proc
2161  * prc.curry(arity) -> a_proc
2162  *
2163  * Returns a curried proc. If the optional <i>arity</i> argument is given,
2164  * it determines the number of arguments.
2165  * A curried proc receives some arguments. If a sufficient number of
2166  * arguments are supplied, it passes the supplied arguments to the original
2167  * proc and returns the result. Otherwise, returns another curried proc that
2168  * takes the rest of arguments.
2169  *
2170  * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
2171  * p b.curry[1][2][3] #=> 6
2172  * p b.curry[1, 2][3, 4] #=> 6
2173  * p b.curry(5)[1][2][3][4][5] #=> 6
2174  * p b.curry(5)[1, 2][3, 4][5] #=> 6
2175  * p b.curry(1)[1] #=> 1
2176  *
2177  * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
2178  * p b.curry[1][2][3] #=> 6
2179  * p b.curry[1, 2][3, 4] #=> 10
2180  * p b.curry(5)[1][2][3][4][5] #=> 15
2181  * p b.curry(5)[1, 2][3, 4][5] #=> 15
2182  * p b.curry(1)[1] #=> 1
2183  *
2184  * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
2185  * p b.curry[1][2][3] #=> 6
2186  * p b.curry[1, 2][3, 4] #=> wrong number of arguments (4 for 3)
2187  * p b.curry(5) #=> wrong number of arguments (5 for 3)
2188  * p b.curry(1) #=> wrong number of arguments (1 for 3)
2189  *
2190  * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
2191  * p b.curry[1][2][3] #=> 6
2192  * p b.curry[1, 2][3, 4] #=> 10
2193  * p b.curry(5)[1][2][3][4][5] #=> 15
2194  * p b.curry(5)[1, 2][3, 4][5] #=> 15
2195  * p b.curry(1) #=> wrong number of arguments (1 for 3)
2196  *
2197  * b = proc { :foo }
2198  * p b.curry[] #=> :foo
2199  */
2200 static VALUE
2201 proc_curry(int argc, VALUE *argv, VALUE self)
2202 {
2203  int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
2204  VALUE arity;
2205 
2206  rb_scan_args(argc, argv, "01", &arity);
2207  if (NIL_P(arity)) {
2208  arity = INT2FIX(min_arity);
2209  }
2210  else {
2211  sarity = FIX2INT(arity);
2212  if (rb_proc_lambda_p(self)) {
2213  rb_check_arity(sarity, min_arity, max_arity);
2214  }
2215  }
2216 
2217  return make_curry_proc(self, rb_ary_new(), arity);
2218 }
2219 
2220 /*
2221  * Document-class: LocalJumpError
2222  *
2223  * Raised when Ruby can't yield as requested.
2224  *
2225  * A typical scenario is attempting to yield when no block is given:
2226  *
2227  * def call_block
2228  * yield 42
2229  * end
2230  * call_block
2231  *
2232  * <em>raises the exception:</em>
2233  *
2234  * LocalJumpError: no block given (yield)
2235  *
2236  * A more subtle example:
2237  *
2238  * def get_me_a_return
2239  * Proc.new { return 42 }
2240  * end
2241  * get_me_a_return.call
2242  *
2243  * <em>raises the exception:</em>
2244  *
2245  * LocalJumpError: unexpected return
2246  */
2247 
2248 /*
2249  * Document-class: SystemStackError
2250  *
2251  * Raised in case of a stack overflow.
2252  *
2253  * def me_myself_and_i
2254  * me_myself_and_i
2255  * end
2256  * me_myself_and_i
2257  *
2258  * <em>raises the exception:</em>
2259  *
2260  * SystemStackError: stack level too deep
2261  */
2262 
2263 /*
2264  * <code>Proc</code> objects are blocks of code that have been bound to
2265  * a set of local variables. Once bound, the code may be called in
2266  * different contexts and still access those variables.
2267  *
2268  * def gen_times(factor)
2269  * return Proc.new {|n| n*factor }
2270  * end
2271  *
2272  * times3 = gen_times(3)
2273  * times5 = gen_times(5)
2274  *
2275  * times3.call(12) #=> 36
2276  * times5.call(5) #=> 25
2277  * times3.call(times5.call(4)) #=> 60
2278  *
2279  */
2280 
2281 void
2283 {
2284  /* Proc */
2285  rb_cProc = rb_define_class("Proc", rb_cObject);
2288 
2289 #if 0 /* incomplete. */
2291  (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
2293  (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
2295  (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
2297  (void *)OPTIMIZED_METHOD_TYPE_CALL, 0);
2298 #else
2299  rb_define_method(rb_cProc, "call", proc_call, -1);
2300  rb_define_method(rb_cProc, "[]", proc_call, -1);
2301  rb_define_method(rb_cProc, "===", proc_call, -1);
2302  rb_define_method(rb_cProc, "yield", proc_call, -1);
2303 #endif
2304  rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
2305  rb_define_method(rb_cProc, "arity", proc_arity, 0);
2306  rb_define_method(rb_cProc, "clone", proc_clone, 0);
2307  rb_define_method(rb_cProc, "dup", proc_dup, 0);
2308  rb_define_method(rb_cProc, "hash", proc_hash, 0);
2309  rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
2310  rb_define_alias(rb_cProc, "inspect", "to_s");
2311  rb_define_method(rb_cProc, "lambda?", rb_proc_lambda_p, 0);
2312  rb_define_method(rb_cProc, "binding", proc_binding, 0);
2313  rb_define_method(rb_cProc, "curry", proc_curry, -1);
2314  rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
2315  rb_define_method(rb_cProc, "parameters", rb_proc_parameters, 0);
2316 
2317  /* Exceptions */
2321 
2322  rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
2324  rb_obj_freeze(rb_str_new2("stack level too deep")));
2326 
2327  /* utility functions */
2329  rb_define_global_function("lambda", proc_lambda, 0);
2330 
2331  /* Method */
2332  rb_cMethod = rb_define_class("Method", rb_cObject);
2336  rb_define_method(rb_cMethod, "eql?", method_eq, 1);
2342  rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
2344  rb_define_method(rb_cMethod, "to_proc", method_proc, 0);
2345  rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
2348  rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
2349  rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
2351  rb_define_method(rb_mKernel, "method", rb_obj_method, 1);
2352  rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
2353 
2354  /* UnboundMethod */
2355  rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
2368  rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
2370 
2371  /* Module#*_method */
2372  rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
2373  rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
2375 
2376  /* Kernel */
2377  rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
2378 
2380  "define_method", top_define_method, -1);
2381 }
2382 
2383 /*
2384  * Objects of class <code>Binding</code> encapsulate the execution
2385  * context at some particular place in the code and retain this context
2386  * for future use. The variables, methods, value of <code>self</code>,
2387  * and possibly an iterator block that can be accessed in this context
2388  * are all retained. Binding objects can be created using
2389  * <code>Kernel#binding</code>, and are made available to the callback
2390  * of <code>Kernel#set_trace_func</code>.
2391  *
2392  * These binding objects can be passed as the second argument of the
2393  * <code>Kernel#eval</code> method, establishing an environment for the
2394  * evaluation.
2395  *
2396  * class Demo
2397  * def initialize(n)
2398  * @secret = n
2399  * end
2400  * def get_binding
2401  * return binding()
2402  * end
2403  * end
2404  *
2405  * k1 = Demo.new(99)
2406  * b1 = k1.get_binding
2407  * k2 = Demo.new(-3)
2408  * b2 = k2.get_binding
2409  *
2410  * eval("@secret", b1) #=> 99
2411  * eval("@secret", b2) #=> -3
2412  * eval("@secret") #=> nil
2413  *
2414  * Binding objects have no class-specific methods.
2415  *
2416  */
2417 
2418 void
2420 {
2421  rb_cBinding = rb_define_class("Binding", rb_cObject);
2426  rb_define_method(rb_cBinding, "eval", bind_eval, -1);
2427  rb_define_global_function("binding", rb_f_binding, 0);
2428  attached = rb_intern("__attached__");
2429 }
2430 
2431