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