Ruby 2.0.0p247(2013-06-27revision41674)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

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