Ruby  2.0.0p481(2014-05-08revision45883)
enumerator.c
Go to the documentation of this file.
00001 /************************************************
00002 
00003   enumerator.c - provides Enumerator class
00004 
00005   $Author: nagachika $
00006 
00007   Copyright (C) 2001-2003 Akinori MUSHA
00008 
00009   $Idaemons: /home/cvs/rb/enumerator/enumerator.c,v 1.1.1.1 2001/07/15 10:12:48 knu Exp $
00010   $RoughId: enumerator.c,v 1.6 2003/07/27 11:03:24 nobu Exp $
00011   $Id: enumerator.c 44150 2013-12-12 16:02:08Z nagachika $
00012 
00013 ************************************************/
00014 
00015 #include "ruby/ruby.h"
00016 #include "node.h"
00017 #include "internal.h"
00018 
00019 /*
00020  * Document-class: Enumerator
00021  *
00022  * A class which allows both internal and external iteration.
00023  *
00024  * An Enumerator can be created by the following methods.
00025  * - Kernel#to_enum
00026  * - Kernel#enum_for
00027  * - Enumerator.new
00028  *
00029  * Most methods have two forms: a block form where the contents
00030  * are evaluated for each item in the enumeration, and a non-block form
00031  * which returns a new Enumerator wrapping the iteration.
00032  *
00033  *   enumerator = %w(one two three).each
00034  *   puts enumerator.class # => Enumerator
00035  *
00036  *   enumerator.each_with_object("foo") do |item, obj|
00037  *     puts "#{obj}: #{item}"
00038  *   end
00039  *
00040  *   # foo: one
00041  *   # foo: two
00042  *   # foo: three
00043  *
00044  *   enum_with_obj = enumerator.each_with_object("foo")
00045  *   puts enum_with_obj.class # => Enumerator
00046  *
00047  *   enum_with_obj.each do |item, obj|
00048  *     puts "#{obj}: #{item}"
00049  *   end
00050  *
00051  *   # foo: one
00052  *   # foo: two
00053  *   # foo: three
00054  *
00055  * This allows you to chain Enumerators together.  For example, you
00056  * can map a list's elements to strings containing the index
00057  * and the element as a string via:
00058  *
00059  *   puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" }
00060  *   # => ["0:foo", "1:bar", "2:baz"]
00061  *
00062  * An Enumerator can also be used as an external iterator.
00063  * For example, Enumerator#next returns the next value of the iterator
00064  * or raises StopIteration if the Enumerator is at the end.
00065  *
00066  *   e = [1,2,3].each   # returns an enumerator object.
00067  *   puts e.next   # => 1
00068  *   puts e.next   # => 2
00069  *   puts e.next   # => 3
00070  *   puts e.next   # raises StopIteration
00071  *
00072  * You can use this to implement an internal iterator as follows:
00073  *
00074  *   def ext_each(e)
00075  *     while true
00076  *       begin
00077  *         vs = e.next_values
00078  *       rescue StopIteration
00079  *         return $!.result
00080  *       end
00081  *       y = yield(*vs)
00082  *       e.feed y
00083  *     end
00084  *   end
00085  *
00086  *   o = Object.new
00087  *
00088  *   def o.each
00089  *     puts yield
00090  *     puts yield(1)
00091  *     puts yield(1, 2)
00092  *     3
00093  *   end
00094  *
00095  *   # use o.each as an internal iterator directly.
00096  *   puts o.each {|*x| puts x; [:b, *x] }
00097  *   # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
00098  *
00099  *   # convert o.each to an external iterator for
00100  *   # implementing an internal iterator.
00101  *   puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] }
00102  *   # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
00103  *
00104  */
00105 VALUE rb_cEnumerator;
00106 VALUE rb_cLazy;
00107 static ID id_rewind, id_each, id_new, id_initialize, id_yield, id_call, id_size, id_to_enum;
00108 static ID id_eqq, id_next, id_result, id_lazy, id_receiver, id_arguments, id_memo, id_method, id_force;
00109 static VALUE sym_each, sym_cycle;
00110 
00111 VALUE rb_eStopIteration;
00112 
00113 struct enumerator {
00114     VALUE obj;
00115     ID    meth;
00116     VALUE args;
00117     VALUE fib;
00118     VALUE dst;
00119     VALUE lookahead;
00120     VALUE feedvalue;
00121     VALUE stop_exc;
00122     VALUE size;
00123     VALUE (*size_fn)(ANYARGS);
00124 };
00125 
00126 static VALUE rb_cGenerator, rb_cYielder;
00127 
00128 struct generator {
00129     VALUE proc;
00130 };
00131 
00132 struct yielder {
00133     VALUE proc;
00134 };
00135 
00136 static VALUE generator_allocate(VALUE klass);
00137 static VALUE generator_init(VALUE obj, VALUE proc);
00138 
00139 /*
00140  * Enumerator
00141  */
00142 static void
00143 enumerator_mark(void *p)
00144 {
00145     struct enumerator *ptr = p;
00146     rb_gc_mark(ptr->obj);
00147     rb_gc_mark(ptr->args);
00148     rb_gc_mark(ptr->fib);
00149     rb_gc_mark(ptr->dst);
00150     rb_gc_mark(ptr->lookahead);
00151     rb_gc_mark(ptr->feedvalue);
00152     rb_gc_mark(ptr->stop_exc);
00153     rb_gc_mark(ptr->size);
00154 }
00155 
00156 #define enumerator_free RUBY_TYPED_DEFAULT_FREE
00157 
00158 static size_t
00159 enumerator_memsize(const void *p)
00160 {
00161     return p ? sizeof(struct enumerator) : 0;
00162 }
00163 
00164 static const rb_data_type_t enumerator_data_type = {
00165     "enumerator",
00166     {
00167         enumerator_mark,
00168         enumerator_free,
00169         enumerator_memsize,
00170     },
00171 };
00172 
00173 static struct enumerator *
00174 enumerator_ptr(VALUE obj)
00175 {
00176     struct enumerator *ptr;
00177 
00178     TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr);
00179     if (!ptr || ptr->obj == Qundef) {
00180         rb_raise(rb_eArgError, "uninitialized enumerator");
00181     }
00182     return ptr;
00183 }
00184 
00185 /*
00186  * call-seq:
00187  *   obj.to_enum(method = :each, *args)                 -> enum
00188  *   obj.enum_for(method = :each, *args)                -> enum
00189  *   obj.to_enum(method = :each, *args) {|*args| block} -> enum
00190  *   obj.enum_for(method = :each, *args){|*args| block} -> enum
00191  *
00192  * Creates a new Enumerator which will enumerate by calling +method+ on
00193  * +obj+, passing +args+ if any.
00194  *
00195  * If a block is given, it will be used to calculate the size of
00196  * the enumerator without the need to iterate it (see Enumerator#size).
00197  *
00198  * === Examples
00199  *
00200  *   str = "xyz"
00201  *
00202  *   enum = str.enum_for(:each_byte)
00203  *   enum.each { |b| puts b }
00204  *   # => 120
00205  *   # => 121
00206  *   # => 122
00207  *
00208  *   # protect an array from being modified by some_method
00209  *   a = [1, 2, 3]
00210  *   some_method(a.to_enum)
00211  *
00212  * It is typical to call to_enum when defining methods for
00213  * a generic Enumerable, in case no block is passed.
00214  *
00215  * Here is such an example, with parameter passing and a sizing block:
00216  *
00217  *   module Enumerable
00218  *     # a generic method to repeat the values of any enumerable
00219  *     def repeat(n)
00220  *       raise ArgumentError, "#{n} is negative!" if n < 0
00221  *       unless block_given?
00222  *         return to_enum(__method__, n) do # __method__ is :repeat here
00223  *           sz = size     # Call size and multiply by n...
00224  *           sz * n if sz  # but return nil if size itself is nil
00225  *         end
00226  *       end
00227  *       each do |*val|
00228  *         n.times { yield *val }
00229  *       end
00230  *     end
00231  *   end
00232  *
00233  *   %i[hello world].repeat(2) { |w| puts w }
00234  *     # => Prints 'hello', 'hello', 'world', 'world'
00235  *   enum = (1..14).repeat(3)
00236  *     # => returns an Enumerator when called without a block
00237  *   enum.first(4) # => [1, 1, 1, 2]
00238  *   enum.size # => 42
00239  */
00240 static VALUE
00241 obj_to_enum(int argc, VALUE *argv, VALUE obj)
00242 {
00243     VALUE enumerator, meth = sym_each;
00244 
00245     if (argc > 0) {
00246         --argc;
00247         meth = *argv++;
00248     }
00249     enumerator = rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
00250     if (rb_block_given_p()) {
00251         enumerator_ptr(enumerator)->size = rb_block_proc();
00252     }
00253     return enumerator;
00254 }
00255 
00256 static VALUE
00257 enumerator_allocate(VALUE klass)
00258 {
00259     struct enumerator *ptr;
00260     VALUE enum_obj;
00261 
00262     enum_obj = TypedData_Make_Struct(klass, struct enumerator, &enumerator_data_type, ptr);
00263     ptr->obj = Qundef;
00264 
00265     return enum_obj;
00266 }
00267 
00268 static VALUE
00269 enumerator_init(VALUE enum_obj, VALUE obj, VALUE meth, int argc, VALUE *argv, VALUE (*size_fn)(ANYARGS), VALUE size)
00270 {
00271     struct enumerator *ptr;
00272 
00273     TypedData_Get_Struct(enum_obj, struct enumerator, &enumerator_data_type, ptr);
00274 
00275     if (!ptr) {
00276         rb_raise(rb_eArgError, "unallocated enumerator");
00277     }
00278 
00279     ptr->obj  = obj;
00280     ptr->meth = rb_to_id(meth);
00281     if (argc) ptr->args = rb_ary_new4(argc, argv);
00282     ptr->fib = 0;
00283     ptr->dst = Qnil;
00284     ptr->lookahead = Qundef;
00285     ptr->feedvalue = Qundef;
00286     ptr->stop_exc = Qfalse;
00287     ptr->size = size;
00288     ptr->size_fn = size_fn;
00289 
00290     return enum_obj;
00291 }
00292 
00293 /*
00294  * call-seq:
00295  *   Enumerator.new(size = nil) { |yielder| ... }
00296  *   Enumerator.new(obj, method = :each, *args)
00297  *
00298  * Creates a new Enumerator object, which can be used as an
00299  * Enumerable.
00300  *
00301  * In the first form, iteration is defined by the given block, in
00302  * which a "yielder" object, given as block parameter, can be used to
00303  * yield a value by calling the +yield+ method (aliased as +<<+):
00304  *
00305  *   fib = Enumerator.new do |y|
00306  *     a = b = 1
00307  *     loop do
00308  *       y << a
00309  *       a, b = b, a + b
00310  *     end
00311  *   end
00312  *
00313  *   p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
00314  *
00315  * The optional parameter can be used to specify how to calculate the size
00316  * in a lazy fashion (see Enumerator#size). It can either be a value or
00317  * a callable object.
00318  *
00319  * In the second, deprecated, form, a generated Enumerator iterates over the
00320  * given object using the given method with the given arguments passed.
00321  *
00322  * Use of this form is discouraged.  Use Kernel#enum_for or Kernel#to_enum
00323  * instead.
00324  *
00325  *   e = Enumerator.new(ObjectSpace, :each_object)
00326  *       #-> ObjectSpace.enum_for(:each_object)
00327  *
00328  *   e.select { |obj| obj.is_a?(Class) }  #=> array of all classes
00329  *
00330  */
00331 static VALUE
00332 enumerator_initialize(int argc, VALUE *argv, VALUE obj)
00333 {
00334     VALUE recv, meth = sym_each;
00335     VALUE size = Qnil;
00336 
00337     if (rb_block_given_p()) {
00338         rb_check_arity(argc, 0, 1);
00339         recv = generator_init(generator_allocate(rb_cGenerator), rb_block_proc());
00340         if (argc) {
00341             if (NIL_P(argv[0]) || rb_obj_is_proc(argv[0]) ||
00342                 (RB_TYPE_P(argv[0], T_FLOAT) && RFLOAT_VALUE(argv[0]) == INFINITY)) {
00343                 size = argv[0];
00344             } else {
00345                 size = rb_to_int(argv[0]);
00346             }
00347             argc = 0;
00348         }
00349     }
00350     else {
00351         rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
00352         rb_warn("Enumerator.new without a block is deprecated; use Object#to_enum");
00353         recv = *argv++;
00354         if (--argc) {
00355             meth = *argv++;
00356             --argc;
00357         }
00358     }
00359 
00360     return enumerator_init(obj, recv, meth, argc, argv, 0, size);
00361 }
00362 
00363 /* :nodoc: */
00364 static VALUE
00365 enumerator_init_copy(VALUE obj, VALUE orig)
00366 {
00367     struct enumerator *ptr0, *ptr1;
00368 
00369     if (!OBJ_INIT_COPY(obj, orig)) return obj;
00370     ptr0 = enumerator_ptr(orig);
00371     if (ptr0->fib) {
00372         /* Fibers cannot be copied */
00373         rb_raise(rb_eTypeError, "can't copy execution context");
00374     }
00375 
00376     TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr1);
00377 
00378     if (!ptr1) {
00379         rb_raise(rb_eArgError, "unallocated enumerator");
00380     }
00381 
00382     ptr1->obj  = ptr0->obj;
00383     ptr1->meth = ptr0->meth;
00384     ptr1->args = ptr0->args;
00385     ptr1->fib  = 0;
00386     ptr1->lookahead  = Qundef;
00387     ptr1->feedvalue  = Qundef;
00388     ptr1->size  = ptr0->size;
00389     ptr1->size_fn  = ptr0->size_fn;
00390 
00391     return obj;
00392 }
00393 
00394 /*
00395  * For backwards compatibility; use rb_enumeratorize_with_size
00396  */
00397 VALUE
00398 rb_enumeratorize(VALUE obj, VALUE meth, int argc, VALUE *argv)
00399 {
00400     return rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
00401 }
00402 
00403 static VALUE
00404 lazy_to_enum_i(VALUE self, VALUE meth, int argc, VALUE *argv, VALUE (*size_fn)(ANYARGS));
00405 
00406 VALUE
00407 rb_enumeratorize_with_size(VALUE obj, VALUE meth, int argc, VALUE *argv, VALUE (*size_fn)(ANYARGS))
00408 {
00409     /* Similar effect as calling obj.to_enum, i.e. dispatching to either
00410        Kernel#to_enum vs Lazy#to_enum */
00411     if (RTEST(rb_obj_is_kind_of(obj, rb_cLazy)))
00412         return lazy_to_enum_i(obj, meth, argc, argv, size_fn);
00413     else
00414         return enumerator_init(enumerator_allocate(rb_cEnumerator),
00415             obj, meth, argc, argv, size_fn, Qnil);
00416 }
00417 
00418 static VALUE
00419 enumerator_block_call(VALUE obj, rb_block_call_func *func, VALUE arg)
00420 {
00421     int argc = 0;
00422     VALUE *argv = 0;
00423     const struct enumerator *e = enumerator_ptr(obj);
00424     ID meth = e->meth;
00425 
00426     if (e->args) {
00427         argc = RARRAY_LENINT(e->args);
00428         argv = RARRAY_PTR(e->args);
00429     }
00430     return rb_block_call(e->obj, meth, argc, argv, func, arg);
00431 }
00432 
00433 /*
00434  * call-seq:
00435  *   enum.each {...}
00436  *
00437  * Iterates over the block according to how this Enumerable was constructed.
00438  * If no block is given, returns self.
00439  *
00440  */
00441 static VALUE
00442 enumerator_each(int argc, VALUE *argv, VALUE obj)
00443 {
00444     if (argc > 0) {
00445         struct enumerator *e = enumerator_ptr(obj = rb_obj_dup(obj));
00446         VALUE args = e->args;
00447         if (args) {
00448             args = rb_ary_dup(args);
00449             rb_ary_cat(args, argv, argc);
00450         }
00451         else {
00452             args = rb_ary_new4(argc, argv);
00453         }
00454         e->args = args;
00455     }
00456     if (!rb_block_given_p()) return obj;
00457     return enumerator_block_call(obj, 0, obj);
00458 }
00459 
00460 static VALUE
00461 enumerator_with_index_i(VALUE val, VALUE m, int argc, VALUE *argv)
00462 {
00463     NODE *memo = (NODE *)m;
00464     VALUE idx = memo->u1.value;
00465     memo->u1.value = rb_int_succ(idx);
00466 
00467     if (argc <= 1)
00468         return rb_yield_values(2, val, idx);
00469 
00470     return rb_yield_values(2, rb_ary_new4(argc, argv), idx);
00471 }
00472 
00473 static VALUE
00474 enumerator_size(VALUE obj);
00475 
00476 /*
00477  * call-seq:
00478  *   e.with_index(offset = 0) {|(*args), idx| ... }
00479  *   e.with_index(offset = 0)
00480  *
00481  * Iterates the given block for each element with an index, which
00482  * starts from +offset+.  If no block is given, returns a new Enumerator
00483  * that includes the index, starting from +offset+
00484  *
00485  * +offset+:: the starting index to use
00486  *
00487  */
00488 static VALUE
00489 enumerator_with_index(int argc, VALUE *argv, VALUE obj)
00490 {
00491     VALUE memo;
00492 
00493     rb_scan_args(argc, argv, "01", &memo);
00494     RETURN_SIZED_ENUMERATOR(obj, argc, argv, enumerator_size);
00495     if (NIL_P(memo))
00496         memo = INT2FIX(0);
00497     else
00498         memo = rb_to_int(memo);
00499     return enumerator_block_call(obj, enumerator_with_index_i, (VALUE)NEW_MEMO(memo, 0, 0));
00500 }
00501 
00502 /*
00503  * call-seq:
00504  *   e.each_with_index {|(*args), idx| ... }
00505  *   e.each_with_index
00506  *
00507  * Same as Enumerator#with_index(0), i.e. there is no starting offset.
00508  *
00509  * If no block is given, a new Enumerator is returned that includes the index.
00510  *
00511  */
00512 static VALUE
00513 enumerator_each_with_index(VALUE obj)
00514 {
00515     return enumerator_with_index(0, NULL, obj);
00516 }
00517 
00518 static VALUE
00519 enumerator_with_object_i(VALUE val, VALUE memo, int argc, VALUE *argv)
00520 {
00521     if (argc <= 1)
00522         return rb_yield_values(2, val, memo);
00523 
00524     return rb_yield_values(2, rb_ary_new4(argc, argv), memo);
00525 }
00526 
00527 /*
00528  * call-seq:
00529  *   e.with_object(obj) {|(*args), obj| ... }
00530  *   e.with_object(obj)
00531  *
00532  * Iterates the given block for each element with an arbitrary object, +obj+,
00533  * and returns +obj+
00534  *
00535  * If no block is given, returns a new Enumerator.
00536  *
00537  * === Example
00538  *
00539  *   to_three = Enumerator.new do |y|
00540  *     3.times do |x|
00541  *       y << x
00542  *     end
00543  *   end
00544  *
00545  *   to_three_with_string = to_three.with_object("foo")
00546  *   to_three_with_string.each do |x,string|
00547  *     puts "#{string}: #{x}"
00548  *   end
00549  *
00550  *   # => foo:0
00551  *   # => foo:1
00552  *   # => foo:2
00553  */
00554 static VALUE
00555 enumerator_with_object(VALUE obj, VALUE memo)
00556 {
00557     RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enumerator_size);
00558     enumerator_block_call(obj, enumerator_with_object_i, memo);
00559 
00560     return memo;
00561 }
00562 
00563 static VALUE
00564 next_ii(VALUE i, VALUE obj, int argc, VALUE *argv)
00565 {
00566     struct enumerator *e = enumerator_ptr(obj);
00567     VALUE feedvalue = Qnil;
00568     VALUE args = rb_ary_new4(argc, argv);
00569     rb_fiber_yield(1, &args);
00570     if (e->feedvalue != Qundef) {
00571         feedvalue = e->feedvalue;
00572         e->feedvalue = Qundef;
00573     }
00574     return feedvalue;
00575 }
00576 
00577 static VALUE
00578 next_i(VALUE curr, VALUE obj)
00579 {
00580     struct enumerator *e = enumerator_ptr(obj);
00581     VALUE nil = Qnil;
00582     VALUE result;
00583 
00584     result = rb_block_call(obj, id_each, 0, 0, next_ii, obj);
00585     e->stop_exc = rb_exc_new2(rb_eStopIteration, "iteration reached an end");
00586     rb_ivar_set(e->stop_exc, id_result, result);
00587     return rb_fiber_yield(1, &nil);
00588 }
00589 
00590 static void
00591 next_init(VALUE obj, struct enumerator *e)
00592 {
00593     VALUE curr = rb_fiber_current();
00594     e->dst = curr;
00595     e->fib = rb_fiber_new(next_i, obj);
00596     e->lookahead = Qundef;
00597 }
00598 
00599 static VALUE
00600 get_next_values(VALUE obj, struct enumerator *e)
00601 {
00602     VALUE curr, vs;
00603 
00604     if (e->stop_exc)
00605         rb_exc_raise(e->stop_exc);
00606 
00607     curr = rb_fiber_current();
00608 
00609     if (!e->fib || !rb_fiber_alive_p(e->fib)) {
00610         next_init(obj, e);
00611     }
00612 
00613     vs = rb_fiber_resume(e->fib, 1, &curr);
00614     if (e->stop_exc) {
00615         e->fib = 0;
00616         e->dst = Qnil;
00617         e->lookahead = Qundef;
00618         e->feedvalue = Qundef;
00619         rb_exc_raise(e->stop_exc);
00620     }
00621     return vs;
00622 }
00623 
00624 /*
00625  * call-seq:
00626  *   e.next_values   -> array
00627  *
00628  * Returns the next object as an array in the enumerator, and move the
00629  * internal position forward.  When the position reached at the end,
00630  * StopIteration is raised.
00631  *
00632  * This method can be used to distinguish <code>yield</code> and <code>yield
00633  * nil</code>.
00634  *
00635  * === Example
00636  *
00637  *   o = Object.new
00638  *   def o.each
00639  *     yield
00640  *     yield 1
00641  *     yield 1, 2
00642  *     yield nil
00643  *     yield [1, 2]
00644  *   end
00645  *   e = o.to_enum
00646  *   p e.next_values
00647  *   p e.next_values
00648  *   p e.next_values
00649  *   p e.next_values
00650  *   p e.next_values
00651  *   e = o.to_enum
00652  *   p e.next
00653  *   p e.next
00654  *   p e.next
00655  *   p e.next
00656  *   p e.next
00657  *
00658  *   ## yield args       next_values      next
00659  *   #  yield            []               nil
00660  *   #  yield 1          [1]              1
00661  *   #  yield 1, 2       [1, 2]           [1, 2]
00662  *   #  yield nil        [nil]            nil
00663  *   #  yield [1, 2]     [[1, 2]]         [1, 2]
00664  *
00665  * Note that +next_values+ does not affect other non-external enumeration
00666  * methods unless underlying iteration method itself has side-effect, e.g.
00667  * IO#each_line.
00668  *
00669  */
00670 
00671 static VALUE
00672 enumerator_next_values(VALUE obj)
00673 {
00674     struct enumerator *e = enumerator_ptr(obj);
00675     VALUE vs;
00676 
00677     if (e->lookahead != Qundef) {
00678         vs = e->lookahead;
00679         e->lookahead = Qundef;
00680         return vs;
00681     }
00682 
00683     return get_next_values(obj, e);
00684 }
00685 
00686 static VALUE
00687 ary2sv(VALUE args, int dup)
00688 {
00689     if (!RB_TYPE_P(args, T_ARRAY))
00690         return args;
00691 
00692     switch (RARRAY_LEN(args)) {
00693       case 0:
00694         return Qnil;
00695 
00696       case 1:
00697         return RARRAY_PTR(args)[0];
00698 
00699       default:
00700         if (dup)
00701             return rb_ary_dup(args);
00702         return args;
00703     }
00704 }
00705 
00706 /*
00707  * call-seq:
00708  *   e.next   -> object
00709  *
00710  * Returns the next object in the enumerator, and move the internal position
00711  * forward.  When the position reached at the end, StopIteration is raised.
00712  *
00713  * === Example
00714  *
00715  *   a = [1,2,3]
00716  *   e = a.to_enum
00717  *   p e.next   #=> 1
00718  *   p e.next   #=> 2
00719  *   p e.next   #=> 3
00720  *   p e.next   #raises StopIteration
00721  *
00722  * Note that enumeration sequence by +next+ does not affect other non-external
00723  * enumeration methods, unless the underlying iteration methods itself has
00724  * side-effect, e.g. IO#each_line.
00725  *
00726  */
00727 
00728 static VALUE
00729 enumerator_next(VALUE obj)
00730 {
00731     VALUE vs = enumerator_next_values(obj);
00732     return ary2sv(vs, 0);
00733 }
00734 
00735 static VALUE
00736 enumerator_peek_values(VALUE obj)
00737 {
00738     struct enumerator *e = enumerator_ptr(obj);
00739 
00740     if (e->lookahead == Qundef) {
00741         e->lookahead = get_next_values(obj, e);
00742     }
00743     return e->lookahead;
00744 }
00745 
00746 /*
00747  * call-seq:
00748  *   e.peek_values   -> array
00749  *
00750  * Returns the next object as an array, similar to Enumerator#next_values, but
00751  * doesn't move the internal position forward.  If the position is already at
00752  * the end, StopIteration is raised.
00753  *
00754  * === Example
00755  *
00756  *   o = Object.new
00757  *   def o.each
00758  *     yield
00759  *     yield 1
00760  *     yield 1, 2
00761  *   end
00762  *   e = o.to_enum
00763  *   p e.peek_values    #=> []
00764  *   e.next
00765  *   p e.peek_values    #=> [1]
00766  *   p e.peek_values    #=> [1]
00767  *   e.next
00768  *   p e.peek_values    #=> [1, 2]
00769  *   e.next
00770  *   p e.peek_values    # raises StopIteration
00771  *
00772  */
00773 
00774 static VALUE
00775 enumerator_peek_values_m(VALUE obj)
00776 {
00777     return rb_ary_dup(enumerator_peek_values(obj));
00778 }
00779 
00780 /*
00781  * call-seq:
00782  *   e.peek   -> object
00783  *
00784  * Returns the next object in the enumerator, but doesn't move the internal
00785  * position forward.  If the position is already at the end, StopIteration
00786  * is raised.
00787  *
00788  * === Example
00789  *
00790  *   a = [1,2,3]
00791  *   e = a.to_enum
00792  *   p e.next   #=> 1
00793  *   p e.peek   #=> 2
00794  *   p e.peek   #=> 2
00795  *   p e.peek   #=> 2
00796  *   p e.next   #=> 2
00797  *   p e.next   #=> 3
00798  *   p e.next   #raises StopIteration
00799  *
00800  */
00801 
00802 static VALUE
00803 enumerator_peek(VALUE obj)
00804 {
00805     VALUE vs = enumerator_peek_values(obj);
00806     return ary2sv(vs, 1);
00807 }
00808 
00809 /*
00810  * call-seq:
00811  *   e.feed obj   -> nil
00812  *
00813  * Sets the value to be returned by the next yield inside +e+.
00814  *
00815  * If the value is not set, the yield returns nil.
00816  *
00817  * This value is cleared after being yielded.
00818  *
00819  *   o = Object.new
00820  *   def o.each
00821  *     x = yield         # (2) blocks
00822  *     p x               # (5) => "foo"
00823  *     x = yield         # (6) blocks
00824  *     p x               # (8) => nil
00825  *     x = yield         # (9) blocks
00826  *     p x               # not reached w/o another e.next
00827  *   end
00828  *
00829  *   e = o.to_enum
00830  *   e.next              # (1)
00831  *   e.feed "foo"        # (3)
00832  *   e.next              # (4)
00833  *   e.next              # (7)
00834  *                       # (10)
00835  */
00836 
00837 static VALUE
00838 enumerator_feed(VALUE obj, VALUE v)
00839 {
00840     struct enumerator *e = enumerator_ptr(obj);
00841 
00842     if (e->feedvalue != Qundef) {
00843         rb_raise(rb_eTypeError, "feed value already set");
00844     }
00845     e->feedvalue = v;
00846 
00847     return Qnil;
00848 }
00849 
00850 /*
00851  * call-seq:
00852  *   e.rewind   -> e
00853  *
00854  * Rewinds the enumeration sequence to the beginning.
00855  *
00856  * If the enclosed object responds to a "rewind" method, it is called.
00857  */
00858 
00859 static VALUE
00860 enumerator_rewind(VALUE obj)
00861 {
00862     struct enumerator *e = enumerator_ptr(obj);
00863 
00864     rb_check_funcall(e->obj, id_rewind, 0, 0);
00865 
00866     e->fib = 0;
00867     e->dst = Qnil;
00868     e->lookahead = Qundef;
00869     e->feedvalue = Qundef;
00870     e->stop_exc = Qfalse;
00871     return obj;
00872 }
00873 
00874 static VALUE
00875 inspect_enumerator(VALUE obj, VALUE dummy, int recur)
00876 {
00877     struct enumerator *e;
00878     const char *cname;
00879     VALUE eobj, eargs, str, method;
00880     int tainted, untrusted;
00881 
00882     TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, e);
00883 
00884     cname = rb_obj_classname(obj);
00885 
00886     if (!e || e->obj == Qundef) {
00887         return rb_sprintf("#<%s: uninitialized>", cname);
00888     }
00889 
00890     if (recur) {
00891         str = rb_sprintf("#<%s: ...>", cname);
00892         OBJ_TAINT(str);
00893         return str;
00894     }
00895 
00896     eobj = rb_attr_get(obj, id_receiver);
00897     if (NIL_P(eobj)) {
00898         eobj = e->obj;
00899     }
00900 
00901     tainted   = OBJ_TAINTED(eobj);
00902     untrusted = OBJ_UNTRUSTED(eobj);
00903 
00904     /* (1..100).each_cons(2) => "#<Enumerator: 1..100:each_cons(2)>" */
00905     str = rb_sprintf("#<%s: ", cname);
00906     rb_str_concat(str, rb_inspect(eobj));
00907     method = rb_attr_get(obj, id_method);
00908     if (NIL_P(method)) {
00909         rb_str_buf_cat2(str, ":");
00910         rb_str_buf_cat2(str, rb_id2name(e->meth));
00911     }
00912     else if (method != Qfalse) {
00913         Check_Type(method, T_SYMBOL);
00914         rb_str_buf_cat2(str, ":");
00915         rb_str_buf_cat2(str, rb_id2name(SYM2ID(method)));
00916     }
00917 
00918     eargs = rb_attr_get(obj, id_arguments);
00919     if (NIL_P(eargs)) {
00920         eargs = e->args;
00921     }
00922     if (eargs != Qfalse) {
00923         long   argc = RARRAY_LEN(eargs);
00924         VALUE *argv = RARRAY_PTR(eargs);
00925 
00926         if (argc > 0) {
00927             rb_str_buf_cat2(str, "(");
00928 
00929             while (argc--) {
00930                 VALUE arg = *argv++;
00931 
00932                 rb_str_concat(str, rb_inspect(arg));
00933                 rb_str_buf_cat2(str, argc > 0 ? ", " : ")");
00934 
00935                 if (OBJ_TAINTED(arg)) tainted = TRUE;
00936                 if (OBJ_UNTRUSTED(arg)) untrusted = TRUE;
00937             }
00938         }
00939     }
00940 
00941     rb_str_buf_cat2(str, ">");
00942 
00943     if (tainted) OBJ_TAINT(str);
00944     if (untrusted) OBJ_UNTRUST(str);
00945     return str;
00946 }
00947 
00948 /*
00949  * call-seq:
00950  *   e.inspect  -> string
00951  *
00952  * Creates a printable version of <i>e</i>.
00953  */
00954 
00955 static VALUE
00956 enumerator_inspect(VALUE obj)
00957 {
00958     return rb_exec_recursive(inspect_enumerator, obj, 0);
00959 }
00960 
00961 /*
00962  * call-seq:
00963  *   e.size          -> int, Float::INFINITY or nil
00964  *
00965  * Returns the size of the enumerator, or +nil+ if it can't be calculated lazily.
00966  *
00967  *   (1..100).to_a.permutation(4).size # => 94109400
00968  *   loop.size # => Float::INFINITY
00969  *   (1..100).drop_while.size # => nil
00970  */
00971 
00972 static VALUE
00973 enumerator_size(VALUE obj)
00974 {
00975     struct enumerator *e = enumerator_ptr(obj);
00976 
00977     if (e->size_fn) {
00978         return (*e->size_fn)(e->obj, e->args, obj);
00979     }
00980     if (rb_obj_is_proc(e->size)) {
00981         if (e->args)
00982             return rb_proc_call(e->size, e->args);
00983         else
00984             return rb_proc_call_with_block(e->size, 0, 0, Qnil);
00985     }
00986     return e->size;
00987 }
00988 
00989 /*
00990  * Yielder
00991  */
00992 static void
00993 yielder_mark(void *p)
00994 {
00995     struct yielder *ptr = p;
00996     rb_gc_mark(ptr->proc);
00997 }
00998 
00999 #define yielder_free RUBY_TYPED_DEFAULT_FREE
01000 
01001 static size_t
01002 yielder_memsize(const void *p)
01003 {
01004     return p ? sizeof(struct yielder) : 0;
01005 }
01006 
01007 static const rb_data_type_t yielder_data_type = {
01008     "yielder",
01009     {
01010         yielder_mark,
01011         yielder_free,
01012         yielder_memsize,
01013     },
01014 };
01015 
01016 static struct yielder *
01017 yielder_ptr(VALUE obj)
01018 {
01019     struct yielder *ptr;
01020 
01021     TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
01022     if (!ptr || ptr->proc == Qundef) {
01023         rb_raise(rb_eArgError, "uninitialized yielder");
01024     }
01025     return ptr;
01026 }
01027 
01028 /* :nodoc: */
01029 static VALUE
01030 yielder_allocate(VALUE klass)
01031 {
01032     struct yielder *ptr;
01033     VALUE obj;
01034 
01035     obj = TypedData_Make_Struct(klass, struct yielder, &yielder_data_type, ptr);
01036     ptr->proc = Qundef;
01037 
01038     return obj;
01039 }
01040 
01041 static VALUE
01042 yielder_init(VALUE obj, VALUE proc)
01043 {
01044     struct yielder *ptr;
01045 
01046     TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
01047 
01048     if (!ptr) {
01049         rb_raise(rb_eArgError, "unallocated yielder");
01050     }
01051 
01052     ptr->proc = proc;
01053 
01054     return obj;
01055 }
01056 
01057 /* :nodoc: */
01058 static VALUE
01059 yielder_initialize(VALUE obj)
01060 {
01061     rb_need_block();
01062 
01063     return yielder_init(obj, rb_block_proc());
01064 }
01065 
01066 /* :nodoc: */
01067 static VALUE
01068 yielder_yield(VALUE obj, VALUE args)
01069 {
01070     struct yielder *ptr = yielder_ptr(obj);
01071 
01072     return rb_proc_call(ptr->proc, args);
01073 }
01074 
01075 /* :nodoc: */
01076 static VALUE yielder_yield_push(VALUE obj, VALUE args)
01077 {
01078     yielder_yield(obj, args);
01079     return obj;
01080 }
01081 
01082 static VALUE
01083 yielder_yield_i(VALUE obj, VALUE memo, int argc, VALUE *argv)
01084 {
01085     return rb_yield_values2(argc, argv);
01086 }
01087 
01088 static VALUE
01089 yielder_new(void)
01090 {
01091     return yielder_init(yielder_allocate(rb_cYielder), rb_proc_new(yielder_yield_i, 0));
01092 }
01093 
01094 /*
01095  * Generator
01096  */
01097 static void
01098 generator_mark(void *p)
01099 {
01100     struct generator *ptr = p;
01101     rb_gc_mark(ptr->proc);
01102 }
01103 
01104 #define generator_free RUBY_TYPED_DEFAULT_FREE
01105 
01106 static size_t
01107 generator_memsize(const void *p)
01108 {
01109     return p ? sizeof(struct generator) : 0;
01110 }
01111 
01112 static const rb_data_type_t generator_data_type = {
01113     "generator",
01114     {
01115         generator_mark,
01116         generator_free,
01117         generator_memsize,
01118     },
01119 };
01120 
01121 static struct generator *
01122 generator_ptr(VALUE obj)
01123 {
01124     struct generator *ptr;
01125 
01126     TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
01127     if (!ptr || ptr->proc == Qundef) {
01128         rb_raise(rb_eArgError, "uninitialized generator");
01129     }
01130     return ptr;
01131 }
01132 
01133 /* :nodoc: */
01134 static VALUE
01135 generator_allocate(VALUE klass)
01136 {
01137     struct generator *ptr;
01138     VALUE obj;
01139 
01140     obj = TypedData_Make_Struct(klass, struct generator, &generator_data_type, ptr);
01141     ptr->proc = Qundef;
01142 
01143     return obj;
01144 }
01145 
01146 static VALUE
01147 generator_init(VALUE obj, VALUE proc)
01148 {
01149     struct generator *ptr;
01150 
01151     TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
01152 
01153     if (!ptr) {
01154         rb_raise(rb_eArgError, "unallocated generator");
01155     }
01156 
01157     ptr->proc = proc;
01158 
01159     return obj;
01160 }
01161 
01162 /* :nodoc: */
01163 static VALUE
01164 generator_initialize(int argc, VALUE *argv, VALUE obj)
01165 {
01166     VALUE proc;
01167 
01168     if (argc == 0) {
01169         rb_need_block();
01170 
01171         proc = rb_block_proc();
01172     }
01173     else {
01174         rb_scan_args(argc, argv, "1", &proc);
01175 
01176         if (!rb_obj_is_proc(proc))
01177             rb_raise(rb_eTypeError,
01178                      "wrong argument type %s (expected Proc)",
01179                      rb_obj_classname(proc));
01180 
01181         if (rb_block_given_p()) {
01182             rb_warn("given block not used");
01183         }
01184     }
01185 
01186     return generator_init(obj, proc);
01187 }
01188 
01189 /* :nodoc: */
01190 static VALUE
01191 generator_init_copy(VALUE obj, VALUE orig)
01192 {
01193     struct generator *ptr0, *ptr1;
01194 
01195     if (!OBJ_INIT_COPY(obj, orig)) return obj;
01196 
01197     ptr0 = generator_ptr(orig);
01198 
01199     TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr1);
01200 
01201     if (!ptr1) {
01202         rb_raise(rb_eArgError, "unallocated generator");
01203     }
01204 
01205     ptr1->proc = ptr0->proc;
01206 
01207     return obj;
01208 }
01209 
01210 /* :nodoc: */
01211 static VALUE
01212 generator_each(int argc, VALUE *argv, VALUE obj)
01213 {
01214     struct generator *ptr = generator_ptr(obj);
01215     VALUE args = rb_ary_new2(argc + 1);
01216 
01217     rb_ary_push(args, yielder_new());
01218     if (argc > 0) {
01219         rb_ary_cat(args, argv, argc);
01220     }
01221 
01222     return rb_proc_call(ptr->proc, args);
01223 }
01224 
01225 /* Lazy Enumerator methods */
01226 static VALUE
01227 enum_size(VALUE self)
01228 {
01229     VALUE r = rb_check_funcall(self, id_size, 0, 0);
01230     return (r == Qundef) ? Qnil : r;
01231 }
01232 
01233 static VALUE
01234 lazy_size(VALUE self)
01235 {
01236     return enum_size(rb_ivar_get(self, id_receiver));
01237 }
01238 
01239 static VALUE
01240 lazy_receiver_size(VALUE generator, VALUE args, VALUE lazy)
01241 {
01242     return lazy_size(lazy);
01243 }
01244 
01245 static VALUE
01246 lazy_init_iterator(VALUE val, VALUE m, int argc, VALUE *argv)
01247 {
01248     VALUE result;
01249     if (argc == 1) {
01250         VALUE args[2];
01251         args[0] = m;
01252         args[1] = val;
01253         result = rb_yield_values2(2, args);
01254     }
01255     else {
01256         VALUE args;
01257         int len = rb_long2int((long)argc + 1);
01258 
01259         args = rb_ary_tmp_new(len);
01260         rb_ary_push(args, m);
01261         if (argc > 0) {
01262             rb_ary_cat(args, argv, argc);
01263         }
01264         result = rb_yield_values2(len, RARRAY_PTR(args));
01265         RB_GC_GUARD(args);
01266     }
01267     if (result == Qundef) rb_iter_break();
01268     return Qnil;
01269 }
01270 
01271 static VALUE
01272 lazy_init_block_i(VALUE val, VALUE m, int argc, VALUE *argv)
01273 {
01274     rb_block_call(m, id_each, argc-1, argv+1, lazy_init_iterator, val);
01275     return Qnil;
01276 }
01277 
01278 /*
01279  * call-seq:
01280  *   Lazy.new(obj, size=nil) { |yielder, *values| ... }
01281  *
01282  * Creates a new Lazy enumerator. When the enumerator is actually enumerated
01283  * (e.g. by calling #force), +obj+ will be enumerated and each value passed
01284  * to the given block. The block can yield values back using +yielder+.
01285  * For example, to create a method +filter_map+ in both lazy and
01286  * non-lazy fashions:
01287  *
01288  *   module Enumerable
01289  *     def filter_map(&block)
01290  *       map(&block).compact
01291  *     end
01292  *   end
01293  *
01294  *   class Enumerator::Lazy
01295  *     def filter_map
01296  *       Lazy.new(self) do |yielder, *values|
01297  *         result = yield *values
01298  *         yielder << result if result
01299  *       end
01300  *     end
01301  *   end
01302  *
01303  *   (1..Float::INFINITY).lazy.filter_map{|i| i*i if i.even?}.first(5)
01304  *       # => [4, 16, 36, 64, 100]
01305  */
01306 static VALUE
01307 lazy_initialize(int argc, VALUE *argv, VALUE self)
01308 {
01309     VALUE obj, size = Qnil;
01310     VALUE generator;
01311 
01312     rb_check_arity(argc, 1, 2);
01313     if (!rb_block_given_p()) {
01314         rb_raise(rb_eArgError, "tried to call lazy new without a block");
01315     }
01316     obj = argv[0];
01317     if (argc > 1) {
01318         size = argv[1];
01319     }
01320     generator = generator_allocate(rb_cGenerator);
01321     rb_block_call(generator, id_initialize, 0, 0, lazy_init_block_i, obj);
01322     enumerator_init(self, generator, sym_each, 0, 0, 0, size);
01323     rb_ivar_set(self, id_receiver, obj);
01324 
01325     return self;
01326 }
01327 
01328 static VALUE
01329 lazy_set_method(VALUE lazy, VALUE args, VALUE (*size_fn)(ANYARGS))
01330 {
01331     ID id = rb_frame_this_func();
01332     struct enumerator *e = enumerator_ptr(lazy);
01333     rb_ivar_set(lazy, id_method, ID2SYM(id));
01334     if (NIL_P(args)) {
01335         /* Qfalse indicates that the arguments are empty */
01336         rb_ivar_set(lazy, id_arguments, Qfalse);
01337     }
01338     else {
01339         rb_ivar_set(lazy, id_arguments, args);
01340     }
01341     e->size_fn = size_fn;
01342     return lazy;
01343 }
01344 
01345 /*
01346  * call-seq:
01347  *   e.lazy -> lazy_enumerator
01348  *
01349  * Returns a lazy enumerator, whose methods map/collect,
01350  * flat_map/collect_concat, select/find_all, reject, grep, zip, take,
01351  * take_while, drop, and drop_while enumerate values only on an
01352  * as-needed basis.  However, if a block is given to zip, values
01353  * are enumerated immediately.
01354  *
01355  * === Example
01356  *
01357  * The following program finds pythagorean triples:
01358  *
01359  *   def pythagorean_triples
01360  *     (1..Float::INFINITY).lazy.flat_map {|z|
01361  *       (1..z).flat_map {|x|
01362  *         (x..z).select {|y|
01363  *           x**2 + y**2 == z**2
01364  *         }.map {|y|
01365  *           [x, y, z]
01366  *         }
01367  *       }
01368  *     }
01369  *   end
01370  *   # show first ten pythagorean triples
01371  *   p pythagorean_triples.take(10).force # take is lazy, so force is needed
01372  *   p pythagorean_triples.first(10)      # first is eager
01373  *   # show pythagorean triples less than 100
01374  *   p pythagorean_triples.take_while { |*, z| z < 100 }.force
01375  */
01376 static VALUE
01377 enumerable_lazy(VALUE obj)
01378 {
01379     VALUE result = lazy_to_enum_i(obj, sym_each, 0, 0, enum_size);
01380     /* Qfalse indicates that the Enumerator::Lazy has no method name */
01381     rb_ivar_set(result, id_method, Qfalse);
01382     return result;
01383 }
01384 
01385 static VALUE
01386 lazy_to_enum_i(VALUE obj, VALUE meth, int argc, VALUE *argv, VALUE (*size_fn)(ANYARGS))
01387 {
01388     return enumerator_init(enumerator_allocate(rb_cLazy),
01389         obj, meth, argc, argv, size_fn, Qnil);
01390 }
01391 
01392 /*
01393  * call-seq:
01394  *   lzy.to_enum(method = :each, *args)                 -> lazy_enum
01395  *   lzy.enum_for(method = :each, *args)                -> lazy_enum
01396  *   lzy.to_enum(method = :each, *args) {|*args| block} -> lazy_enum
01397  *   lzy.enum_for(method = :each, *args){|*args| block} -> lazy_enum
01398  *
01399  * Similar to Kernel#to_enum, except it returns a lazy enumerator.
01400  * This makes it easy to define Enumerable methods that will
01401  * naturally remain lazy if called from a lazy enumerator.
01402  *
01403  * For example, continuing from the example in Kernel#to_enum:
01404  *
01405  *   # See Kernel#to_enum for the definition of repeat
01406  *   r = 1..Float::INFINITY
01407  *   r.repeat(2).first(5) # => [1, 1, 2, 2, 3]
01408  *   r.repeat(2).class # => Enumerator
01409  *   r.repeat(2).map{|n| n ** 2}.first(5) # => endless loop!
01410  *   # works naturally on lazy enumerator:
01411  *   r.lazy.repeat(2).class # => Enumerator::Lazy
01412  *   r.lazy.repeat(2).map{|n| n ** 2}.first(5) # => [1, 1, 4, 4, 9]
01413  */
01414 
01415 static VALUE
01416 lazy_to_enum(int argc, VALUE *argv, VALUE self)
01417 {
01418     VALUE lazy, meth = sym_each;
01419 
01420     if (argc > 0) {
01421         --argc;
01422         meth = *argv++;
01423     }
01424     lazy = lazy_to_enum_i(self, meth, argc, argv, 0);
01425     if (rb_block_given_p()) {
01426         enumerator_ptr(lazy)->size = rb_block_proc();
01427     }
01428     return lazy;
01429 }
01430 
01431 static VALUE
01432 lazy_map_func(VALUE val, VALUE m, int argc, VALUE *argv)
01433 {
01434     VALUE result = rb_yield_values2(argc - 1, &argv[1]);
01435 
01436     rb_funcall(argv[0], id_yield, 1, result);
01437     return Qnil;
01438 }
01439 
01440 static VALUE
01441 lazy_map(VALUE obj)
01442 {
01443     if (!rb_block_given_p()) {
01444         rb_raise(rb_eArgError, "tried to call lazy map without a block");
01445     }
01446 
01447     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01448                                          lazy_map_func, 0),
01449                            Qnil, lazy_receiver_size);
01450 }
01451 
01452 static VALUE
01453 lazy_flat_map_i(VALUE i, VALUE yielder, int argc, VALUE *argv)
01454 {
01455     return rb_funcall2(yielder, id_yield, argc, argv);
01456 }
01457 
01458 static VALUE
01459 lazy_flat_map_each(VALUE obj, VALUE yielder)
01460 {
01461     rb_block_call(obj, id_each, 0, 0, lazy_flat_map_i, yielder);
01462     return Qnil;
01463 }
01464 
01465 static VALUE
01466 lazy_flat_map_to_ary(VALUE obj, VALUE yielder)
01467 {
01468     VALUE ary = rb_check_array_type(obj);
01469     if (NIL_P(ary)) {
01470         rb_funcall(yielder, id_yield, 1, obj);
01471     }
01472     else {
01473         long i;
01474         for (i = 0; i < RARRAY_LEN(ary); i++) {
01475             rb_funcall(yielder, id_yield, 1, RARRAY_PTR(ary)[i]);
01476         }
01477     }
01478     return Qnil;
01479 }
01480 
01481 static VALUE
01482 lazy_flat_map_func(VALUE val, VALUE m, int argc, VALUE *argv)
01483 {
01484     VALUE result = rb_yield_values2(argc - 1, &argv[1]);
01485     if (RB_TYPE_P(result, T_ARRAY)) {
01486         long i;
01487         for (i = 0; i < RARRAY_LEN(result); i++) {
01488             rb_funcall(argv[0], id_yield, 1, RARRAY_PTR(result)[i]);
01489         }
01490     }
01491     else {
01492         if (rb_respond_to(result, id_force) && rb_respond_to(result, id_each)) {
01493             lazy_flat_map_each(result, argv[0]);
01494         }
01495         else {
01496             lazy_flat_map_to_ary(result, argv[0]);
01497         }
01498     }
01499     return Qnil;
01500 }
01501 
01502 /*
01503  *  call-seq:
01504  *     lazy.flat_map       { |obj| block } -> a_lazy_enumerator
01505  *
01506  *  Returns a new lazy enumerator with the concatenated results of running
01507  *  <i>block</i> once for every element in <i>lazy</i>.
01508  *
01509  *    ["foo", "bar"].lazy.flat_map {|i| i.each_char.lazy}.force
01510  *    #=> ["f", "o", "o", "b", "a", "r"]
01511  *
01512  *  A value <i>x</i> returned by <i>block</i> is decomposed if either of
01513  *  the following conditions is true:
01514  *
01515  *    a) <i>x</i> responds to both each and force, which means that
01516  *       <i>x</i> is a lazy enumerator.
01517  *    b) <i>x</i> is an array or responds to to_ary.
01518  *
01519  *  Otherwise, <i>x</i> is contained as-is in the return value.
01520  *
01521  *    [{a:1}, {b:2}].lazy.flat_map {|i| i}.force
01522  *    #=> [{:a=>1}, {:b=>2}]
01523  */
01524 static VALUE
01525 lazy_flat_map(VALUE obj)
01526 {
01527     if (!rb_block_given_p()) {
01528         rb_raise(rb_eArgError, "tried to call lazy flat_map without a block");
01529     }
01530 
01531     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01532                                          lazy_flat_map_func, 0),
01533                            Qnil, 0);
01534 }
01535 
01536 static VALUE
01537 lazy_select_func(VALUE val, VALUE m, int argc, VALUE *argv)
01538 {
01539     VALUE element = rb_enum_values_pack(argc - 1, argv + 1);
01540 
01541     if (RTEST(rb_yield(element))) {
01542         return rb_funcall(argv[0], id_yield, 1, element);
01543     }
01544     return Qnil;
01545 }
01546 
01547 static VALUE
01548 lazy_select(VALUE obj)
01549 {
01550     if (!rb_block_given_p()) {
01551         rb_raise(rb_eArgError, "tried to call lazy select without a block");
01552     }
01553 
01554     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01555                                          lazy_select_func, 0),
01556                            Qnil, 0);
01557 }
01558 
01559 static VALUE
01560 lazy_reject_func(VALUE val, VALUE m, int argc, VALUE *argv)
01561 {
01562     VALUE element = rb_enum_values_pack(argc - 1, argv + 1);
01563 
01564     if (!RTEST(rb_yield(element))) {
01565         return rb_funcall(argv[0], id_yield, 1, element);
01566     }
01567     return Qnil;
01568 }
01569 
01570 static VALUE
01571 lazy_reject(VALUE obj)
01572 {
01573     if (!rb_block_given_p()) {
01574         rb_raise(rb_eArgError, "tried to call lazy reject without a block");
01575     }
01576 
01577     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01578                                          lazy_reject_func, 0),
01579                            Qnil, 0);
01580 }
01581 
01582 static VALUE
01583 lazy_grep_func(VALUE val, VALUE m, int argc, VALUE *argv)
01584 {
01585     VALUE i = rb_enum_values_pack(argc - 1, argv + 1);
01586     VALUE result = rb_funcall(m, id_eqq, 1, i);
01587 
01588     if (RTEST(result)) {
01589         rb_funcall(argv[0], id_yield, 1, i);
01590     }
01591     return Qnil;
01592 }
01593 
01594 static VALUE
01595 lazy_grep_iter(VALUE val, VALUE m, int argc, VALUE *argv)
01596 {
01597     VALUE i = rb_enum_values_pack(argc - 1, argv + 1);
01598     VALUE result = rb_funcall(m, id_eqq, 1, i);
01599 
01600     if (RTEST(result)) {
01601         rb_funcall(argv[0], id_yield, 1, rb_yield(i));
01602     }
01603     return Qnil;
01604 }
01605 
01606 static VALUE
01607 lazy_grep(VALUE obj, VALUE pattern)
01608 {
01609     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01610                                          rb_block_given_p() ?
01611                                          lazy_grep_iter : lazy_grep_func,
01612                                          pattern),
01613                            rb_ary_new3(1, pattern), 0);
01614 }
01615 
01616 static VALUE
01617 call_next(VALUE obj)
01618 {
01619     return rb_funcall(obj, id_next, 0);
01620 }
01621 
01622 static VALUE
01623 next_stopped(VALUE obj)
01624 {
01625     return Qnil;
01626 }
01627 
01628 static VALUE
01629 lazy_zip_arrays_func(VALUE val, VALUE arrays, int argc, VALUE *argv)
01630 {
01631     VALUE yielder, ary, memo;
01632     long i, count;
01633 
01634     yielder = argv[0];
01635     memo = rb_attr_get(yielder, id_memo);
01636     count = NIL_P(memo) ? 0 : NUM2LONG(memo);
01637 
01638     ary = rb_ary_new2(RARRAY_LEN(arrays) + 1);
01639     rb_ary_push(ary, argv[1]);
01640     for (i = 0; i < RARRAY_LEN(arrays); i++) {
01641         rb_ary_push(ary, rb_ary_entry(RARRAY_PTR(arrays)[i], count));
01642     }
01643     rb_funcall(yielder, id_yield, 1, ary);
01644     rb_ivar_set(yielder, id_memo, LONG2NUM(++count));
01645     return Qnil;
01646 }
01647 
01648 static VALUE
01649 lazy_zip_func(VALUE val, VALUE zip_args, int argc, VALUE *argv)
01650 {
01651     VALUE yielder, ary, arg, v;
01652     long i;
01653 
01654     yielder = argv[0];
01655     arg = rb_attr_get(yielder, id_memo);
01656     if (NIL_P(arg)) {
01657         arg = rb_ary_new2(RARRAY_LEN(zip_args));
01658         for (i = 0; i < RARRAY_LEN(zip_args); i++) {
01659             rb_ary_push(arg, rb_funcall(RARRAY_PTR(zip_args)[i], id_to_enum, 0));
01660         }
01661         rb_ivar_set(yielder, id_memo, arg);
01662     }
01663 
01664     ary = rb_ary_new2(RARRAY_LEN(arg) + 1);
01665     v = Qnil;
01666     if (--argc > 0) {
01667         ++argv;
01668         v = argc > 1 ? rb_ary_new4(argc, argv) : *argv;
01669     }
01670     rb_ary_push(ary, v);
01671     for (i = 0; i < RARRAY_LEN(arg); i++) {
01672         v = rb_rescue2(call_next, RARRAY_PTR(arg)[i], next_stopped, 0,
01673                        rb_eStopIteration, (VALUE)0);
01674         rb_ary_push(ary, v);
01675     }
01676     rb_funcall(yielder, id_yield, 1, ary);
01677     return Qnil;
01678 }
01679 
01680 static VALUE
01681 lazy_zip(int argc, VALUE *argv, VALUE obj)
01682 {
01683     VALUE ary, v;
01684     long i;
01685     rb_block_call_func *func = lazy_zip_arrays_func;
01686 
01687     if (rb_block_given_p()) {
01688         return rb_call_super(argc, argv);
01689     }
01690 
01691     ary = rb_ary_new2(argc);
01692     for (i = 0; i < argc; i++) {
01693         v = rb_check_array_type(argv[i]);
01694         if (NIL_P(v)) {
01695             for (; i < argc; i++) {
01696                 if (!rb_respond_to(argv[i], id_each)) {
01697                     rb_raise(rb_eTypeError, "wrong argument type %s (must respond to :each)",
01698                         rb_obj_classname(argv[i]));
01699                 }
01700             }
01701             ary = rb_ary_new4(argc, argv);
01702             func = lazy_zip_func;
01703             break;
01704         }
01705         rb_ary_push(ary, v);
01706     }
01707 
01708     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01709                                          func, ary),
01710                            ary, lazy_receiver_size);
01711 }
01712 
01713 static VALUE
01714 lazy_take_func(VALUE val, VALUE args, int argc, VALUE *argv)
01715 {
01716     long remain;
01717     VALUE memo = rb_attr_get(argv[0], id_memo);
01718     if (NIL_P(memo)) {
01719         memo = args;
01720     }
01721 
01722     rb_funcall2(argv[0], id_yield, argc - 1, argv + 1);
01723     if ((remain = NUM2LONG(memo)-1) == 0) {
01724         return Qundef;
01725     }
01726     else {
01727         rb_ivar_set(argv[0], id_memo, LONG2NUM(remain));
01728         return Qnil;
01729     }
01730 }
01731 
01732 static VALUE
01733 lazy_take_size(VALUE generator, VALUE args, VALUE lazy)
01734 {
01735     VALUE receiver = lazy_size(lazy);
01736     long len = NUM2LONG(RARRAY_PTR(rb_ivar_get(lazy, id_arguments))[0]);
01737     if (NIL_P(receiver) || (FIXNUM_P(receiver) && FIX2LONG(receiver) < len))
01738         return receiver;
01739     return LONG2NUM(len);
01740 }
01741 
01742 static VALUE
01743 lazy_take(VALUE obj, VALUE n)
01744 {
01745     long len = NUM2LONG(n);
01746     VALUE lazy;
01747 
01748     if (len < 0) {
01749         rb_raise(rb_eArgError, "attempt to take negative size");
01750     }
01751     if (len == 0) {
01752         VALUE len = INT2NUM(0);
01753         lazy = lazy_to_enum_i(obj, sym_cycle, 1, &len, 0);
01754     }
01755     else {
01756         lazy = rb_block_call(rb_cLazy, id_new, 1, &obj,
01757                                          lazy_take_func, n);
01758     }
01759     return lazy_set_method(lazy, rb_ary_new3(1, n), lazy_take_size);
01760 }
01761 
01762 static VALUE
01763 lazy_take_while_func(VALUE val, VALUE args, int argc, VALUE *argv)
01764 {
01765     VALUE result = rb_yield_values2(argc - 1, &argv[1]);
01766     if (!RTEST(result)) return Qundef;
01767     rb_funcall2(argv[0], id_yield, argc - 1, argv + 1);
01768     return Qnil;
01769 }
01770 
01771 static VALUE
01772 lazy_take_while(VALUE obj)
01773 {
01774     if (!rb_block_given_p()) {
01775         rb_raise(rb_eArgError, "tried to call lazy take_while without a block");
01776     }
01777     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01778                                          lazy_take_while_func, 0),
01779                            Qnil, 0);
01780 }
01781 
01782 static VALUE
01783 lazy_drop_size(VALUE generator, VALUE args, VALUE lazy)
01784 {
01785     long len = NUM2LONG(RARRAY_PTR(rb_ivar_get(lazy, id_arguments))[0]);
01786     VALUE receiver = lazy_size(lazy);
01787     if (NIL_P(receiver))
01788         return receiver;
01789     if (FIXNUM_P(receiver)) {
01790         len = FIX2LONG(receiver) - len;
01791         return LONG2FIX(len < 0 ? 0 : len);
01792     }
01793     return rb_funcall(receiver, '-', 1, LONG2NUM(len));
01794 }
01795 
01796 static VALUE
01797 lazy_drop_func(VALUE val, VALUE args, int argc, VALUE *argv)
01798 {
01799     long remain;
01800     VALUE memo = rb_attr_get(argv[0], id_memo);
01801     if (NIL_P(memo)) {
01802         memo = args;
01803     }
01804     if ((remain = NUM2LONG(memo)) == 0) {
01805         rb_funcall2(argv[0], id_yield, argc - 1, argv + 1);
01806     }
01807     else {
01808         rb_ivar_set(argv[0], id_memo, LONG2NUM(--remain));
01809     }
01810     return Qnil;
01811 }
01812 
01813 static VALUE
01814 lazy_drop(VALUE obj, VALUE n)
01815 {
01816     long len = NUM2LONG(n);
01817 
01818     if (len < 0) {
01819         rb_raise(rb_eArgError, "attempt to drop negative size");
01820     }
01821     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01822                                          lazy_drop_func, n),
01823                            rb_ary_new3(1, n), lazy_drop_size);
01824 }
01825 
01826 static VALUE
01827 lazy_drop_while_func(VALUE val, VALUE args, int argc, VALUE *argv)
01828 {
01829     VALUE memo = rb_attr_get(argv[0], id_memo);
01830     if (NIL_P(memo) && !RTEST(rb_yield_values2(argc - 1, &argv[1]))) {
01831         rb_ivar_set(argv[0], id_memo, memo = Qtrue);
01832     }
01833     if (memo == Qtrue) {
01834         rb_funcall2(argv[0], id_yield, argc - 1, argv + 1);
01835     }
01836     return Qnil;
01837 }
01838 
01839 static VALUE
01840 lazy_drop_while(VALUE obj)
01841 {
01842     if (!rb_block_given_p()) {
01843         rb_raise(rb_eArgError, "tried to call lazy drop_while without a block");
01844     }
01845     return lazy_set_method(rb_block_call(rb_cLazy, id_new, 1, &obj,
01846                                          lazy_drop_while_func, 0),
01847                            Qnil, 0);
01848 }
01849 
01850 static VALUE
01851 lazy_super(int argc, VALUE *argv, VALUE lazy)
01852 {
01853     return enumerable_lazy(rb_call_super(argc, argv));
01854 }
01855 
01856 static VALUE
01857 lazy_lazy(VALUE obj)
01858 {
01859     return obj;
01860 }
01861 
01862 /*
01863  * Document-class: StopIteration
01864  *
01865  * Raised to stop the iteration, in particular by Enumerator#next. It is
01866  * rescued by Kernel#loop.
01867  *
01868  *   loop do
01869  *     puts "Hello"
01870  *     raise StopIteration
01871  *     puts "World"
01872  *   end
01873  *   puts "Done!"
01874  *
01875  * <em>produces:</em>
01876  *
01877  *   Hello
01878  *   Done!
01879  */
01880 
01881 /*
01882  * call-seq:
01883  *   result       -> value
01884  *
01885  * Returns the return value of the iterator.
01886  *
01887  *   o = Object.new
01888  *   def o.each
01889  *     yield 1
01890  *     yield 2
01891  *     yield 3
01892  *     100
01893  *   end
01894  *
01895  *   e = o.to_enum
01896  *
01897  *   puts e.next                   #=> 1
01898  *   puts e.next                   #=> 2
01899  *   puts e.next                   #=> 3
01900  *
01901  *   begin
01902  *     e.next
01903  *   rescue StopIteration => ex
01904  *     puts ex.result              #=> 100
01905  *   end
01906  *
01907  */
01908 
01909 static VALUE
01910 stop_result(VALUE self)
01911 {
01912     return rb_attr_get(self, id_result);
01913 }
01914 
01915 void
01916 InitVM_Enumerator(void)
01917 {
01918     rb_define_method(rb_mKernel, "to_enum", obj_to_enum, -1);
01919     rb_define_method(rb_mKernel, "enum_for", obj_to_enum, -1);
01920 
01921     rb_cEnumerator = rb_define_class("Enumerator", rb_cObject);
01922     rb_include_module(rb_cEnumerator, rb_mEnumerable);
01923 
01924     rb_define_alloc_func(rb_cEnumerator, enumerator_allocate);
01925     rb_define_method(rb_cEnumerator, "initialize", enumerator_initialize, -1);
01926     rb_define_method(rb_cEnumerator, "initialize_copy", enumerator_init_copy, 1);
01927     rb_define_method(rb_cEnumerator, "each", enumerator_each, -1);
01928     rb_define_method(rb_cEnumerator, "each_with_index", enumerator_each_with_index, 0);
01929     rb_define_method(rb_cEnumerator, "each_with_object", enumerator_with_object, 1);
01930     rb_define_method(rb_cEnumerator, "with_index", enumerator_with_index, -1);
01931     rb_define_method(rb_cEnumerator, "with_object", enumerator_with_object, 1);
01932     rb_define_method(rb_cEnumerator, "next_values", enumerator_next_values, 0);
01933     rb_define_method(rb_cEnumerator, "peek_values", enumerator_peek_values_m, 0);
01934     rb_define_method(rb_cEnumerator, "next", enumerator_next, 0);
01935     rb_define_method(rb_cEnumerator, "peek", enumerator_peek, 0);
01936     rb_define_method(rb_cEnumerator, "feed", enumerator_feed, 1);
01937     rb_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
01938     rb_define_method(rb_cEnumerator, "inspect", enumerator_inspect, 0);
01939     rb_define_method(rb_cEnumerator, "size", enumerator_size, 0);
01940 
01941     /* Lazy */
01942     rb_cLazy = rb_define_class_under(rb_cEnumerator, "Lazy", rb_cEnumerator);
01943     rb_define_method(rb_mEnumerable, "lazy", enumerable_lazy, 0);
01944     rb_define_method(rb_cLazy, "initialize", lazy_initialize, -1);
01945     rb_define_method(rb_cLazy, "to_enum", lazy_to_enum, -1);
01946     rb_define_method(rb_cLazy, "enum_for", lazy_to_enum, -1);
01947     rb_define_method(rb_cLazy, "map", lazy_map, 0);
01948     rb_define_method(rb_cLazy, "collect", lazy_map, 0);
01949     rb_define_method(rb_cLazy, "flat_map", lazy_flat_map, 0);
01950     rb_define_method(rb_cLazy, "collect_concat", lazy_flat_map, 0);
01951     rb_define_method(rb_cLazy, "select", lazy_select, 0);
01952     rb_define_method(rb_cLazy, "find_all", lazy_select, 0);
01953     rb_define_method(rb_cLazy, "reject", lazy_reject, 0);
01954     rb_define_method(rb_cLazy, "grep", lazy_grep, 1);
01955     rb_define_method(rb_cLazy, "zip", lazy_zip, -1);
01956     rb_define_method(rb_cLazy, "take", lazy_take, 1);
01957     rb_define_method(rb_cLazy, "take_while", lazy_take_while, 0);
01958     rb_define_method(rb_cLazy, "drop", lazy_drop, 1);
01959     rb_define_method(rb_cLazy, "drop_while", lazy_drop_while, 0);
01960     rb_define_method(rb_cLazy, "lazy", lazy_lazy, 0);
01961     rb_define_method(rb_cLazy, "chunk", lazy_super, -1);
01962     rb_define_method(rb_cLazy, "slice_before", lazy_super, -1);
01963 
01964     rb_define_alias(rb_cLazy, "force", "to_a");
01965 
01966     rb_eStopIteration = rb_define_class("StopIteration", rb_eIndexError);
01967     rb_define_method(rb_eStopIteration, "result", stop_result, 0);
01968 
01969     /* Generator */
01970     rb_cGenerator = rb_define_class_under(rb_cEnumerator, "Generator", rb_cObject);
01971     rb_include_module(rb_cGenerator, rb_mEnumerable);
01972     rb_define_alloc_func(rb_cGenerator, generator_allocate);
01973     rb_define_method(rb_cGenerator, "initialize", generator_initialize, -1);
01974     rb_define_method(rb_cGenerator, "initialize_copy", generator_init_copy, 1);
01975     rb_define_method(rb_cGenerator, "each", generator_each, -1);
01976 
01977     /* Yielder */
01978     rb_cYielder = rb_define_class_under(rb_cEnumerator, "Yielder", rb_cObject);
01979     rb_define_alloc_func(rb_cYielder, yielder_allocate);
01980     rb_define_method(rb_cYielder, "initialize", yielder_initialize, 0);
01981     rb_define_method(rb_cYielder, "yield", yielder_yield, -2);
01982     rb_define_method(rb_cYielder, "<<", yielder_yield_push, -2);
01983 
01984     rb_provide("enumerator.so");        /* for backward compatibility */
01985 }
01986 
01987 void
01988 Init_Enumerator(void)
01989 {
01990     id_rewind = rb_intern("rewind");
01991     id_each = rb_intern("each");
01992     id_call = rb_intern("call");
01993     id_size = rb_intern("size");
01994     id_yield = rb_intern("yield");
01995     id_new = rb_intern("new");
01996     id_initialize = rb_intern("initialize");
01997     id_next = rb_intern("next");
01998     id_result = rb_intern("result");
01999     id_lazy = rb_intern("lazy");
02000     id_eqq = rb_intern("===");
02001     id_receiver = rb_intern("receiver");
02002     id_arguments = rb_intern("arguments");
02003     id_memo = rb_intern("memo");
02004     id_method = rb_intern("method");
02005     id_force = rb_intern("force");
02006     id_to_enum = rb_intern("to_enum");
02007     sym_each = ID2SYM(id_each);
02008     sym_cycle = ID2SYM(rb_intern("cycle"));
02009 
02010     InitVM(Enumerator);
02011 }
02012