Ruby 4.0.9p0 (2026-10-23 revision 3e93b23afcec3433f6aecc34b5d832799d754238)
enumerator.c
1/************************************************
2
3 enumerator.c - provides Enumerator class
4
5 $Author$
6
7 Copyright (C) 2001-2003 Akinori MUSHA
8
9 $Idaemons: /home/cvs/rb/enumerator/enumerator.c,v 1.1.1.1 2001/07/15 10:12:48 knu Exp $
10 $RoughId: enumerator.c,v 1.6 2003/07/27 11:03:24 nobu Exp $
11 $Id$
12
13************************************************/
14
15#include "ruby/internal/config.h"
16
17#ifdef HAVE_FLOAT_H
18#include <float.h>
19#endif
20
21#include <limits.h>
22#include "id.h"
23#include "internal.h"
24#include "internal/class.h"
25#include "internal/enumerator.h"
26#include "internal/error.h"
27#include "internal/hash.h"
28#include "internal/imemo.h"
29#include "internal/numeric.h"
30#include "internal/range.h"
31#include "internal/rational.h"
32#include "ruby/ruby.h"
33
34/*
35 * Document-class: Enumerator
36 *
37 * A class which allows both internal and external iteration.
38 *
39 * An Enumerator can be created by the following methods.
40 * - Object#to_enum
41 * - Object#enum_for
42 * - Enumerator.new
43 *
44 * Most methods have two forms: a block form where the contents
45 * are evaluated for each item in the enumeration, and a non-block form
46 * which returns a new Enumerator wrapping the iteration.
47 *
48 * enumerator = %w(one two three).each
49 * puts enumerator.class # => Enumerator
50 *
51 * enumerator.each_with_object("foo") do |item, obj|
52 * puts "#{obj}: #{item}"
53 * end
54 *
55 * # foo: one
56 * # foo: two
57 * # foo: three
58 *
59 * enum_with_obj = enumerator.each_with_object("foo")
60 * puts enum_with_obj.class # => Enumerator
61 *
62 * enum_with_obj.each do |item, obj|
63 * puts "#{obj}: #{item}"
64 * end
65 *
66 * # foo: one
67 * # foo: two
68 * # foo: three
69 *
70 * This allows you to chain Enumerators together. For example, you
71 * can map a list's elements to strings containing the index
72 * and the element as a string via:
73 *
74 * puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" }
75 * # => ["0:foo", "1:bar", "2:baz"]
76 *
77 * == External Iteration
78 *
79 * An Enumerator can also be used as an external iterator.
80 * For example, Enumerator#next returns the next value of the iterator
81 * or raises StopIteration if the Enumerator is at the end.
82 *
83 * e = [1,2,3].each # returns an enumerator object.
84 * puts e.next # => 1
85 * puts e.next # => 2
86 * puts e.next # => 3
87 * puts e.next # raises StopIteration
88 *
89 * +next+, +next_values+, +peek+, and +peek_values+ are the only methods
90 * which use external iteration (and Array#zip(Enumerable-not-Array) which uses +next+ internally).
91 *
92 * These methods do not affect other internal enumeration methods,
93 * unless the underlying iteration method itself has side-effect, e.g. IO#each_line.
94 *
95 * FrozenError will be raised if these methods are called against a frozen enumerator.
96 * Since +rewind+ and +feed+ also change state for external iteration,
97 * these methods may raise FrozenError too.
98 *
99 * External iteration differs *significantly* from internal iteration
100 * due to using a Fiber:
101 * - The Fiber adds some overhead compared to internal enumeration.
102 * - The stacktrace will only include the stack from the Enumerator, not above.
103 * - Fiber-local variables are *not* inherited inside the Enumerator Fiber,
104 * which instead starts with no Fiber-local variables.
105 * - Fiber storage variables *are* inherited and are designed
106 * to handle Enumerator Fibers. Assigning to a Fiber storage variable
107 * only affects the current Fiber, so if you want to change state
108 * in the caller Fiber of the Enumerator Fiber, you need to use an
109 * extra indirection (e.g., use some object in the Fiber storage
110 * variable and mutate some ivar of it).
111 *
112 * Concretely:
113 *
114 * Thread.current[:fiber_local] = 1
115 * Fiber[:storage_var] = 1
116 * e = Enumerator.new do |y|
117 * p Thread.current[:fiber_local] # for external iteration: nil, for internal iteration: 1
118 * p Fiber[:storage_var] # => 1, inherited
119 * Fiber[:storage_var] += 1
120 * y << 42
121 * end
122 *
123 * p e.next # => 42
124 * p Fiber[:storage_var] # => 1 (it ran in a different Fiber)
125 *
126 * e.each { p _1 }
127 * p Fiber[:storage_var] # => 2 (it ran in the same Fiber/"stack" as the current Fiber)
128 *
129 * == Convert External Iteration to Internal Iteration
130 *
131 * You can use an external iterator to implement an internal iterator as follows:
132 *
133 * def ext_each(e)
134 * while true
135 * begin
136 * vs = e.next_values
137 * rescue StopIteration
138 * return $!.result
139 * end
140 * y = yield(*vs)
141 * e.feed y
142 * end
143 * end
144 *
145 * o = Object.new
146 *
147 * def o.each
148 * puts yield
149 * puts yield(1)
150 * puts yield(1, 2)
151 * 3
152 * end
153 *
154 * # use o.each as an internal iterator directly.
155 * puts o.each {|*x| puts x; [:b, *x] }
156 * # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
157 *
158 * # convert o.each to an external iterator for
159 * # implementing an internal iterator.
160 * puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] }
161 * # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
162 *
163 */
165static VALUE rb_cLazy;
166static ID id_rewind, id_to_enum, id_each_entry;
167static ID id_next, id_result, id_receiver, id_arguments, id_memo, id_method, id_force;
168static VALUE sym_each, sym_yield;
169
170static VALUE lazy_use_super_method;
171
172extern ID ruby_static_id_cause;
173
174#define id_call idCall
175#define id_cause ruby_static_id_cause
176#define id_each idEach
177#define id_eqq idEqq
178#define id_initialize idInitialize
179#define id_size idSize
180
182
184 VALUE obj;
185 ID meth;
186 VALUE args;
187 VALUE fib;
188 VALUE dst;
189 VALUE lookahead;
190 VALUE feedvalue;
191 VALUE stop_exc;
192 VALUE size;
193 VALUE procs;
195 int kw_splat;
196};
197
198RUBY_REFERENCES(enumerator_refs) = {
199 RUBY_REF_EDGE(struct enumerator, obj),
200 RUBY_REF_EDGE(struct enumerator, args),
201 RUBY_REF_EDGE(struct enumerator, fib),
202 RUBY_REF_EDGE(struct enumerator, dst),
203 RUBY_REF_EDGE(struct enumerator, lookahead),
204 RUBY_REF_EDGE(struct enumerator, feedvalue),
205 RUBY_REF_EDGE(struct enumerator, stop_exc),
206 RUBY_REF_EDGE(struct enumerator, size),
207 RUBY_REF_EDGE(struct enumerator, procs),
208 RUBY_REF_END
209};
210
211static VALUE rb_cGenerator, rb_cYielder, rb_cEnumProducer;
212
213struct generator {
214 VALUE proc;
215 VALUE obj;
216};
217
218struct yielder {
219 VALUE proc;
220};
221
222struct producer {
223 VALUE init;
224 VALUE proc;
225 VALUE size;
226};
227
228typedef struct MEMO *lazyenum_proc_func(VALUE, struct MEMO *, VALUE, long);
229typedef VALUE lazyenum_size_func(VALUE, VALUE);
230typedef int lazyenum_precheck_func(VALUE proc_entry);
231typedef struct {
232 lazyenum_proc_func *proc;
233 lazyenum_size_func *size;
234 lazyenum_precheck_func *precheck;
236
238 VALUE proc;
239 VALUE memo;
240 const lazyenum_funcs *fn;
241};
242
243static VALUE generator_allocate(VALUE klass);
244static VALUE generator_init(VALUE obj, VALUE proc);
245
246static VALUE rb_cEnumChain;
247
249 VALUE enums;
250 long pos;
251};
252
253static VALUE rb_cEnumProduct;
254
256 VALUE enums;
257};
258
259VALUE rb_cArithSeq;
260
261static const rb_data_type_t enumerator_data_type = {
262 "enumerator",
263 {
264 RUBY_REFS_LIST_PTR(enumerator_refs),
266 NULL, // Nothing allocated externally, so don't need a memsize function
267 NULL,
268 },
269 0, NULL, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
270};
271
272static struct enumerator *
273enumerator_ptr(VALUE obj)
274{
275 struct enumerator *ptr;
276
277 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr);
278 if (!ptr || UNDEF_P(ptr->obj)) {
279 rb_raise(rb_eArgError, "uninitialized enumerator");
280 }
281 return ptr;
282}
283
284static void
285proc_entry_mark_and_move(void *p)
286{
287 struct proc_entry *ptr = p;
288 rb_gc_mark_and_move(&ptr->proc);
289 rb_gc_mark_and_move(&ptr->memo);
290}
291
292static const rb_data_type_t proc_entry_data_type = {
293 "proc_entry",
294 {
295 proc_entry_mark_and_move,
297 NULL, // Nothing allocated externally, so don't need a memsize function
298 proc_entry_mark_and_move,
299 },
300 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
301};
302
303static struct proc_entry *
304proc_entry_ptr(VALUE proc_entry)
305{
306 struct proc_entry *ptr;
307
308 TypedData_Get_Struct(proc_entry, struct proc_entry, &proc_entry_data_type, ptr);
309
310 return ptr;
311}
312
313/*
314 * call-seq:
315 * obj.to_enum(method = :each, *args) -> enum
316 * obj.enum_for(method = :each, *args) -> enum
317 * obj.to_enum(method = :each, *args) {|*args| block} -> enum
318 * obj.enum_for(method = :each, *args){|*args| block} -> enum
319 *
320 * Creates a new Enumerator which will enumerate by calling +method+ on
321 * +obj+, passing +args+ if any. What was _yielded_ by method becomes
322 * values of enumerator.
323 *
324 * If a block is given, it will be used to calculate the size of
325 * the enumerator without the need to iterate it (see Enumerator#size).
326 *
327 * === Examples
328 *
329 * str = "xyz"
330 *
331 * enum = str.enum_for(:each_byte)
332 * enum.each { |b| puts b }
333 * # => 120
334 * # => 121
335 * # => 122
336 *
337 * # protect an array from being modified by some_method
338 * a = [1, 2, 3]
339 * some_method(a.to_enum)
340 *
341 * # String#split in block form is more memory-effective:
342 * very_large_string.split("|") { |chunk| return chunk if chunk.include?('DATE') }
343 * # This could be rewritten more idiomatically with to_enum:
344 * very_large_string.to_enum(:split, "|").lazy.grep(/DATE/).first
345 *
346 * It is typical to call to_enum when defining methods for
347 * a generic Enumerable, in case no block is passed.
348 *
349 * Here is such an example, with parameter passing and a sizing block:
350 *
351 * module Enumerable
352 * # a generic method to repeat the values of any enumerable
353 * def repeat(n)
354 * raise ArgumentError, "#{n} is negative!" if n < 0
355 * unless block_given?
356 * return to_enum(__method__, n) do # __method__ is :repeat here
357 * sz = size # Call size and multiply by n...
358 * sz * n if sz # but return nil if size itself is nil
359 * end
360 * end
361 * each do |*val|
362 * n.times { yield *val }
363 * end
364 * end
365 * end
366 *
367 * %i[hello world].repeat(2) { |w| puts w }
368 * # => Prints 'hello', 'hello', 'world', 'world'
369 * enum = (1..14).repeat(3)
370 * # => returns an Enumerator when called without a block
371 * enum.first(4) # => [1, 1, 1, 2]
372 * enum.size # => 42
373 */
374static VALUE
375obj_to_enum(int argc, VALUE *argv, VALUE obj)
376{
377 VALUE enumerator, meth = sym_each;
378
379 if (argc > 0) {
380 --argc;
381 meth = *argv++;
382 }
383 enumerator = rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
384 if (rb_block_given_p()) {
385 RB_OBJ_WRITE(enumerator, &enumerator_ptr(enumerator)->size, rb_block_proc());
386 }
387 return enumerator;
388}
389
390static VALUE
391enumerator_allocate(VALUE klass)
392{
393 struct enumerator *ptr;
394 VALUE enum_obj;
395
396 enum_obj = TypedData_Make_Struct(klass, struct enumerator, &enumerator_data_type, ptr);
397 ptr->obj = Qundef;
398
399 return enum_obj;
400}
401
402static VALUE
403enumerator_init(VALUE enum_obj, VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, VALUE size, int kw_splat)
404{
405 struct enumerator *ptr;
406
407 rb_check_frozen(enum_obj);
408 TypedData_Get_Struct(enum_obj, struct enumerator, &enumerator_data_type, ptr);
409
410 if (!ptr) {
411 rb_raise(rb_eArgError, "unallocated enumerator");
412 }
413
414 RB_OBJ_WRITE(enum_obj, &ptr->obj, obj);
415 ptr->meth = rb_to_id(meth);
416 if (argc) RB_OBJ_WRITE(enum_obj, &ptr->args, rb_ary_new4(argc, argv));
417 ptr->fib = 0;
418 ptr->dst = Qnil;
419 ptr->lookahead = Qundef;
420 ptr->feedvalue = Qundef;
421 ptr->stop_exc = Qfalse;
422 RB_OBJ_WRITE(enum_obj, &ptr->size, size);
423 ptr->size_fn = size_fn;
424 ptr->kw_splat = kw_splat;
425
426 return enum_obj;
427}
428
429static VALUE
430convert_to_feasible_size_value(VALUE obj)
431{
432 if (NIL_P(obj)) {
433 return obj;
434 }
435 else if (rb_respond_to(obj, id_call)) {
436 return obj;
437 }
438 else if (RB_FLOAT_TYPE_P(obj) && RFLOAT_VALUE(obj) == HUGE_VAL) {
439 return obj;
440 }
441 else {
442 return rb_to_int(obj);
443 }
444}
445
446/*
447 * call-seq:
448 * Enumerator.new(size = nil) { |yielder| ... }
449 *
450 * Creates a new Enumerator object, which can be used as an
451 * Enumerable.
452 *
453 * Iteration is defined by the given block, in
454 * which a "yielder" object, given as block parameter, can be used to
455 * yield a value by calling the +yield+ method (aliased as <code><<</code>):
456 *
457 * fib = Enumerator.new do |y|
458 * a = b = 1
459 * loop do
460 * y << a
461 * a, b = b, a + b
462 * end
463 * end
464 *
465 * fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
466 *
467 * The optional parameter can be used to specify how to calculate the size
468 * in a lazy fashion (see Enumerator#size). It can either be a value or
469 * a callable object.
470 */
471static VALUE
472enumerator_initialize(int argc, VALUE *argv, VALUE obj)
473{
474 VALUE iter = rb_block_proc();
475 VALUE recv = generator_init(generator_allocate(rb_cGenerator), iter);
476 VALUE arg0 = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
477 VALUE size = convert_to_feasible_size_value(arg0);
478
479 return enumerator_init(obj, recv, sym_each, 0, 0, 0, size, false);
480}
481
482/* :nodoc: */
483static VALUE
484enumerator_init_copy(VALUE obj, VALUE orig)
485{
486 struct enumerator *ptr0, *ptr1;
487
488 if (!OBJ_INIT_COPY(obj, orig)) return obj;
489 ptr0 = enumerator_ptr(orig);
490 if (ptr0->fib) {
491 /* Fibers cannot be copied */
492 rb_raise(rb_eTypeError, "can't copy execution context");
493 }
494
495 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr1);
496
497 if (!ptr1) {
498 rb_raise(rb_eArgError, "unallocated enumerator");
499 }
500
501 RB_OBJ_WRITE(obj, &ptr1->obj, ptr0->obj);
502 ptr1->meth = ptr0->meth;
503 RB_OBJ_WRITE(obj, &ptr1->args, ptr0->args);
504 ptr1->fib = 0;
505 ptr1->lookahead = Qundef;
506 ptr1->feedvalue = Qundef;
507 RB_OBJ_WRITE(obj, &ptr1->size, ptr0->size);
508 ptr1->size_fn = ptr0->size_fn;
509
510 return obj;
511}
512
513/*
514 * For backwards compatibility; use rb_enumeratorize_with_size
515 */
516VALUE
517rb_enumeratorize(VALUE obj, VALUE meth, int argc, const VALUE *argv)
518{
519 return rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
520}
521
522static VALUE lazy_to_enum_i(VALUE self, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat);
523static int lazy_precheck(VALUE procs);
524
525VALUE
526rb_enumeratorize_with_size_kw(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat)
527{
528 VALUE base_class = rb_cEnumerator;
529
530 if (RTEST(rb_obj_is_kind_of(obj, rb_cLazy))) {
531 base_class = rb_cLazy;
532 }
533 else if (RTEST(rb_obj_is_kind_of(obj, rb_cEnumChain))) {
534 obj = enumerator_init(enumerator_allocate(rb_cEnumerator), obj, sym_each, 0, 0, 0, Qnil, false);
535 }
536
537 return enumerator_init(enumerator_allocate(base_class),
538 obj, meth, argc, argv, size_fn, Qnil, kw_splat);
539}
540
541VALUE
542rb_enumeratorize_with_size(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn)
543{
544 return rb_enumeratorize_with_size_kw(obj, meth, argc, argv, size_fn, rb_keyword_given_p());
545}
546
547static VALUE
548enumerator_block_call(VALUE obj, rb_block_call_func *func, VALUE arg)
549{
550 int argc = 0;
551 const VALUE *argv = 0;
552 const struct enumerator *e = enumerator_ptr(obj);
553 ID meth = e->meth;
554
555 VALUE args = e->args;
556 if (args) {
557 argc = RARRAY_LENINT(args);
558 argv = RARRAY_CONST_PTR(args);
559 }
560
561 VALUE ret = rb_block_call_kw(e->obj, meth, argc, argv, func, arg, e->kw_splat);
562
563 RB_GC_GUARD(args);
564
565 return ret;
566}
567
568/*
569 * call-seq:
570 * enum.each { |elm| block } -> obj
571 * enum.each -> enum
572 * enum.each(*appending_args) { |elm| block } -> obj
573 * enum.each(*appending_args) -> an_enumerator
574 *
575 * Iterates over the block according to how this Enumerator was constructed.
576 * If no block and no arguments are given, returns self.
577 *
578 * === Examples
579 *
580 * "Hello, world!".scan(/\w+/) #=> ["Hello", "world"]
581 * "Hello, world!".to_enum(:scan, /\w+/).to_a #=> ["Hello", "world"]
582 * "Hello, world!".to_enum(:scan).each(/\w+/).to_a #=> ["Hello", "world"]
583 *
584 * obj = Object.new
585 *
586 * def obj.each_arg(a, b=:b, *rest)
587 * yield a
588 * yield b
589 * yield rest
590 * :method_returned
591 * end
592 *
593 * enum = obj.to_enum :each_arg, :a, :x
594 *
595 * enum.each.to_a #=> [:a, :x, []]
596 * enum.each.equal?(enum) #=> true
597 * enum.each { |elm| elm } #=> :method_returned
598 *
599 * enum.each(:y, :z).to_a #=> [:a, :x, [:y, :z]]
600 * enum.each(:y, :z).equal?(enum) #=> false
601 * enum.each(:y, :z) { |elm| elm } #=> :method_returned
602 *
603 */
604static VALUE
605enumerator_each(int argc, VALUE *argv, VALUE obj)
606{
607 struct enumerator *e = enumerator_ptr(obj);
608
609 if (argc > 0) {
610 VALUE args = (e = enumerator_ptr(obj = rb_obj_dup(obj)))->args;
611 if (args) {
612#if SIZEOF_INT < SIZEOF_LONG
613 /* check int range overflow */
614 rb_long2int(RARRAY_LEN(args) + argc);
615#endif
616 args = rb_ary_dup(args);
617 rb_ary_cat(args, argv, argc);
618 }
619 else {
620 args = rb_ary_new4(argc, argv);
621 }
622 RB_OBJ_WRITE(obj, &e->args, args);
623 e->size = Qnil;
624 e->size_fn = 0;
625 }
626 if (!rb_block_given_p()) return obj;
627
628 if (!lazy_precheck(e->procs)) return Qnil;
629
630 return enumerator_block_call(obj, 0, obj);
631}
632
633static VALUE
634enumerator_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
635{
636 struct MEMO *memo = (struct MEMO *)m;
637 VALUE idx = memo->v1;
638 MEMO_V1_SET(memo, rb_int_succ(idx));
639
640 if (argc <= 1)
641 return rb_yield_values(2, val, idx);
642
643 return rb_yield_values(2, rb_ary_new4(argc, argv), idx);
644}
645
646static VALUE
647enumerator_size(VALUE obj);
648
649static VALUE
650enumerator_enum_size(VALUE obj, VALUE args, VALUE eobj)
651{
652 return enumerator_size(obj);
653}
654
655/*
656 * call-seq:
657 * e.with_index(offset = 0) {|(*args), idx| ... }
658 * e.with_index(offset = 0)
659 *
660 * Iterates the given block for each element with an index, which
661 * starts from +offset+. If no block is given, returns a new Enumerator
662 * that includes the index, starting from +offset+
663 *
664 * +offset+:: the starting index to use
665 *
666 */
667static VALUE
668enumerator_with_index(int argc, VALUE *argv, VALUE obj)
669{
670 VALUE memo;
671
672 rb_check_arity(argc, 0, 1);
673 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enumerator_enum_size);
674 memo = (!argc || NIL_P(memo = argv[0])) ? INT2FIX(0) : rb_to_int(memo);
675 return enumerator_block_call(obj, enumerator_with_index_i, (VALUE)MEMO_NEW(memo, 0, 0));
676}
677
678/*
679 * call-seq:
680 * e.each_with_index {|(*args), idx| ... }
681 * e.each_with_index
682 *
683 * Same as Enumerator#with_index(0), i.e. there is no starting offset.
684 *
685 * If no block is given, a new Enumerator is returned that includes the index.
686 *
687 */
688static VALUE
689enumerator_each_with_index(VALUE obj)
690{
691 return enumerator_with_index(0, NULL, obj);
692}
693
694static VALUE
695enumerator_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memo))
696{
697 if (argc <= 1)
698 return rb_yield_values(2, val, memo);
699
700 return rb_yield_values(2, rb_ary_new4(argc, argv), memo);
701}
702
703/*
704 * call-seq:
705 * e.each_with_object(obj) {|(*args), obj| ... }
706 * e.each_with_object(obj)
707 * e.with_object(obj) {|(*args), obj| ... }
708 * e.with_object(obj)
709 *
710 * Iterates the given block for each element with an arbitrary object, +obj+,
711 * and returns +obj+
712 *
713 * If no block is given, returns a new Enumerator.
714 *
715 * === Example
716 *
717 * to_three = Enumerator.new do |y|
718 * 3.times do |x|
719 * y << x
720 * end
721 * end
722 *
723 * to_three_with_string = to_three.with_object("foo")
724 * to_three_with_string.each do |x,string|
725 * puts "#{string}: #{x}"
726 * end
727 *
728 * # => foo: 0
729 * # => foo: 1
730 * # => foo: 2
731 */
732static VALUE
733enumerator_with_object(VALUE obj, VALUE memo)
734{
735 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enumerator_enum_size);
736 enumerator_block_call(obj, enumerator_with_object_i, memo);
737
738 return memo;
739}
740
741static VALUE
742next_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, obj))
743{
744 struct enumerator *e = enumerator_ptr(obj);
745 VALUE feedvalue = Qnil;
746 VALUE args = rb_ary_new4(argc, argv);
747 rb_fiber_yield(1, &args);
748 if (!UNDEF_P(e->feedvalue)) {
749 feedvalue = e->feedvalue;
750 e->feedvalue = Qundef;
751 }
752 return feedvalue;
753}
754
755static VALUE
756next_i(RB_BLOCK_CALL_FUNC_ARGLIST(_, obj))
757{
758 struct enumerator *e = enumerator_ptr(obj);
759 VALUE nil = Qnil;
760 VALUE result;
761
762 result = rb_block_call(obj, id_each, 0, 0, next_ii, obj);
763 RB_OBJ_WRITE(obj, &e->stop_exc, rb_exc_new2(rb_eStopIteration, "iteration reached an end"));
764 rb_ivar_set(e->stop_exc, id_result, result);
765 return rb_fiber_yield(1, &nil);
766}
767
768static void
769next_init(VALUE obj, struct enumerator *e)
770{
771 VALUE curr = rb_fiber_current();
772 RB_OBJ_WRITE(obj, &e->dst, curr);
773 RB_OBJ_WRITE(obj, &e->fib, rb_fiber_new(next_i, obj));
774 e->lookahead = Qundef;
775}
776
777static VALUE
778get_next_values(VALUE obj, struct enumerator *e)
779{
780 VALUE curr, vs;
781
782 if (e->stop_exc) {
783 VALUE exc = e->stop_exc;
784 VALUE result = rb_attr_get(exc, id_result);
785 VALUE mesg = rb_attr_get(exc, idMesg);
786 if (!NIL_P(mesg)) mesg = rb_str_dup(mesg);
787 VALUE stop_exc = rb_exc_new_str(rb_eStopIteration, mesg);
788 rb_ivar_set(stop_exc, id_cause, exc);
789 rb_ivar_set(stop_exc, id_result, result);
790 rb_exc_raise(stop_exc);
791 }
792
793 curr = rb_fiber_current();
794
795 if (!e->fib || !rb_fiber_alive_p(e->fib)) {
796 next_init(obj, e);
797 }
798
799 vs = rb_fiber_resume(e->fib, 1, &curr);
800 if (e->stop_exc) {
801 e->fib = 0;
802 e->dst = Qnil;
803 e->lookahead = Qundef;
804 e->feedvalue = Qundef;
805 rb_exc_raise(e->stop_exc);
806 }
807 return vs;
808}
809
810/*
811 * call-seq:
812 * e.next_values -> array
813 *
814 * Returns the next object as an array in the enumerator, and move the
815 * internal position forward. When the position reached at the end,
816 * StopIteration is raised.
817 *
818 * See class-level notes about external iterators.
819 *
820 * This method can be used to distinguish <code>yield</code> and <code>yield
821 * nil</code>.
822 *
823 * === Example
824 *
825 * o = Object.new
826 * def o.each
827 * yield
828 * yield 1
829 * yield 1, 2
830 * yield nil
831 * yield [1, 2]
832 * end
833 * e = o.to_enum
834 * p e.next_values
835 * p e.next_values
836 * p e.next_values
837 * p e.next_values
838 * p e.next_values
839 * e = o.to_enum
840 * p e.next
841 * p e.next
842 * p e.next
843 * p e.next
844 * p e.next
845 *
846 * ## yield args next_values next
847 * # yield [] nil
848 * # yield 1 [1] 1
849 * # yield 1, 2 [1, 2] [1, 2]
850 * # yield nil [nil] nil
851 * # yield [1, 2] [[1, 2]] [1, 2]
852 *
853 */
854
855static VALUE
856enumerator_next_values(VALUE obj)
857{
858 struct enumerator *e = enumerator_ptr(obj);
859 VALUE vs;
860
861 rb_check_frozen(obj);
862
863 if (!UNDEF_P(e->lookahead)) {
864 vs = e->lookahead;
865 e->lookahead = Qundef;
866 return vs;
867 }
868
869 return get_next_values(obj, e);
870}
871
872static VALUE
873ary2sv(VALUE args, int dup)
874{
875 if (!RB_TYPE_P(args, T_ARRAY))
876 return args;
877
878 switch (RARRAY_LEN(args)) {
879 case 0:
880 return Qnil;
881
882 case 1:
883 return RARRAY_AREF(args, 0);
884
885 default:
886 if (dup)
887 return rb_ary_dup(args);
888 return args;
889 }
890}
891
892/*
893 * call-seq:
894 * e.next -> object
895 *
896 * Returns the next object in the enumerator, and move the internal position
897 * forward. When the position reached at the end, StopIteration is raised.
898 *
899 * === Example
900 *
901 * a = [1,2,3]
902 * e = a.to_enum
903 * p e.next #=> 1
904 * p e.next #=> 2
905 * p e.next #=> 3
906 * p e.next #raises StopIteration
907 *
908 * See class-level notes about external iterators.
909 *
910 */
911
912static VALUE
913enumerator_next(VALUE obj)
914{
915 VALUE vs = enumerator_next_values(obj);
916 return ary2sv(vs, 0);
917}
918
919static VALUE
920enumerator_peek_values(VALUE obj)
921{
922 struct enumerator *e = enumerator_ptr(obj);
923
924 rb_check_frozen(obj);
925
926 if (UNDEF_P(e->lookahead)) {
927 RB_OBJ_WRITE(obj, &e->lookahead, get_next_values(obj, e));
928 }
929
930 return e->lookahead;
931}
932
933/*
934 * call-seq:
935 * e.peek_values -> array
936 *
937 * Returns the next object as an array, similar to Enumerator#next_values, but
938 * doesn't move the internal position forward. If the position is already at
939 * the end, StopIteration is raised.
940 *
941 * See class-level notes about external iterators.
942 *
943 * === Example
944 *
945 * o = Object.new
946 * def o.each
947 * yield
948 * yield 1
949 * yield 1, 2
950 * end
951 * e = o.to_enum
952 * p e.peek_values #=> []
953 * e.next
954 * p e.peek_values #=> [1]
955 * p e.peek_values #=> [1]
956 * e.next
957 * p e.peek_values #=> [1, 2]
958 * e.next
959 * p e.peek_values # raises StopIteration
960 *
961 */
962
963static VALUE
964enumerator_peek_values_m(VALUE obj)
965{
966 return rb_ary_dup(enumerator_peek_values(obj));
967}
968
969/*
970 * call-seq:
971 * e.peek -> object
972 *
973 * Returns the next object in the enumerator, but doesn't move the internal
974 * position forward. If the position is already at the end, StopIteration
975 * is raised.
976 *
977 * See class-level notes about external iterators.
978 *
979 * === Example
980 *
981 * a = [1,2,3]
982 * e = a.to_enum
983 * p e.next #=> 1
984 * p e.peek #=> 2
985 * p e.peek #=> 2
986 * p e.peek #=> 2
987 * p e.next #=> 2
988 * p e.next #=> 3
989 * p e.peek #raises StopIteration
990 *
991 */
992
993static VALUE
994enumerator_peek(VALUE obj)
995{
996 VALUE vs = enumerator_peek_values(obj);
997 return ary2sv(vs, 1);
998}
999
1000/*
1001 * call-seq:
1002 * e.feed obj -> nil
1003 *
1004 * Sets the value to be returned by the next yield inside +e+.
1005 *
1006 * If the value is not set, the yield returns nil.
1007 *
1008 * This value is cleared after being yielded.
1009 *
1010 * # Array#map passes the array's elements to "yield" and collects the
1011 * # results of "yield" as an array.
1012 * # Following example shows that "next" returns the passed elements and
1013 * # values passed to "feed" are collected as an array which can be
1014 * # obtained by StopIteration#result.
1015 * e = [1,2,3].map
1016 * p e.next #=> 1
1017 * e.feed "a"
1018 * p e.next #=> 2
1019 * e.feed "b"
1020 * p e.next #=> 3
1021 * e.feed "c"
1022 * begin
1023 * e.next
1024 * rescue StopIteration
1025 * p $!.result #=> ["a", "b", "c"]
1026 * end
1027 *
1028 * o = Object.new
1029 * def o.each
1030 * x = yield # (2) blocks
1031 * p x # (5) => "foo"
1032 * x = yield # (6) blocks
1033 * p x # (8) => nil
1034 * x = yield # (9) blocks
1035 * p x # not reached w/o another e.next
1036 * end
1037 *
1038 * e = o.to_enum
1039 * e.next # (1)
1040 * e.feed "foo" # (3)
1041 * e.next # (4)
1042 * e.next # (7)
1043 * # (10)
1044 */
1045
1046static VALUE
1047enumerator_feed(VALUE obj, VALUE v)
1048{
1049 struct enumerator *e = enumerator_ptr(obj);
1050
1051 rb_check_frozen(obj);
1052
1053 if (!UNDEF_P(e->feedvalue)) {
1054 rb_raise(rb_eTypeError, "feed value already set");
1055 }
1056 RB_OBJ_WRITE(obj, &e->feedvalue, v);
1057
1058 return Qnil;
1059}
1060
1061/*
1062 * call-seq:
1063 * e.rewind -> e
1064 *
1065 * Rewinds the enumeration sequence to the beginning.
1066 *
1067 * If the enclosed object responds to a "rewind" method, it is called.
1068 */
1069
1070static VALUE
1071enumerator_rewind(VALUE obj)
1072{
1073 struct enumerator *e = enumerator_ptr(obj);
1074
1075 rb_check_frozen(obj);
1076
1077 rb_check_funcall(e->obj, id_rewind, 0, 0);
1078
1079 e->fib = 0;
1080 e->dst = Qnil;
1081 e->lookahead = Qundef;
1082 e->feedvalue = Qundef;
1083 e->stop_exc = Qfalse;
1084 return obj;
1085}
1086
1087static struct generator *generator_ptr(VALUE obj);
1088static VALUE append_method(VALUE obj, VALUE str, ID default_method, VALUE default_args);
1089
1090static VALUE
1091inspect_enumerator(VALUE obj, VALUE dummy, int recur)
1092{
1093 struct enumerator *e;
1094 VALUE eobj, str, cname;
1095
1096 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, e);
1097
1098 cname = rb_obj_class(obj);
1099
1100 if (!e || UNDEF_P(e->obj)) {
1101 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(cname));
1102 }
1103
1104 if (recur) {
1105 str = rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(cname));
1106 return str;
1107 }
1108
1109 if (e->procs) {
1110 long i;
1111
1112 eobj = generator_ptr(e->obj)->obj;
1113 /* In case procs chained enumerator traversing all proc entries manually */
1114 if (rb_obj_class(eobj) == cname) {
1115 str = rb_inspect(eobj);
1116 }
1117 else {
1118 str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(cname), eobj);
1119 }
1120 for (i = 0; i < RARRAY_LEN(e->procs); i++) {
1121 str = rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE, cname, str);
1122 append_method(RARRAY_AREF(e->procs, i), str, e->meth, e->args);
1123 rb_str_buf_cat2(str, ">");
1124 }
1125 return str;
1126 }
1127
1128 eobj = rb_attr_get(obj, id_receiver);
1129 if (NIL_P(eobj)) {
1130 eobj = e->obj;
1131 }
1132
1133 /* (1..100).each_cons(2) => "#<Enumerator: 1..100:each_cons(2)>" */
1134 str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE, rb_class_path(cname), eobj);
1135 append_method(obj, str, e->meth, e->args);
1136
1137 rb_str_buf_cat2(str, ">");
1138
1139 return str;
1140}
1141
1142static int
1143key_symbol_p(VALUE key, VALUE val, VALUE arg)
1144{
1145 if (SYMBOL_P(key)) return ST_CONTINUE;
1146 *(int *)arg = FALSE;
1147 return ST_STOP;
1148}
1149
1150static int
1151kwd_append(VALUE key, VALUE val, VALUE str)
1152{
1153 if (!SYMBOL_P(key)) rb_raise(rb_eRuntimeError, "non-symbol key inserted");
1154 rb_str_catf(str, "% "PRIsVALUE": %"PRIsVALUE", ", key, val);
1155 return ST_CONTINUE;
1156}
1157
1158static VALUE
1159append_method(VALUE obj, VALUE str, ID default_method, VALUE default_args)
1160{
1161 VALUE method, eargs;
1162
1163 method = rb_attr_get(obj, id_method);
1164 if (method != Qfalse) {
1165 if (!NIL_P(method)) {
1166 Check_Type(method, T_SYMBOL);
1167 method = rb_sym2str(method);
1168 }
1169 else {
1170 method = rb_id2str(default_method);
1171 }
1172 rb_str_buf_cat2(str, ":");
1173 rb_str_buf_append(str, method);
1174 }
1175
1176 eargs = rb_attr_get(obj, id_arguments);
1177 if (NIL_P(eargs)) {
1178 eargs = default_args;
1179 }
1180 if (eargs != Qfalse) {
1181 long argc = RARRAY_LEN(eargs);
1182 const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */
1183
1184 if (argc > 0) {
1185 VALUE kwds = Qnil;
1186
1187 rb_str_buf_cat2(str, "(");
1188
1189 if (RB_TYPE_P(argv[argc-1], T_HASH) && !RHASH_EMPTY_P(argv[argc-1])) {
1190 int all_key = TRUE;
1191 rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key);
1192 if (all_key) kwds = argv[--argc];
1193 }
1194
1195 while (argc--) {
1196 VALUE arg = *argv++;
1197
1198 rb_str_append(str, rb_inspect(arg));
1199 rb_str_buf_cat2(str, ", ");
1200 }
1201 if (!NIL_P(kwds)) {
1202 rb_hash_foreach(kwds, kwd_append, str);
1203 }
1204 rb_str_set_len(str, RSTRING_LEN(str)-2);
1205 rb_str_buf_cat2(str, ")");
1206 }
1207 }
1208
1209 return str;
1210}
1211
1212/*
1213 * call-seq:
1214 * e.inspect -> string
1215 *
1216 * Creates a printable version of <i>e</i>.
1217 */
1218
1219static VALUE
1220enumerator_inspect(VALUE obj)
1221{
1222 return rb_exec_recursive(inspect_enumerator, obj, 0);
1223}
1224
1225/*
1226 * call-seq:
1227 * e.size -> int, Float::INFINITY or nil
1228 *
1229 * Returns the size of the enumerator, or +nil+ if it can't be calculated lazily.
1230 *
1231 * (1..100).to_a.permutation(4).size # => 94109400
1232 * loop.size # => Float::INFINITY
1233 * (1..100).drop_while.size # => nil
1234 *
1235 * Note that enumerator size might be inaccurate, and should be rather treated as a hint.
1236 * For example, there is no check that the size provided to ::new is accurate:
1237 *
1238 * e = Enumerator.new(5) { |y| 2.times { y << it} }
1239 * e.size # => 5
1240 * e.to_a.size # => 2
1241 *
1242 * Another example is an enumerator created by ::produce without a +size+ argument.
1243 * Such enumerators return +Infinity+ for size, but this is inaccurate if the passed
1244 * block raises StopIteration:
1245 *
1246 * e = Enumerator.produce(1) { it + 1 }
1247 * e.size # => Infinity
1248 *
1249 * e = Enumerator.produce(1) { it > 3 ? raise(StopIteration) : it + 1 }
1250 * e.size # => Infinity
1251 * e.to_a.size # => 4
1252 */
1253
1254static VALUE
1255enumerator_size(VALUE obj)
1256{
1257 struct enumerator *e = enumerator_ptr(obj);
1258 int argc = 0;
1259 const VALUE *argv = NULL;
1260 VALUE size;
1261
1262 if (e->procs) {
1263 struct generator *g = generator_ptr(e->obj);
1264 VALUE receiver = rb_check_funcall(g->obj, id_size, 0, 0);
1265 long i = 0;
1266
1267 for (i = 0; i < RARRAY_LEN(e->procs); i++) {
1268 VALUE proc = RARRAY_AREF(e->procs, i);
1269 struct proc_entry *entry = proc_entry_ptr(proc);
1270 lazyenum_size_func *size_fn = entry->fn->size;
1271 if (!size_fn) {
1272 return Qnil;
1273 }
1274 receiver = (*size_fn)(proc, receiver);
1275 }
1276 return receiver;
1277 }
1278
1279 if (e->size_fn) {
1280 return (*e->size_fn)(e->obj, e->args, obj);
1281 }
1282 if (e->args) {
1283 argc = (int)RARRAY_LEN(e->args);
1284 argv = RARRAY_CONST_PTR(e->args);
1285 }
1286 size = rb_check_funcall_kw(e->size, id_call, argc, argv, e->kw_splat);
1287 if (!UNDEF_P(size)) return size;
1288 return e->size;
1289}
1290
1291/*
1292 * Yielder
1293 */
1294static void
1295yielder_mark_and_move(void *p)
1296{
1297 struct yielder *ptr = p;
1298 rb_gc_mark_and_move(&ptr->proc);
1299}
1300
1301static const rb_data_type_t yielder_data_type = {
1302 "yielder",
1303 {
1304 yielder_mark_and_move,
1306 NULL,
1307 yielder_mark_and_move,
1308 },
1309 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1310};
1311
1312static struct yielder *
1313yielder_ptr(VALUE obj)
1314{
1315 struct yielder *ptr;
1316
1317 TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
1318 if (!ptr || UNDEF_P(ptr->proc)) {
1319 rb_raise(rb_eArgError, "uninitialized yielder");
1320 }
1321 return ptr;
1322}
1323
1324/* :nodoc: */
1325static VALUE
1326yielder_allocate(VALUE klass)
1327{
1328 struct yielder *ptr;
1329 VALUE obj;
1330
1331 obj = TypedData_Make_Struct(klass, struct yielder, &yielder_data_type, ptr);
1332 ptr->proc = Qundef;
1333
1334 return obj;
1335}
1336
1337static VALUE
1338yielder_init(VALUE obj, VALUE proc)
1339{
1340 struct yielder *ptr;
1341
1342 TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
1343
1344 if (!ptr) {
1345 rb_raise(rb_eArgError, "unallocated yielder");
1346 }
1347
1348 RB_OBJ_WRITE(obj, &ptr->proc, proc);
1349
1350 return obj;
1351}
1352
1353/* :nodoc: */
1354static VALUE
1355yielder_initialize(VALUE obj)
1356{
1357 rb_need_block();
1358
1359 return yielder_init(obj, rb_block_proc());
1360}
1361
1362/* :nodoc: */
1363static VALUE
1364yielder_yield(VALUE obj, VALUE args)
1365{
1366 struct yielder *ptr = yielder_ptr(obj);
1367
1368 return rb_proc_call_kw(ptr->proc, args, RB_PASS_CALLED_KEYWORDS);
1369}
1370
1371/* :nodoc: */
1372static VALUE
1373yielder_yield_push(VALUE obj, VALUE arg)
1374{
1375 struct yielder *ptr = yielder_ptr(obj);
1376
1377 rb_proc_call_with_block(ptr->proc, 1, &arg, Qnil);
1378
1379 return obj;
1380}
1381
1382/*
1383 * Returns a Proc object that takes arguments and yields them.
1384 *
1385 * This method is implemented so that a Yielder object can be directly
1386 * passed to another method as a block argument.
1387 *
1388 * enum = Enumerator.new { |y|
1389 * Dir.glob("*.rb") { |file|
1390 * File.open(file) { |f| f.each_line(&y) }
1391 * }
1392 * }
1393 */
1394static VALUE
1395yielder_to_proc(VALUE obj)
1396{
1397 VALUE method = rb_obj_method(obj, sym_yield);
1398
1399 return rb_funcall(method, idTo_proc, 0);
1400}
1401
1402static VALUE
1403yielder_yield_i(RB_BLOCK_CALL_FUNC_ARGLIST(obj, memo))
1404{
1405 return rb_yield_values_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
1406}
1407
1408static VALUE
1409yielder_new(void)
1410{
1411 return yielder_init(yielder_allocate(rb_cYielder), rb_proc_new(yielder_yield_i, 0));
1412}
1413
1414/*
1415 * Generator
1416 */
1417static void
1418generator_mark_and_move(void *p)
1419{
1420 struct generator *ptr = p;
1421 rb_gc_mark_and_move(&ptr->proc);
1422 rb_gc_mark_and_move(&ptr->obj);
1423}
1424
1425static const rb_data_type_t generator_data_type = {
1426 "generator",
1427 {
1428 generator_mark_and_move,
1430 NULL,
1431 generator_mark_and_move,
1432 },
1433 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1434};
1435
1436static struct generator *
1437generator_ptr(VALUE obj)
1438{
1439 struct generator *ptr;
1440
1441 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
1442 if (!ptr || UNDEF_P(ptr->proc)) {
1443 rb_raise(rb_eArgError, "uninitialized generator");
1444 }
1445 return ptr;
1446}
1447
1448/* :nodoc: */
1449static VALUE
1450generator_allocate(VALUE klass)
1451{
1452 struct generator *ptr;
1453 VALUE obj;
1454
1455 obj = TypedData_Make_Struct(klass, struct generator, &generator_data_type, ptr);
1456 ptr->proc = Qundef;
1457
1458 return obj;
1459}
1460
1461static VALUE
1462generator_init(VALUE obj, VALUE proc)
1463{
1464 struct generator *ptr;
1465
1466 rb_check_frozen(obj);
1467 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
1468
1469 if (!ptr) {
1470 rb_raise(rb_eArgError, "unallocated generator");
1471 }
1472
1473 RB_OBJ_WRITE(obj, &ptr->proc, proc);
1474
1475 return obj;
1476}
1477
1478/* :nodoc: */
1479static VALUE
1480generator_initialize(int argc, VALUE *argv, VALUE obj)
1481{
1482 VALUE proc;
1483
1484 if (argc == 0) {
1485 rb_need_block();
1486
1487 proc = rb_block_proc();
1488 }
1489 else {
1490 rb_scan_args(argc, argv, "1", &proc);
1491
1492 if (!rb_obj_is_proc(proc))
1493 rb_raise(rb_eTypeError,
1494 "wrong argument type %"PRIsVALUE" (expected Proc)",
1495 rb_obj_class(proc));
1496
1497 if (rb_block_given_p()) {
1498 rb_warn("given block not used");
1499 }
1500 }
1501
1502 return generator_init(obj, proc);
1503}
1504
1505/* :nodoc: */
1506static VALUE
1507generator_init_copy(VALUE obj, VALUE orig)
1508{
1509 struct generator *ptr0, *ptr1;
1510
1511 if (!OBJ_INIT_COPY(obj, orig)) return obj;
1512
1513 ptr0 = generator_ptr(orig);
1514
1515 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr1);
1516
1517 if (!ptr1) {
1518 rb_raise(rb_eArgError, "unallocated generator");
1519 }
1520
1521 RB_OBJ_WRITE(obj, &ptr1->proc, ptr0->proc);
1522
1523 return obj;
1524}
1525
1526/* :nodoc: */
1527static VALUE
1528generator_each(int argc, VALUE *argv, VALUE obj)
1529{
1530 struct generator *ptr = generator_ptr(obj);
1531 VALUE args = rb_ary_new2(argc + 1);
1532
1533 rb_ary_push(args, yielder_new());
1534 if (argc > 0) {
1535 rb_ary_cat(args, argv, argc);
1536 }
1537
1538 return rb_proc_call_kw(ptr->proc, args, RB_PASS_CALLED_KEYWORDS);
1539}
1540
1541/* Lazy Enumerator methods */
1542static VALUE
1543enum_size(VALUE self)
1544{
1545 VALUE r = rb_check_funcall(self, id_size, 0, 0);
1546 return UNDEF_P(r) ? Qnil : r;
1547}
1548
1549static VALUE
1550lazyenum_size(VALUE self, VALUE args, VALUE eobj)
1551{
1552 return enum_size(self);
1553}
1554
1555#define lazy_receiver_size lazy_map_size
1556
1557static VALUE
1558lazy_init_iterator(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1559{
1560 VALUE result;
1561 if (argc == 1) {
1562 VALUE args[2];
1563 args[0] = m;
1564 args[1] = val;
1565 result = rb_yield_values2(2, args);
1566 }
1567 else {
1568 VALUE args;
1569 int len = rb_long2int((long)argc + 1);
1570 VALUE *nargv = ALLOCV_N(VALUE, args, len);
1571
1572 nargv[0] = m;
1573 if (argc > 0) {
1574 MEMCPY(nargv + 1, argv, VALUE, argc);
1575 }
1576 result = rb_yield_values2(len, nargv);
1577 ALLOCV_END(args);
1578 }
1579 if (UNDEF_P(result)) rb_iter_break();
1580 return Qnil;
1581}
1582
1583static VALUE
1584lazy_init_block_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1585{
1586 rb_block_call(m, id_each, argc-1, argv+1, lazy_init_iterator, val);
1587 return Qnil;
1588}
1589
1590#define memo_value v2
1591#define memo_flags u3.state
1592#define LAZY_MEMO_BREAK 1
1593#define LAZY_MEMO_PACKED 2
1594#define LAZY_MEMO_BREAK_P(memo) ((memo)->memo_flags & LAZY_MEMO_BREAK)
1595#define LAZY_MEMO_PACKED_P(memo) ((memo)->memo_flags & LAZY_MEMO_PACKED)
1596#define LAZY_MEMO_SET_BREAK(memo) ((memo)->memo_flags |= LAZY_MEMO_BREAK)
1597#define LAZY_MEMO_RESET_BREAK(memo) ((memo)->memo_flags &= ~LAZY_MEMO_BREAK)
1598#define LAZY_MEMO_SET_VALUE(memo, value) MEMO_V2_SET(memo, value)
1599#define LAZY_MEMO_SET_PACKED(memo) ((memo)->memo_flags |= LAZY_MEMO_PACKED)
1600#define LAZY_MEMO_RESET_PACKED(memo) ((memo)->memo_flags &= ~LAZY_MEMO_PACKED)
1601
1602#define LAZY_NEED_BLOCK(func) \
1603 if (!rb_block_given_p()) { \
1604 rb_raise(rb_eArgError, "tried to call lazy " #func " without a block"); \
1605 }
1606
1607static VALUE lazy_yielder_result(struct MEMO *result, VALUE yielder, VALUE procs_array, VALUE memos, long i);
1608
1609static VALUE
1610lazy_init_yielder(RB_BLOCK_CALL_FUNC_ARGLIST(_, m))
1611{
1612 VALUE yielder = RARRAY_AREF(m, 0);
1613 VALUE procs_array = RARRAY_AREF(m, 1);
1614 VALUE memos = rb_attr_get(yielder, id_memo);
1615 struct MEMO *result;
1616
1617 result = MEMO_NEW(m, rb_enum_values_pack(argc, argv),
1618 argc > 1 ? LAZY_MEMO_PACKED : 0);
1619 return lazy_yielder_result(result, yielder, procs_array, memos, 0);
1620}
1621
1622static VALUE
1623lazy_yielder_yield(struct MEMO *result, long memo_index, int argc, const VALUE *argv)
1624{
1625 VALUE m = result->v1;
1626 VALUE yielder = RARRAY_AREF(m, 0);
1627 VALUE procs_array = RARRAY_AREF(m, 1);
1628 VALUE memos = rb_attr_get(yielder, id_memo);
1629 LAZY_MEMO_SET_VALUE(result, rb_enum_values_pack(argc, argv));
1630 if (argc > 1)
1631 LAZY_MEMO_SET_PACKED(result);
1632 else
1633 LAZY_MEMO_RESET_PACKED(result);
1634 return lazy_yielder_result(result, yielder, procs_array, memos, memo_index);
1635}
1636
1637static VALUE
1638lazy_yielder_result(struct MEMO *result, VALUE yielder, VALUE procs_array, VALUE memos, long i)
1639{
1640 int cont = 1;
1641
1642 for (; i < RARRAY_LEN(procs_array); i++) {
1643 VALUE proc = RARRAY_AREF(procs_array, i);
1644 struct proc_entry *entry = proc_entry_ptr(proc);
1645 if (!(*entry->fn->proc)(proc, result, memos, i)) {
1646 cont = 0;
1647 break;
1648 }
1649 }
1650
1651 if (cont) {
1652 rb_funcall2(yielder, idLTLT, 1, &(result->memo_value));
1653 }
1654 if (LAZY_MEMO_BREAK_P(result)) {
1655 rb_iter_break();
1656 }
1657 return result->memo_value;
1658}
1659
1660static VALUE
1661lazy_init_block(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1662{
1663 VALUE procs = RARRAY_AREF(m, 1);
1664
1665 rb_ivar_set(val, id_memo, rb_ary_new2(RARRAY_LEN(procs)));
1666 rb_block_call(RARRAY_AREF(m, 0), id_each, 0, 0,
1667 lazy_init_yielder, rb_ary_new3(2, val, procs));
1668 return Qnil;
1669}
1670
1671static VALUE
1672lazy_generator_init(VALUE enumerator, VALUE procs)
1673{
1675 VALUE obj;
1676 struct generator *gen_ptr;
1677 struct enumerator *e = enumerator_ptr(enumerator);
1678
1679 if (RARRAY_LEN(procs) > 0) {
1680 struct generator *old_gen_ptr = generator_ptr(e->obj);
1681 obj = old_gen_ptr->obj;
1682 }
1683 else {
1684 obj = enumerator;
1685 }
1686
1687 generator = generator_allocate(rb_cGenerator);
1688
1689 rb_block_call(generator, id_initialize, 0, 0,
1690 lazy_init_block, rb_ary_new3(2, obj, procs));
1691
1692 gen_ptr = generator_ptr(generator);
1693 RB_OBJ_WRITE(generator, &gen_ptr->obj, obj);
1694
1695 return generator;
1696}
1697
1698static int
1699lazy_precheck(VALUE procs)
1700{
1701 if (RTEST(procs)) {
1702 long num_procs = RARRAY_LEN(procs), i = num_procs;
1703 while (i-- > 0) {
1704 VALUE proc = RARRAY_AREF(procs, i);
1705 struct proc_entry *entry = proc_entry_ptr(proc);
1706 lazyenum_precheck_func *precheck = entry->fn->precheck;
1707 if (precheck && !precheck(proc)) return FALSE;
1708 }
1709 }
1710
1711 return TRUE;
1712}
1713
1714/*
1715 * Document-class: Enumerator::Lazy
1716 *
1717 * Enumerator::Lazy is a special type of Enumerator, that allows constructing
1718 * chains of operations without evaluating them immediately, and evaluating
1719 * values on as-needed basis. In order to do so it redefines most of Enumerable
1720 * methods so that they just construct another lazy enumerator.
1721 *
1722 * Enumerator::Lazy can be constructed from any Enumerable with the
1723 * Enumerable#lazy method.
1724 *
1725 * lazy = (1..Float::INFINITY).lazy.select(&:odd?).drop(10).take_while { |i| i < 30 }
1726 * # => #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:select>:drop(10)>:take_while>
1727 *
1728 * The real enumeration is performed when any non-redefined Enumerable method
1729 * is called, like Enumerable#first or Enumerable#to_a (the latter is aliased
1730 * as #force for more semantic code):
1731 *
1732 * lazy.first(2)
1733 * #=> [21, 23]
1734 *
1735 * lazy.force
1736 * #=> [21, 23, 25, 27, 29]
1737 *
1738 * Note that most Enumerable methods that could be called with or without
1739 * a block, on Enumerator::Lazy will always require a block:
1740 *
1741 * [1, 2, 3].map #=> #<Enumerator: [1, 2, 3]:map>
1742 * [1, 2, 3].lazy.map # ArgumentError: tried to call lazy map without a block
1743 *
1744 * This class allows idiomatic calculations on long or infinite sequences, as well
1745 * as chaining of calculations without constructing intermediate arrays.
1746 *
1747 * Example for working with a slowly calculated sequence:
1748 *
1749 * require 'open-uri'
1750 *
1751 * # This will fetch all URLs before selecting
1752 * # necessary data
1753 * URLS.map { |u| JSON.parse(URI.open(u).read) }
1754 * .select { |data| data.key?('stats') }
1755 * .first(5)
1756 *
1757 * # This will fetch URLs one-by-one, only till
1758 * # there is enough data to satisfy the condition
1759 * URLS.lazy.map { |u| JSON.parse(URI.open(u).read) }
1760 * .select { |data| data.key?('stats') }
1761 * .first(5)
1762 *
1763 * Ending a chain with ".eager" generates a non-lazy enumerator, which
1764 * is suitable for returning or passing to another method that expects
1765 * a normal enumerator.
1766 *
1767 * def active_items
1768 * groups
1769 * .lazy
1770 * .flat_map(&:items)
1771 * .reject(&:disabled)
1772 * .eager
1773 * end
1774 *
1775 * # This works lazily; if a checked item is found, it stops
1776 * # iteration and does not look into remaining groups.
1777 * first_checked = active_items.find(&:checked)
1778 *
1779 * # This returns an array of items like a normal enumerator does.
1780 * all_checked = active_items.select(&:checked)
1781 *
1782 */
1783
1784/*
1785 * call-seq:
1786 * Lazy.new(obj, size=nil) { |yielder, *values| block }
1787 *
1788 * Creates a new Lazy enumerator. When the enumerator is actually enumerated
1789 * (e.g. by calling #force), +obj+ will be enumerated and each value passed
1790 * to the given block. The block can yield values back using +yielder+.
1791 * For example, to create a "filter+map" enumerator:
1792 *
1793 * def filter_map(sequence)
1794 * Lazy.new(sequence) do |yielder, *values|
1795 * result = yield *values
1796 * yielder << result if result
1797 * end
1798 * end
1799 *
1800 * filter_map(1..Float::INFINITY) {|i| i*i if i.even?}.first(5)
1801 * #=> [4, 16, 36, 64, 100]
1802 */
1803static VALUE
1804lazy_initialize(int argc, VALUE *argv, VALUE self)
1805{
1806 VALUE obj, size = Qnil;
1808
1809 rb_check_arity(argc, 1, 2);
1810 LAZY_NEED_BLOCK(new);
1811 obj = argv[0];
1812 if (argc > 1) {
1813 size = argv[1];
1814 }
1815 generator = generator_allocate(rb_cGenerator);
1816 rb_block_call(generator, id_initialize, 0, 0, lazy_init_block_i, obj);
1817 enumerator_init(self, generator, sym_each, 0, 0, 0, size, 0);
1818 rb_ivar_set(self, id_receiver, obj);
1819
1820 return self;
1821}
1822
1823#if 0 /* for RDoc */
1824/*
1825 * call-seq:
1826 * lazy.to_a -> array
1827 * lazy.force -> array
1828 *
1829 * Expands +lazy+ enumerator to an array.
1830 * See Enumerable#to_a.
1831 */
1832static VALUE
1833lazy_to_a(VALUE self)
1834{
1835}
1836#endif
1837
1838static void
1839lazy_set_args(VALUE lazy, VALUE args)
1840{
1841 ID id = rb_frame_this_func();
1842 rb_ivar_set(lazy, id_method, ID2SYM(id));
1843 if (NIL_P(args)) {
1844 /* Qfalse indicates that the arguments are empty */
1845 rb_ivar_set(lazy, id_arguments, Qfalse);
1846 }
1847 else {
1848 rb_ivar_set(lazy, id_arguments, args);
1849 }
1850}
1851
1852#if 0
1853static VALUE
1854lazy_set_method(VALUE lazy, VALUE args, rb_enumerator_size_func *size_fn)
1855{
1856 struct enumerator *e = enumerator_ptr(lazy);
1857 lazy_set_args(lazy, args);
1858 e->size_fn = size_fn;
1859 return lazy;
1860}
1861#endif
1862
1863static VALUE
1864lazy_add_method(VALUE obj, int argc, VALUE *argv, VALUE args, VALUE memo,
1865 const lazyenum_funcs *fn)
1866{
1867 struct enumerator *new_e;
1868 VALUE new_obj;
1869 VALUE new_generator;
1870 VALUE new_procs;
1871 struct enumerator *e = enumerator_ptr(obj);
1872 struct proc_entry *entry;
1873 VALUE entry_obj = TypedData_Make_Struct(rb_cObject, struct proc_entry,
1874 &proc_entry_data_type, entry);
1875 if (rb_block_given_p()) {
1876 RB_OBJ_WRITE(entry_obj, &entry->proc, rb_block_proc());
1877 }
1878 entry->fn = fn;
1879 RB_OBJ_WRITE(entry_obj, &entry->memo, args);
1880
1881 lazy_set_args(entry_obj, memo);
1882
1883 new_procs = RTEST(e->procs) ? rb_ary_dup(e->procs) : rb_ary_new();
1884 new_generator = lazy_generator_init(obj, new_procs);
1885 rb_ary_push(new_procs, entry_obj);
1886
1887 new_obj = enumerator_init_copy(enumerator_allocate(rb_cLazy), obj);
1888 new_e = RTYPEDDATA_GET_DATA(new_obj);
1889 RB_OBJ_WRITE(new_obj, &new_e->obj, new_generator);
1890 RB_OBJ_WRITE(new_obj, &new_e->procs, new_procs);
1891
1892 if (argc > 0) {
1893 new_e->meth = rb_to_id(*argv++);
1894 --argc;
1895 }
1896 else {
1897 new_e->meth = id_each;
1898 }
1899
1900 RB_OBJ_WRITE(new_obj, &new_e->args, rb_ary_new4(argc, argv));
1901
1902 return new_obj;
1903}
1904
1905/*
1906 * call-seq:
1907 * e.lazy -> lazy_enumerator
1908 *
1909 * Returns an Enumerator::Lazy, which redefines most Enumerable
1910 * methods to postpone enumeration and enumerate values only on an
1911 * as-needed basis.
1912 *
1913 * === Example
1914 *
1915 * The following program finds pythagorean triples:
1916 *
1917 * def pythagorean_triples
1918 * (1..Float::INFINITY).lazy.flat_map {|z|
1919 * (1..z).flat_map {|x|
1920 * (x..z).select {|y|
1921 * x**2 + y**2 == z**2
1922 * }.map {|y|
1923 * [x, y, z]
1924 * }
1925 * }
1926 * }
1927 * end
1928 * # show first ten pythagorean triples
1929 * p pythagorean_triples.take(10).force # take is lazy, so force is needed
1930 * p pythagorean_triples.first(10) # first is eager
1931 * # show pythagorean triples less than 100
1932 * p pythagorean_triples.take_while { |*, z| z < 100 }.force
1933 */
1934static VALUE
1935enumerable_lazy(VALUE obj)
1936{
1937 VALUE result = lazy_to_enum_i(obj, sym_each, 0, 0, lazyenum_size, rb_keyword_given_p());
1938 /* Qfalse indicates that the Enumerator::Lazy has no method name */
1939 rb_ivar_set(result, id_method, Qfalse);
1940 return result;
1941}
1942
1943static VALUE
1944lazy_to_enum_i(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat)
1945{
1946 return enumerator_init(enumerator_allocate(rb_cLazy),
1947 obj, meth, argc, argv, size_fn, Qnil, kw_splat);
1948}
1949
1950/*
1951 * call-seq:
1952 * lzy.to_enum(method = :each, *args) -> lazy_enum
1953 * lzy.enum_for(method = :each, *args) -> lazy_enum
1954 * lzy.to_enum(method = :each, *args) {|*args| block } -> lazy_enum
1955 * lzy.enum_for(method = :each, *args) {|*args| block } -> lazy_enum
1956 *
1957 * Similar to Object#to_enum, except it returns a lazy enumerator.
1958 * This makes it easy to define Enumerable methods that will
1959 * naturally remain lazy if called from a lazy enumerator.
1960 *
1961 * For example, continuing from the example in Object#to_enum:
1962 *
1963 * # See Object#to_enum for the definition of repeat
1964 * r = 1..Float::INFINITY
1965 * r.repeat(2).first(5) # => [1, 1, 2, 2, 3]
1966 * r.repeat(2).class # => Enumerator
1967 * r.repeat(2).map{|n| n ** 2}.first(5) # => endless loop!
1968 * # works naturally on lazy enumerator:
1969 * r.lazy.repeat(2).class # => Enumerator::Lazy
1970 * r.lazy.repeat(2).map{|n| n ** 2}.first(5) # => [1, 1, 4, 4, 9]
1971 */
1972
1973static VALUE
1974lazy_to_enum(int argc, VALUE *argv, VALUE self)
1975{
1976 VALUE lazy, meth = sym_each, super_meth;
1977
1978 if (argc > 0) {
1979 --argc;
1980 meth = rb_to_symbol(*argv++);
1981 }
1982 if (RTEST((super_meth = rb_hash_aref(lazy_use_super_method, meth)))) {
1983 meth = super_meth;
1984 }
1985 lazy = lazy_to_enum_i(self, meth, argc, argv, 0, rb_keyword_given_p());
1986 if (rb_block_given_p()) {
1987 RB_OBJ_WRITE(lazy, &enumerator_ptr(lazy)->size, rb_block_proc());
1988 }
1989 return lazy;
1990}
1991
1992static VALUE
1993lazy_eager_size(VALUE self, VALUE args, VALUE eobj)
1994{
1995 return enum_size(self);
1996}
1997
1998/*
1999 * call-seq:
2000 * lzy.eager -> enum
2001 *
2002 * Returns a non-lazy Enumerator converted from the lazy enumerator.
2003 */
2004
2005static VALUE
2006lazy_eager(VALUE self)
2007{
2008 return enumerator_init(enumerator_allocate(rb_cEnumerator),
2009 self, sym_each, 0, 0, lazy_eager_size, Qnil, 0);
2010}
2011
2012static VALUE
2013lazyenum_yield(VALUE proc_entry, struct MEMO *result)
2014{
2015 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2016 return rb_proc_call_with_block(entry->proc, 1, &result->memo_value, Qnil);
2017}
2018
2019static VALUE
2020lazyenum_yield_values(VALUE proc_entry, struct MEMO *result)
2021{
2022 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2023 int argc = 1;
2024 const VALUE *argv = &result->memo_value;
2025 if (LAZY_MEMO_PACKED_P(result)) {
2026 const VALUE args = *argv;
2027 argc = RARRAY_LENINT(args);
2028 argv = RARRAY_CONST_PTR(args);
2029 }
2030 return rb_proc_call_with_block(entry->proc, argc, argv, Qnil);
2031}
2032
2033static struct MEMO *
2034lazy_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2035{
2036 VALUE value = lazyenum_yield_values(proc_entry, result);
2037 LAZY_MEMO_SET_VALUE(result, value);
2038 LAZY_MEMO_RESET_PACKED(result);
2039 return result;
2040}
2041
2042static VALUE
2043lazy_map_size(VALUE entry, VALUE receiver)
2044{
2045 return receiver;
2046}
2047
2048static const lazyenum_funcs lazy_map_funcs = {
2049 lazy_map_proc, lazy_map_size,
2050};
2051
2052/*
2053 * call-seq:
2054 * lazy.collect { |obj| block } -> lazy_enumerator
2055 * lazy.map { |obj| block } -> lazy_enumerator
2056 *
2057 * Like Enumerable#map, but chains operation to be lazy-evaluated.
2058 *
2059 * (1..Float::INFINITY).lazy.map {|i| i**2 }
2060 * #=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:map>
2061 * (1..Float::INFINITY).lazy.map {|i| i**2 }.first(3)
2062 * #=> [1, 4, 9]
2063 */
2064
2065static VALUE
2066lazy_map(VALUE obj)
2067{
2068 LAZY_NEED_BLOCK(map);
2069 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_map_funcs);
2070}
2071
2072static VALUE
2073lazy_flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, y))
2074{
2075 struct MEMO *arg = MEMO_CAST(y);
2076
2077 return lazy_yielder_yield(MEMO_CAST(arg->v1), arg->u3.cnt, argc, argv);
2078}
2079
2080static struct MEMO *
2081lazy_flat_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2082{
2083 VALUE value = lazyenum_yield_values(proc_entry, result);
2084 VALUE ary = 0;
2085 const long proc_index = memo_index + 1;
2086 int break_p = LAZY_MEMO_BREAK_P(result);
2087
2088 if (RB_TYPE_P(value, T_ARRAY)) {
2089 ary = value;
2090 }
2091 else if (rb_respond_to(value, id_force) && rb_respond_to(value, id_each)) {
2092 VALUE arg = (VALUE)MEMO_NEW((VALUE)result, Qnil, proc_index);
2093 LAZY_MEMO_RESET_BREAK(result);
2094 rb_block_call(value, id_each, 0, 0, lazy_flat_map_i, arg);
2095 if (break_p) LAZY_MEMO_SET_BREAK(result);
2096 RB_GC_GUARD(arg);
2097 return 0;
2098 }
2099
2100 if (ary || !NIL_P(ary = rb_check_array_type(value))) {
2101 long i;
2102 LAZY_MEMO_RESET_BREAK(result);
2103 for (i = 0; i + 1 < RARRAY_LEN(ary); i++) {
2104 const VALUE argv = RARRAY_AREF(ary, i);
2105 lazy_yielder_yield(result, proc_index, 1, &argv);
2106 }
2107 if (break_p) LAZY_MEMO_SET_BREAK(result);
2108 if (i >= RARRAY_LEN(ary)) return 0;
2109 value = RARRAY_AREF(ary, i);
2110 }
2111 LAZY_MEMO_SET_VALUE(result, value);
2112 LAZY_MEMO_RESET_PACKED(result);
2113 return result;
2114}
2115
2116static const lazyenum_funcs lazy_flat_map_funcs = {
2117 lazy_flat_map_proc, 0,
2118};
2119
2120/*
2121 * call-seq:
2122 * lazy.collect_concat { |obj| block } -> a_lazy_enumerator
2123 * lazy.flat_map { |obj| block } -> a_lazy_enumerator
2124 *
2125 * Returns a new lazy enumerator with the concatenated results of running
2126 * +block+ once for every element in the lazy enumerator.
2127 *
2128 * ["foo", "bar"].lazy.flat_map {|i| i.each_char.lazy}.force
2129 * #=> ["f", "o", "o", "b", "a", "r"]
2130 *
2131 * A value +x+ returned by +block+ is decomposed if either of
2132 * the following conditions is true:
2133 *
2134 * * +x+ responds to both each and force, which means that
2135 * +x+ is a lazy enumerator.
2136 * * +x+ is an array or responds to to_ary.
2137 *
2138 * Otherwise, +x+ is contained as-is in the return value.
2139 *
2140 * [{a:1}, {b:2}].lazy.flat_map {|i| i}.force
2141 * #=> [{:a=>1}, {:b=>2}]
2142 */
2143static VALUE
2144lazy_flat_map(VALUE obj)
2145{
2146 LAZY_NEED_BLOCK(flat_map);
2147 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_flat_map_funcs);
2148}
2149
2150static struct MEMO *
2151lazy_select_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2152{
2153 VALUE chain = lazyenum_yield(proc_entry, result);
2154 if (!RTEST(chain)) return 0;
2155 return result;
2156}
2157
2158static const lazyenum_funcs lazy_select_funcs = {
2159 lazy_select_proc, 0,
2160};
2161
2162/*
2163 * call-seq:
2164 * lazy.find_all { |obj| block } -> lazy_enumerator
2165 * lazy.select { |obj| block } -> lazy_enumerator
2166 * lazy.filter { |obj| block } -> lazy_enumerator
2167 *
2168 * Like Enumerable#select, but chains operation to be lazy-evaluated.
2169 */
2170static VALUE
2171lazy_select(VALUE obj)
2172{
2173 LAZY_NEED_BLOCK(select);
2174 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_select_funcs);
2175}
2176
2177static struct MEMO *
2178lazy_filter_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2179{
2180 VALUE value = lazyenum_yield_values(proc_entry, result);
2181 if (!RTEST(value)) return 0;
2182 LAZY_MEMO_SET_VALUE(result, value);
2183 LAZY_MEMO_RESET_PACKED(result);
2184 return result;
2185}
2186
2187static const lazyenum_funcs lazy_filter_map_funcs = {
2188 lazy_filter_map_proc, 0,
2189};
2190
2191/*
2192 * call-seq:
2193 * lazy.filter_map { |obj| block } -> lazy_enumerator
2194 *
2195 * Like Enumerable#filter_map, but chains operation to be lazy-evaluated.
2196 *
2197 * (1..).lazy.filter_map { |i| i * 2 if i.even? }.first(5)
2198 * #=> [4, 8, 12, 16, 20]
2199 */
2200
2201static VALUE
2202lazy_filter_map(VALUE obj)
2203{
2204 LAZY_NEED_BLOCK(filter_map);
2205 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_filter_map_funcs);
2206}
2207
2208static struct MEMO *
2209lazy_reject_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2210{
2211 VALUE chain = lazyenum_yield(proc_entry, result);
2212 if (RTEST(chain)) return 0;
2213 return result;
2214}
2215
2216static const lazyenum_funcs lazy_reject_funcs = {
2217 lazy_reject_proc, 0,
2218};
2219
2220/*
2221 * call-seq:
2222 * lazy.reject { |obj| block } -> lazy_enumerator
2223 *
2224 * Like Enumerable#reject, but chains operation to be lazy-evaluated.
2225 */
2226
2227static VALUE
2228lazy_reject(VALUE obj)
2229{
2230 LAZY_NEED_BLOCK(reject);
2231 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_reject_funcs);
2232}
2233
2234static struct MEMO *
2235lazy_grep_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2236{
2237 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2238 VALUE chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2239 if (!RTEST(chain)) return 0;
2240 return result;
2241}
2242
2243static struct MEMO *
2244lazy_grep_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2245{
2246 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2247 VALUE value, chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2248
2249 if (!RTEST(chain)) return 0;
2250 value = rb_proc_call_with_block(entry->proc, 1, &(result->memo_value), Qnil);
2251 LAZY_MEMO_SET_VALUE(result, value);
2252 LAZY_MEMO_RESET_PACKED(result);
2253
2254 return result;
2255}
2256
2257static const lazyenum_funcs lazy_grep_iter_funcs = {
2258 lazy_grep_iter_proc, 0,
2259};
2260
2261static const lazyenum_funcs lazy_grep_funcs = {
2262 lazy_grep_proc, 0,
2263};
2264
2265/*
2266 * call-seq:
2267 * lazy.grep(pattern) -> lazy_enumerator
2268 * lazy.grep(pattern) { |obj| block } -> lazy_enumerator
2269 *
2270 * Like Enumerable#grep, but chains operation to be lazy-evaluated.
2271 */
2272
2273static VALUE
2274lazy_grep(VALUE obj, VALUE pattern)
2275{
2276 const lazyenum_funcs *const funcs = rb_block_given_p() ?
2277 &lazy_grep_iter_funcs : &lazy_grep_funcs;
2278 return lazy_add_method(obj, 0, 0, pattern, rb_ary_new3(1, pattern), funcs);
2279}
2280
2281static struct MEMO *
2282lazy_grep_v_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2283{
2284 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2285 VALUE chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2286 if (RTEST(chain)) return 0;
2287 return result;
2288}
2289
2290static struct MEMO *
2291lazy_grep_v_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2292{
2293 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2294 VALUE value, chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2295
2296 if (RTEST(chain)) return 0;
2297 value = rb_proc_call_with_block(entry->proc, 1, &(result->memo_value), Qnil);
2298 LAZY_MEMO_SET_VALUE(result, value);
2299 LAZY_MEMO_RESET_PACKED(result);
2300
2301 return result;
2302}
2303
2304static const lazyenum_funcs lazy_grep_v_iter_funcs = {
2305 lazy_grep_v_iter_proc, 0,
2306};
2307
2308static const lazyenum_funcs lazy_grep_v_funcs = {
2309 lazy_grep_v_proc, 0,
2310};
2311
2312/*
2313 * call-seq:
2314 * lazy.grep_v(pattern) -> lazy_enumerator
2315 * lazy.grep_v(pattern) { |obj| block } -> lazy_enumerator
2316 *
2317 * Like Enumerable#grep_v, but chains operation to be lazy-evaluated.
2318 */
2319
2320static VALUE
2321lazy_grep_v(VALUE obj, VALUE pattern)
2322{
2323 const lazyenum_funcs *const funcs = rb_block_given_p() ?
2324 &lazy_grep_v_iter_funcs : &lazy_grep_v_funcs;
2325 return lazy_add_method(obj, 0, 0, pattern, rb_ary_new3(1, pattern), funcs);
2326}
2327
2328static VALUE
2329call_next(VALUE obj)
2330{
2331 return rb_funcall(obj, id_next, 0);
2332}
2333
2334static VALUE
2335next_stopped(VALUE obj, VALUE _)
2336{
2337 return Qnil;
2338}
2339
2340static struct MEMO *
2341lazy_zip_arrays_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2342{
2343 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2344 VALUE ary, arrays = entry->memo;
2345 VALUE memo = rb_ary_entry(memos, memo_index);
2346 long i, count = NIL_P(memo) ? 0 : NUM2LONG(memo);
2347
2348 ary = rb_ary_new2(RARRAY_LEN(arrays) + 1);
2349 rb_ary_push(ary, result->memo_value);
2350 for (i = 0; i < RARRAY_LEN(arrays); i++) {
2351 rb_ary_push(ary, rb_ary_entry(RARRAY_AREF(arrays, i), count));
2352 }
2353 LAZY_MEMO_SET_VALUE(result, ary);
2354 rb_ary_store(memos, memo_index, LONG2NUM(++count));
2355 return result;
2356}
2357
2358static struct MEMO *
2359lazy_zip_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2360{
2361 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2362 VALUE arg = rb_ary_entry(memos, memo_index);
2363 VALUE zip_args = entry->memo;
2364 VALUE ary, v;
2365 long i;
2366
2367 if (NIL_P(arg)) {
2368 arg = rb_ary_new2(RARRAY_LEN(zip_args));
2369 for (i = 0; i < RARRAY_LEN(zip_args); i++) {
2370 rb_ary_push(arg, rb_funcall(RARRAY_AREF(zip_args, i), id_to_enum, 0));
2371 }
2372 rb_ary_store(memos, memo_index, arg);
2373 }
2374
2375 ary = rb_ary_new2(RARRAY_LEN(arg) + 1);
2376 rb_ary_push(ary, result->memo_value);
2377 for (i = 0; i < RARRAY_LEN(arg); i++) {
2378 v = rb_rescue2(call_next, RARRAY_AREF(arg, i), next_stopped, 0,
2380 rb_ary_push(ary, v);
2381 }
2382 LAZY_MEMO_SET_VALUE(result, ary);
2383 return result;
2384}
2385
2386static const lazyenum_funcs lazy_zip_funcs[] = {
2387 {lazy_zip_func, lazy_receiver_size,},
2388 {lazy_zip_arrays_func, lazy_receiver_size,},
2389};
2390
2391/*
2392 * call-seq:
2393 * lazy.zip(arg, ...) -> lazy_enumerator
2394 * lazy.zip(arg, ...) { |arr| block } -> nil
2395 *
2396 * Like Enumerable#zip, but chains operation to be lazy-evaluated.
2397 * However, if a block is given to zip, values are enumerated immediately.
2398 */
2399static VALUE
2400lazy_zip(int argc, VALUE *argv, VALUE obj)
2401{
2402 VALUE ary, v;
2403 long i;
2404 const lazyenum_funcs *funcs = &lazy_zip_funcs[1];
2405
2406 if (rb_block_given_p()) {
2407 return rb_call_super(argc, argv);
2408 }
2409
2410 ary = rb_ary_new2(argc);
2411 for (i = 0; i < argc; i++) {
2412 v = rb_check_array_type(argv[i]);
2413 if (NIL_P(v)) {
2414 for (; i < argc; i++) {
2415 if (!rb_respond_to(argv[i], id_each)) {
2416 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
2417 rb_obj_class(argv[i]));
2418 }
2419 }
2420 ary = rb_ary_new4(argc, argv);
2421 funcs = &lazy_zip_funcs[0];
2422 break;
2423 }
2424 rb_ary_push(ary, v);
2425 }
2426
2427 return lazy_add_method(obj, 0, 0, ary, ary, funcs);
2428}
2429
2430static struct MEMO *
2431lazy_take_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2432{
2433 long remain;
2434 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2435 VALUE memo = rb_ary_entry(memos, memo_index);
2436
2437 if (NIL_P(memo)) {
2438 memo = entry->memo;
2439 }
2440
2441 remain = NUM2LONG(memo);
2442 if (--remain == 0) LAZY_MEMO_SET_BREAK(result);
2443 rb_ary_store(memos, memo_index, LONG2NUM(remain));
2444 return result;
2445}
2446
2447static VALUE
2448lazy_take_size(VALUE entry, VALUE receiver)
2449{
2450 long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(entry, id_arguments), 0));
2451 if (NIL_P(receiver) || (FIXNUM_P(receiver) && FIX2LONG(receiver) < len))
2452 return receiver;
2453 return LONG2NUM(len);
2454}
2455
2456static int
2457lazy_take_precheck(VALUE proc_entry)
2458{
2459 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2460 return entry->memo != INT2FIX(0);
2461}
2462
2463static const lazyenum_funcs lazy_take_funcs = {
2464 lazy_take_proc, lazy_take_size, lazy_take_precheck,
2465};
2466
2467/*
2468 * call-seq:
2469 * lazy.take(n) -> lazy_enumerator
2470 *
2471 * Like Enumerable#take, but chains operation to be lazy-evaluated.
2472 */
2473
2474static VALUE
2475lazy_take(VALUE obj, VALUE n)
2476{
2477 long len = NUM2LONG(n);
2478
2479 if (len < 0) {
2480 rb_raise(rb_eArgError, "attempt to take negative size");
2481 }
2482
2483 n = LONG2NUM(len); /* no more conversion */
2484
2485 return lazy_add_method(obj, 0, 0, n, rb_ary_new3(1, n), &lazy_take_funcs);
2486}
2487
2488static struct MEMO *
2489lazy_take_while_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2490{
2491 VALUE take = lazyenum_yield_values(proc_entry, result);
2492 if (!RTEST(take)) {
2493 LAZY_MEMO_SET_BREAK(result);
2494 return 0;
2495 }
2496 return result;
2497}
2498
2499static const lazyenum_funcs lazy_take_while_funcs = {
2500 lazy_take_while_proc, 0,
2501};
2502
2503/*
2504 * call-seq:
2505 * lazy.take_while { |obj| block } -> lazy_enumerator
2506 *
2507 * Like Enumerable#take_while, but chains operation to be lazy-evaluated.
2508 */
2509
2510static VALUE
2511lazy_take_while(VALUE obj)
2512{
2513 LAZY_NEED_BLOCK(take_while);
2514 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_take_while_funcs);
2515}
2516
2517static VALUE
2518lazy_drop_size(VALUE proc_entry, VALUE receiver)
2519{
2520 long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(proc_entry, id_arguments), 0));
2521 if (NIL_P(receiver))
2522 return receiver;
2523 if (FIXNUM_P(receiver)) {
2524 len = FIX2LONG(receiver) - len;
2525 return LONG2FIX(len < 0 ? 0 : len);
2526 }
2527 return rb_funcall(receiver, '-', 1, LONG2NUM(len));
2528}
2529
2530static struct MEMO *
2531lazy_drop_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2532{
2533 long remain;
2534 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2535 VALUE memo = rb_ary_entry(memos, memo_index);
2536
2537 if (NIL_P(memo)) {
2538 memo = entry->memo;
2539 }
2540 remain = NUM2LONG(memo);
2541 if (remain > 0) {
2542 --remain;
2543 rb_ary_store(memos, memo_index, LONG2NUM(remain));
2544 return 0;
2545 }
2546
2547 return result;
2548}
2549
2550static const lazyenum_funcs lazy_drop_funcs = {
2551 lazy_drop_proc, lazy_drop_size,
2552};
2553
2554/*
2555 * call-seq:
2556 * lazy.drop(n) -> lazy_enumerator
2557 *
2558 * Like Enumerable#drop, but chains operation to be lazy-evaluated.
2559 */
2560
2561static VALUE
2562lazy_drop(VALUE obj, VALUE n)
2563{
2564 long len = NUM2LONG(n);
2565 VALUE argv[2];
2566 argv[0] = sym_each;
2567 argv[1] = n;
2568
2569 if (len < 0) {
2570 rb_raise(rb_eArgError, "attempt to drop negative size");
2571 }
2572
2573 return lazy_add_method(obj, 2, argv, n, rb_ary_new3(1, n), &lazy_drop_funcs);
2574}
2575
2576static struct MEMO *
2577lazy_drop_while_proc(VALUE proc_entry, struct MEMO* result, VALUE memos, long memo_index)
2578{
2579 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2580 VALUE memo = rb_ary_entry(memos, memo_index);
2581
2582 if (NIL_P(memo)) {
2583 memo = entry->memo;
2584 }
2585
2586 if (!RTEST(memo)) {
2587 VALUE drop = lazyenum_yield_values(proc_entry, result);
2588 if (RTEST(drop)) return 0;
2589 rb_ary_store(memos, memo_index, Qtrue);
2590 }
2591 return result;
2592}
2593
2594static const lazyenum_funcs lazy_drop_while_funcs = {
2595 lazy_drop_while_proc, 0,
2596};
2597
2598/*
2599 * call-seq:
2600 * lazy.drop_while { |obj| block } -> lazy_enumerator
2601 *
2602 * Like Enumerable#drop_while, but chains operation to be lazy-evaluated.
2603 */
2604
2605static VALUE
2606lazy_drop_while(VALUE obj)
2607{
2608 LAZY_NEED_BLOCK(drop_while);
2609 return lazy_add_method(obj, 0, 0, Qfalse, Qnil, &lazy_drop_while_funcs);
2610}
2611
2612static int
2613lazy_uniq_check(VALUE chain, VALUE memos, long memo_index)
2614{
2615 VALUE hash = rb_ary_entry(memos, memo_index);
2616
2617 if (NIL_P(hash)) {
2618 hash = rb_obj_hide(rb_hash_new());
2619 rb_ary_store(memos, memo_index, hash);
2620 }
2621
2622 return rb_hash_add_new_element(hash, chain, Qfalse);
2623}
2624
2625static struct MEMO *
2626lazy_uniq_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2627{
2628 if (lazy_uniq_check(result->memo_value, memos, memo_index)) return 0;
2629 return result;
2630}
2631
2632static struct MEMO *
2633lazy_uniq_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2634{
2635 VALUE chain = lazyenum_yield(proc_entry, result);
2636
2637 if (lazy_uniq_check(chain, memos, memo_index)) return 0;
2638 return result;
2639}
2640
2641static const lazyenum_funcs lazy_uniq_iter_funcs = {
2642 lazy_uniq_iter_proc, 0,
2643};
2644
2645static const lazyenum_funcs lazy_uniq_funcs = {
2646 lazy_uniq_proc, 0,
2647};
2648
2649/*
2650 * call-seq:
2651 * lazy.uniq -> lazy_enumerator
2652 * lazy.uniq { |item| block } -> lazy_enumerator
2653 *
2654 * Like Enumerable#uniq, but chains operation to be lazy-evaluated.
2655 */
2656
2657static VALUE
2658lazy_uniq(VALUE obj)
2659{
2660 const lazyenum_funcs *const funcs =
2661 rb_block_given_p() ? &lazy_uniq_iter_funcs : &lazy_uniq_funcs;
2662 return lazy_add_method(obj, 0, 0, Qnil, Qnil, funcs);
2663}
2664
2665static struct MEMO *
2666lazy_compact_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2667{
2668 if (NIL_P(result->memo_value)) return 0;
2669 return result;
2670}
2671
2672static const lazyenum_funcs lazy_compact_funcs = {
2673 lazy_compact_proc, 0,
2674};
2675
2676/*
2677 * call-seq:
2678 * lazy.compact -> lazy_enumerator
2679 *
2680 * Like Enumerable#compact, but chains operation to be lazy-evaluated.
2681 */
2682
2683static VALUE
2684lazy_compact(VALUE obj)
2685{
2686 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_compact_funcs);
2687}
2688
2689static struct MEMO *
2690lazy_with_index_proc(VALUE proc_entry, struct MEMO* result, VALUE memos, long memo_index)
2691{
2692 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2693 VALUE memo = rb_ary_entry(memos, memo_index);
2694 VALUE argv[2];
2695
2696 if (NIL_P(memo)) {
2697 memo = entry->memo;
2698 }
2699
2700 argv[0] = result->memo_value;
2701 argv[1] = memo;
2702 if (entry->proc) {
2703 rb_proc_call_with_block(entry->proc, 2, argv, Qnil);
2704 LAZY_MEMO_RESET_PACKED(result);
2705 }
2706 else {
2707 LAZY_MEMO_SET_VALUE(result, rb_ary_new_from_values(2, argv));
2708 LAZY_MEMO_SET_PACKED(result);
2709 }
2710 rb_ary_store(memos, memo_index, LONG2NUM(NUM2LONG(memo) + 1));
2711 return result;
2712}
2713
2714static VALUE
2715lazy_with_index_size(VALUE proc, VALUE receiver)
2716{
2717 return receiver;
2718}
2719
2720static const lazyenum_funcs lazy_with_index_funcs = {
2721 lazy_with_index_proc, lazy_with_index_size,
2722};
2723
2724/*
2725 * call-seq:
2726 * lazy.with_index(offset = 0) {|(*args), idx| block }
2727 * lazy.with_index(offset = 0)
2728 *
2729 * If a block is given, returns a lazy enumerator that will
2730 * iterate over the given block for each element
2731 * with an index, which starts from +offset+, and returns a
2732 * lazy enumerator that yields the same values (without the index).
2733 *
2734 * If a block is not given, returns a new lazy enumerator that
2735 * includes the index, starting from +offset+.
2736 *
2737 * +offset+:: the starting index to use
2738 *
2739 * See Enumerator#with_index.
2740 */
2741static VALUE
2742lazy_with_index(int argc, VALUE *argv, VALUE obj)
2743{
2744 VALUE memo;
2745
2746 rb_scan_args(argc, argv, "01", &memo);
2747 if (NIL_P(memo))
2748 memo = LONG2NUM(0);
2749
2750 return lazy_add_method(obj, 0, 0, memo, rb_ary_new_from_values(1, &memo), &lazy_with_index_funcs);
2751}
2752
2753#if 0 /* for RDoc */
2754
2755/*
2756 * call-seq:
2757 * lazy.chunk { |elt| ... } -> lazy_enumerator
2758 *
2759 * Like Enumerable#chunk, but chains operation to be lazy-evaluated.
2760 */
2761static VALUE
2762lazy_chunk(VALUE self)
2763{
2764}
2765
2766/*
2767 * call-seq:
2768 * lazy.chunk_while {|elt_before, elt_after| bool } -> lazy_enumerator
2769 *
2770 * Like Enumerable#chunk_while, but chains operation to be lazy-evaluated.
2771 */
2772static VALUE
2773lazy_chunk_while(VALUE self)
2774{
2775}
2776
2777/*
2778 * call-seq:
2779 * lazy.slice_after(pattern) -> lazy_enumerator
2780 * lazy.slice_after { |elt| bool } -> lazy_enumerator
2781 *
2782 * Like Enumerable#slice_after, but chains operation to be lazy-evaluated.
2783 */
2784static VALUE
2785lazy_slice_after(VALUE self)
2786{
2787}
2788
2789/*
2790 * call-seq:
2791 * lazy.slice_before(pattern) -> lazy_enumerator
2792 * lazy.slice_before { |elt| bool } -> lazy_enumerator
2793 *
2794 * Like Enumerable#slice_before, but chains operation to be lazy-evaluated.
2795 */
2796static VALUE
2797lazy_slice_before(VALUE self)
2798{
2799}
2800
2801/*
2802 * call-seq:
2803 * lazy.slice_when {|elt_before, elt_after| bool } -> lazy_enumerator
2804 *
2805 * Like Enumerable#slice_when, but chains operation to be lazy-evaluated.
2806 */
2807static VALUE
2808lazy_slice_when(VALUE self)
2809{
2810}
2811# endif
2812
2813static VALUE
2814lazy_super(int argc, VALUE *argv, VALUE lazy)
2815{
2816 return enumerable_lazy(rb_call_super(argc, argv));
2817}
2818
2819/*
2820 * call-seq:
2821 * enum.lazy -> lazy_enumerator
2822 *
2823 * Returns self.
2824 */
2825
2826static VALUE
2827lazy_lazy(VALUE obj)
2828{
2829 return obj;
2830}
2831
2832/*
2833 * Document-class: StopIteration
2834 *
2835 * Raised to stop the iteration, in particular by Enumerator#next. It is
2836 * rescued by Kernel#loop.
2837 *
2838 * loop do
2839 * puts "Hello"
2840 * raise StopIteration
2841 * puts "World"
2842 * end
2843 * puts "Done!"
2844 *
2845 * <em>produces:</em>
2846 *
2847 * Hello
2848 * Done!
2849 */
2850
2851/*
2852 * call-seq:
2853 * result -> value
2854 *
2855 * Returns the return value of the iterator.
2856 *
2857 * o = Object.new
2858 * def o.each
2859 * yield 1
2860 * yield 2
2861 * yield 3
2862 * 100
2863 * end
2864 *
2865 * e = o.to_enum
2866 *
2867 * puts e.next #=> 1
2868 * puts e.next #=> 2
2869 * puts e.next #=> 3
2870 *
2871 * begin
2872 * e.next
2873 * rescue StopIteration => ex
2874 * puts ex.result #=> 100
2875 * end
2876 *
2877 */
2878
2879static VALUE
2880stop_result(VALUE self)
2881{
2882 return rb_attr_get(self, id_result);
2883}
2884
2885/*
2886 * Producer
2887 */
2888
2889static void
2890producer_mark_and_move(void *p)
2891{
2892 struct producer *ptr = p;
2893 rb_gc_mark_and_move(&ptr->init);
2894 rb_gc_mark_and_move(&ptr->proc);
2895 rb_gc_mark_and_move(&ptr->size);
2896}
2897
2898#define producer_free RUBY_TYPED_DEFAULT_FREE
2899
2900static size_t
2901producer_memsize(const void *p)
2902{
2903 return sizeof(struct producer);
2904}
2905
2906static const rb_data_type_t producer_data_type = {
2907 "producer",
2908 {
2909 producer_mark_and_move,
2910 producer_free,
2911 producer_memsize,
2912 producer_mark_and_move,
2913 },
2914 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
2915};
2916
2917static struct producer *
2918producer_ptr(VALUE obj)
2919{
2920 struct producer *ptr;
2921
2922 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
2923 if (!ptr || UNDEF_P(ptr->proc)) {
2924 rb_raise(rb_eArgError, "uninitialized producer");
2925 }
2926 return ptr;
2927}
2928
2929/* :nodoc: */
2930static VALUE
2931producer_allocate(VALUE klass)
2932{
2933 struct producer *ptr;
2934 VALUE obj;
2935
2936 obj = TypedData_Make_Struct(klass, struct producer, &producer_data_type, ptr);
2937 ptr->init = Qundef;
2938 ptr->proc = Qundef;
2939 ptr->size = Qnil;
2940
2941 return obj;
2942}
2943
2944static VALUE
2945producer_init(VALUE obj, VALUE init, VALUE proc, VALUE size)
2946{
2947 struct producer *ptr;
2948
2949 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
2950
2951 if (!ptr) {
2952 rb_raise(rb_eArgError, "unallocated producer");
2953 }
2954
2955 RB_OBJ_WRITE(obj, &ptr->init, init);
2956 RB_OBJ_WRITE(obj, &ptr->proc, proc);
2957 RB_OBJ_WRITE(obj, &ptr->size, size);
2958
2959 return obj;
2960}
2961
2962static VALUE
2963producer_each_stop(VALUE dummy, VALUE exc)
2964{
2965 return rb_attr_get(exc, id_result);
2966}
2967
2968NORETURN(static VALUE producer_each_i(VALUE obj));
2969
2970static VALUE
2971producer_each_i(VALUE obj)
2972{
2973 struct producer *ptr;
2974 VALUE init, proc, curr;
2975
2976 ptr = producer_ptr(obj);
2977 init = ptr->init;
2978 proc = ptr->proc;
2979
2980 if (UNDEF_P(init)) {
2981 curr = Qnil;
2982 }
2983 else {
2984 rb_yield(init);
2985 curr = init;
2986 }
2987
2988 for (;;) {
2989 curr = rb_funcall(proc, id_call, 1, curr);
2990 rb_yield(curr);
2991 }
2992
2994}
2995
2996/* :nodoc: */
2997static VALUE
2998producer_each(VALUE obj)
2999{
3000 rb_need_block();
3001
3002 return rb_rescue2(producer_each_i, obj, producer_each_stop, (VALUE)0, rb_eStopIteration, (VALUE)0);
3003}
3004
3005static VALUE
3006producer_size(VALUE obj, VALUE args, VALUE eobj)
3007{
3008 struct producer *ptr = producer_ptr(obj);
3009 VALUE size = ptr->size;
3010
3011 if (NIL_P(size)) return Qnil;
3012 if (RB_INTEGER_TYPE_P(size) || RB_FLOAT_TYPE_P(size)) return size;
3013
3014 return rb_funcall(size, id_call, 0);
3015}
3016
3017/*
3018 * call-seq:
3019 * Enumerator.produce(initial = nil, size: nil) { |prev| block } -> enumerator
3020 *
3021 * Creates an infinite enumerator from any block, just called over and
3022 * over. The result of the previous iteration is passed to the next one.
3023 * If +initial+ is provided, it is passed to the first iteration, and
3024 * becomes the first element of the enumerator; if it is not provided,
3025 * the first iteration receives +nil+, and its result becomes the first
3026 * element of the iterator.
3027 *
3028 * Raising StopIteration from the block stops an iteration.
3029 *
3030 * Enumerator.produce(1, &:succ) # => enumerator of 1, 2, 3, 4, ....
3031 *
3032 * Enumerator.produce { rand(10) } # => infinite random number sequence
3033 *
3034 * ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
3035 * enclosing_section = ancestors.find { |n| n.type == :section }
3036 *
3037 * Using ::produce together with Enumerable methods like Enumerable#detect,
3038 * Enumerable#slice_after, Enumerable#take_while can provide Enumerator-based alternatives
3039 * for +while+ and +until+ cycles:
3040 *
3041 * # Find next Tuesday
3042 * require "date"
3043 * Enumerator.produce(Date.today, &:succ).detect(&:tuesday?)
3044 *
3045 * # Simple lexer:
3046 * require "strscan"
3047 * scanner = StringScanner.new("7+38/6")
3048 * PATTERN = %r{\d+|[-/+*]}
3049 * Enumerator.produce { scanner.scan(PATTERN) }.slice_after { scanner.eos? }.first
3050 * # => ["7", "+", "38", "/", "6"]
3051 *
3052 * The optional +size+ keyword argument specifies the size of the enumerator,
3053 * which can be retrieved by Enumerator#size. It can be an integer,
3054 * +Float::INFINITY+, a callable object (such as a lambda), or +nil+ to
3055 * indicate unknown size. When not specified, the size defaults to
3056 * +Float::INFINITY+.
3057 *
3058 * # Infinite enumerator
3059 * enum = Enumerator.produce(1, size: Float::INFINITY, &:succ)
3060 * enum.size # => Float::INFINITY
3061 *
3062 * # Finite enumerator with known/computable size
3063 * abs_dir = File.expand_path("./baz") # => "/foo/bar/baz"
3064 * traverser = Enumerator.produce(abs_dir, size: -> { abs_dir.count("/") + 1 }) {
3065 * raise StopIteration if it == "/"
3066 * File.dirname(it)
3067 * }
3068 * traverser.size # => 4
3069 *
3070 * # Finite enumerator with unknown size
3071 * calendar = Enumerator.produce(Date.today, size: nil) {
3072 * it.monday? ? raise(StopIteration) : it + 1
3073 * }
3074 * calendar.size # => nil
3075 */
3076static VALUE
3077enumerator_s_produce(int argc, VALUE *argv, VALUE klass)
3078{
3079 VALUE init, producer, opts, size;
3080 ID keyword_ids[1];
3081
3082 if (!rb_block_given_p()) rb_raise(rb_eArgError, "no block given");
3083
3084 keyword_ids[0] = rb_intern("size");
3085 rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "01:", &init, &opts);
3086 rb_get_kwargs(opts, keyword_ids, 0, 1, &size);
3087
3088 size = UNDEF_P(size) ? DBL2NUM(HUGE_VAL) : convert_to_feasible_size_value(size);
3089
3090 if (argc == 0 || (argc == 1 && !NIL_P(opts))) {
3091 init = Qundef;
3092 }
3093
3094 producer = producer_init(producer_allocate(rb_cEnumProducer), init, rb_block_proc(), size);
3095
3096 return rb_enumeratorize_with_size_kw(producer, sym_each, 0, 0, producer_size, RB_NO_KEYWORDS);
3097}
3098
3099/*
3100 * Document-class: Enumerator::Chain
3101 *
3102 * Enumerator::Chain is a subclass of Enumerator, which represents a
3103 * chain of enumerables that works as a single enumerator.
3104 *
3105 * This type of objects can be created by Enumerable#chain and
3106 * Enumerator#+.
3107 */
3108
3109static void
3110enum_chain_mark_and_move(void *p)
3111{
3112 struct enum_chain *ptr = p;
3113 rb_gc_mark_and_move(&ptr->enums);
3114}
3115
3116#define enum_chain_free RUBY_TYPED_DEFAULT_FREE
3117
3118static size_t
3119enum_chain_memsize(const void *p)
3120{
3121 return sizeof(struct enum_chain);
3122}
3123
3124static const rb_data_type_t enum_chain_data_type = {
3125 "chain",
3126 {
3127 enum_chain_mark_and_move,
3128 enum_chain_free,
3129 enum_chain_memsize,
3130 enum_chain_mark_and_move,
3131 },
3132 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
3133};
3134
3135static struct enum_chain *
3136enum_chain_ptr(VALUE obj)
3137{
3138 struct enum_chain *ptr;
3139
3140 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3141 if (!ptr || UNDEF_P(ptr->enums)) {
3142 rb_raise(rb_eArgError, "uninitialized chain");
3143 }
3144 return ptr;
3145}
3146
3147/* :nodoc: */
3148static VALUE
3149enum_chain_allocate(VALUE klass)
3150{
3151 struct enum_chain *ptr;
3152 VALUE obj;
3153
3154 obj = TypedData_Make_Struct(klass, struct enum_chain, &enum_chain_data_type, ptr);
3155 ptr->enums = Qundef;
3156 ptr->pos = -1;
3157
3158 return obj;
3159}
3160
3161/*
3162 * call-seq:
3163 * Enumerator::Chain.new(*enums) -> enum
3164 *
3165 * Generates a new enumerator object that iterates over the elements
3166 * of given enumerable objects in sequence.
3167 *
3168 * e = Enumerator::Chain.new(1..3, [4, 5])
3169 * e.to_a #=> [1, 2, 3, 4, 5]
3170 * e.size #=> 5
3171 */
3172static VALUE
3173enum_chain_initialize(VALUE obj, VALUE enums)
3174{
3175 struct enum_chain *ptr;
3176
3177 rb_check_frozen(obj);
3178 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3179
3180 if (!ptr) rb_raise(rb_eArgError, "unallocated chain");
3181
3182 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3183 ptr->pos = -1;
3184
3185 return obj;
3186}
3187
3188static VALUE
3189new_enum_chain(VALUE enums)
3190{
3191 long i;
3192 VALUE obj = enum_chain_initialize(enum_chain_allocate(rb_cEnumChain), enums);
3193
3194 for (i = 0; i < RARRAY_LEN(enums); i++) {
3195 if (RTEST(rb_obj_is_kind_of(RARRAY_AREF(enums, i), rb_cLazy))) {
3196 return enumerable_lazy(obj);
3197 }
3198 }
3199
3200 return obj;
3201}
3202
3203/* :nodoc: */
3204static VALUE
3205enum_chain_init_copy(VALUE obj, VALUE orig)
3206{
3207 struct enum_chain *ptr0, *ptr1;
3208
3209 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3210 ptr0 = enum_chain_ptr(orig);
3211
3212 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr1);
3213
3214 if (!ptr1) rb_raise(rb_eArgError, "unallocated chain");
3215
3216 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3217 ptr1->pos = ptr0->pos;
3218
3219 return obj;
3220}
3221
3222static VALUE
3223enum_chain_total_size(VALUE enums)
3224{
3225 VALUE total = INT2FIX(0);
3226 long i;
3227
3228 for (i = 0; i < RARRAY_LEN(enums); i++) {
3229 VALUE size = enum_size(RARRAY_AREF(enums, i));
3230
3231 if (NIL_P(size) || (RB_FLOAT_TYPE_P(size) && isinf(NUM2DBL(size)))) {
3232 return size;
3233 }
3234 if (!RB_INTEGER_TYPE_P(size)) {
3235 return Qnil;
3236 }
3237
3238 total = rb_funcall(total, '+', 1, size);
3239 }
3240
3241 return total;
3242}
3243
3244/*
3245 * call-seq:
3246 * obj.size -> int, Float::INFINITY or nil
3247 *
3248 * Returns the total size of the enumerator chain calculated by
3249 * summing up the size of each enumerable in the chain. If any of the
3250 * enumerables reports its size as nil or Float::INFINITY, that value
3251 * is returned as the total size.
3252 */
3253static VALUE
3254enum_chain_size(VALUE obj)
3255{
3256 return enum_chain_total_size(enum_chain_ptr(obj)->enums);
3257}
3258
3259static VALUE
3260enum_chain_enum_size(VALUE obj, VALUE args, VALUE eobj)
3261{
3262 return enum_chain_size(obj);
3263}
3264
3265static VALUE
3266enum_chain_enum_no_size(VALUE obj, VALUE args, VALUE eobj)
3267{
3268 return Qnil;
3269}
3270
3271/*
3272 * call-seq:
3273 * obj.each(*args) { |...| ... } -> obj
3274 * obj.each(*args) -> enumerator
3275 *
3276 * Iterates over the elements of the first enumerable by calling the
3277 * "each" method on it with the given arguments, then proceeds to the
3278 * following enumerables in sequence until all of the enumerables are
3279 * exhausted.
3280 *
3281 * If no block is given, returns an enumerator.
3282 */
3283static VALUE
3284enum_chain_each(int argc, VALUE *argv, VALUE obj)
3285{
3286 VALUE enums, block;
3287 struct enum_chain *objptr;
3288 long i;
3289
3290 RETURN_SIZED_ENUMERATOR(obj, argc, argv, argc > 0 ? enum_chain_enum_no_size : enum_chain_enum_size);
3291
3292 objptr = enum_chain_ptr(obj);
3293 enums = objptr->enums;
3294 block = rb_block_proc();
3295
3296 for (i = 0; i < RARRAY_LEN(enums); i++) {
3297 objptr->pos = i;
3298 rb_funcall_with_block(RARRAY_AREF(enums, i), id_each, argc, argv, block);
3299 }
3300
3301 return obj;
3302}
3303
3304/*
3305 * call-seq:
3306 * obj.rewind -> obj
3307 *
3308 * Rewinds the enumerator chain by calling the "rewind" method on each
3309 * enumerable in reverse order. Each call is performed only if the
3310 * enumerable responds to the method.
3311 */
3312static VALUE
3313enum_chain_rewind(VALUE obj)
3314{
3315 struct enum_chain *objptr = enum_chain_ptr(obj);
3316 VALUE enums = objptr->enums;
3317 long i;
3318
3319 for (i = objptr->pos; 0 <= i && i < RARRAY_LEN(enums); objptr->pos = --i) {
3320 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3321 }
3322
3323 return obj;
3324}
3325
3326static VALUE
3327inspect_enum_chain(VALUE obj, VALUE dummy, int recur)
3328{
3329 VALUE klass = rb_obj_class(obj);
3330 struct enum_chain *ptr;
3331
3332 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3333
3334 if (!ptr || UNDEF_P(ptr->enums)) {
3335 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3336 }
3337
3338 if (recur) {
3339 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3340 }
3341
3342 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3343}
3344
3345/*
3346 * call-seq:
3347 * obj.inspect -> string
3348 *
3349 * Returns a printable version of the enumerator chain.
3350 */
3351static VALUE
3352enum_chain_inspect(VALUE obj)
3353{
3354 return rb_exec_recursive(inspect_enum_chain, obj, 0);
3355}
3356
3357/*
3358 * call-seq:
3359 * e.chain(*enums) -> enumerator
3360 *
3361 * Returns an enumerator object generated from this enumerator and
3362 * given enumerables.
3363 *
3364 * e = (1..3).chain([4, 5])
3365 * e.to_a #=> [1, 2, 3, 4, 5]
3366 */
3367static VALUE
3368enum_chain(int argc, VALUE *argv, VALUE obj)
3369{
3370 VALUE enums = rb_ary_new_from_values(1, &obj);
3371 rb_ary_cat(enums, argv, argc);
3372 return new_enum_chain(enums);
3373}
3374
3375/*
3376 * call-seq:
3377 * e + enum -> enumerator
3378 *
3379 * Returns an enumerator object generated from this enumerator and a
3380 * given enumerable.
3381 *
3382 * e = (1..3).each + [4, 5]
3383 * e.to_a #=> [1, 2, 3, 4, 5]
3384 */
3385static VALUE
3386enumerator_plus(VALUE obj, VALUE eobj)
3387{
3388 return new_enum_chain(rb_ary_new_from_args(2, obj, eobj));
3389}
3390
3391/*
3392 * Document-class: Enumerator::Product
3393 *
3394 * Enumerator::Product generates a Cartesian product of any number of
3395 * enumerable objects. Iterating over the product of enumerable
3396 * objects is roughly equivalent to nested each_entry loops where the
3397 * loop for the rightmost object is put innermost.
3398 *
3399 * innings = Enumerator::Product.new(1..9, ['top', 'bottom'])
3400 *
3401 * innings.each do |i, h|
3402 * p [i, h]
3403 * end
3404 * # [1, "top"]
3405 * # [1, "bottom"]
3406 * # [2, "top"]
3407 * # [2, "bottom"]
3408 * # [3, "top"]
3409 * # [3, "bottom"]
3410 * # ...
3411 * # [9, "top"]
3412 * # [9, "bottom"]
3413 *
3414 * The method used against each enumerable object is `each_entry`
3415 * instead of `each` so that the product of N enumerable objects
3416 * yields an array of exactly N elements in each iteration.
3417 *
3418 * When no enumerator is given, it calls a given block once yielding
3419 * an empty argument list.
3420 *
3421 * This type of objects can be created by Enumerator.product.
3422 */
3423
3424static void
3425enum_product_mark_and_move(void *p)
3426{
3427 struct enum_product *ptr = p;
3428 rb_gc_mark_and_move(&ptr->enums);
3429}
3430
3431#define enum_product_free RUBY_TYPED_DEFAULT_FREE
3432
3433static size_t
3434enum_product_memsize(const void *p)
3435{
3436 return sizeof(struct enum_product);
3437}
3438
3439static const rb_data_type_t enum_product_data_type = {
3440 "product",
3441 {
3442 enum_product_mark_and_move,
3443 enum_product_free,
3444 enum_product_memsize,
3445 enum_product_mark_and_move,
3446 },
3447 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
3448};
3449
3450static struct enum_product *
3451enum_product_ptr(VALUE obj)
3452{
3453 struct enum_product *ptr;
3454
3455 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3456 if (!ptr || UNDEF_P(ptr->enums)) {
3457 rb_raise(rb_eArgError, "uninitialized product");
3458 }
3459 return ptr;
3460}
3461
3462/* :nodoc: */
3463static VALUE
3464enum_product_allocate(VALUE klass)
3465{
3466 struct enum_product *ptr;
3467 VALUE obj;
3468
3469 obj = TypedData_Make_Struct(klass, struct enum_product, &enum_product_data_type, ptr);
3470 ptr->enums = Qundef;
3471
3472 return obj;
3473}
3474
3475/*
3476 * call-seq:
3477 * Enumerator::Product.new(*enums) -> enum
3478 *
3479 * Generates a new enumerator object that generates a Cartesian
3480 * product of given enumerable objects.
3481 *
3482 * e = Enumerator::Product.new(1..3, [4, 5])
3483 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3484 * e.size #=> 6
3485 */
3486static VALUE
3487enum_product_initialize(int argc, VALUE *argv, VALUE obj)
3488{
3489 struct enum_product *ptr;
3490 VALUE enums = Qnil, options = Qnil;
3491
3492 rb_scan_args(argc, argv, "*:", &enums, &options);
3493
3494 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3495 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3496 }
3497
3498 rb_check_frozen(obj);
3499 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3500
3501 if (!ptr) rb_raise(rb_eArgError, "unallocated product");
3502
3503 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3504
3505 return obj;
3506}
3507
3508/* :nodoc: */
3509static VALUE
3510enum_product_init_copy(VALUE obj, VALUE orig)
3511{
3512 struct enum_product *ptr0, *ptr1;
3513
3514 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3515 ptr0 = enum_product_ptr(orig);
3516
3517 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr1);
3518
3519 if (!ptr1) rb_raise(rb_eArgError, "unallocated product");
3520
3521 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3522
3523 return obj;
3524}
3525
3526static VALUE
3527enum_product_total_size(VALUE enums)
3528{
3529 VALUE total = INT2FIX(1);
3530 VALUE sizes = rb_ary_hidden_new(RARRAY_LEN(enums));
3531 long i;
3532
3533 for (i = 0; i < RARRAY_LEN(enums); i++) {
3534 VALUE size = enum_size(RARRAY_AREF(enums, i));
3535 if (size == INT2FIX(0)) {
3536 rb_ary_resize(sizes, 0);
3537 return size;
3538 }
3539 rb_ary_push(sizes, size);
3540 }
3541 for (i = 0; i < RARRAY_LEN(sizes); i++) {
3542 VALUE size = RARRAY_AREF(sizes, i);
3543
3544 if (NIL_P(size) || (RB_TYPE_P(size, T_FLOAT) && isinf(NUM2DBL(size)))) {
3545 return size;
3546 }
3547 if (!RB_INTEGER_TYPE_P(size)) {
3548 return Qnil;
3549 }
3550
3551 total = rb_funcall(total, '*', 1, size);
3552 }
3553
3554 return total;
3555}
3556
3557/*
3558 * call-seq:
3559 * obj.size -> int, Float::INFINITY or nil
3560 *
3561 * Returns the total size of the enumerator product calculated by
3562 * multiplying the sizes of enumerables in the product. If any of the
3563 * enumerables reports its size as nil or Float::INFINITY, that value
3564 * is returned as the size.
3565 */
3566static VALUE
3567enum_product_size(VALUE obj)
3568{
3569 return enum_product_total_size(enum_product_ptr(obj)->enums);
3570}
3571
3572static VALUE
3573enum_product_enum_size(VALUE obj, VALUE args, VALUE eobj)
3574{
3575 return enum_product_size(obj);
3576}
3577
3579 VALUE obj;
3580 VALUE block;
3581 int argc;
3582 VALUE *argv;
3583 int index;
3584};
3585
3586static VALUE product_each(VALUE, struct product_state *);
3587
3588static VALUE
3589product_each_i(RB_BLOCK_CALL_FUNC_ARGLIST(value, state))
3590{
3591 struct product_state *pstate = (struct product_state *)state;
3592 pstate->argv[pstate->index++] = value;
3593
3594 VALUE val = product_each(pstate->obj, pstate);
3595 pstate->index--;
3596 return val;
3597}
3598
3599static VALUE
3600product_each(VALUE obj, struct product_state *pstate)
3601{
3602 struct enum_product *ptr = enum_product_ptr(obj);
3603 VALUE enums = ptr->enums;
3604
3605 if (pstate->index < pstate->argc) {
3606 VALUE eobj = RARRAY_AREF(enums, pstate->index);
3607
3608 rb_block_call(eobj, id_each_entry, 0, NULL, product_each_i, (VALUE)pstate);
3609 }
3610 else {
3611 rb_funcall(pstate->block, id_call, 1, rb_ary_new_from_values(pstate->argc, pstate->argv));
3612 }
3613
3614 return obj;
3615}
3616
3617static VALUE
3618enum_product_run(VALUE obj, VALUE block)
3619{
3620 struct enum_product *ptr = enum_product_ptr(obj);
3621 int argc = RARRAY_LENINT(ptr->enums);
3622 struct product_state state = {
3623 .obj = obj,
3624 .block = block,
3625 .index = 0,
3626 .argc = argc,
3627 .argv = ALLOCA_N(VALUE, argc),
3628 };
3629
3630 return product_each(obj, &state);
3631}
3632
3633/*
3634 * call-seq:
3635 * obj.each { |...| ... } -> obj
3636 * obj.each -> enumerator
3637 *
3638 * Iterates over the elements of the first enumerable by calling the
3639 * "each_entry" method on it with the given arguments, then proceeds
3640 * to the following enumerables in sequence until all of the
3641 * enumerables are exhausted.
3642 *
3643 * If no block is given, returns an enumerator. Otherwise, returns self.
3644 */
3645static VALUE
3646enum_product_each(VALUE obj)
3647{
3648 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_product_enum_size);
3649
3650 return enum_product_run(obj, rb_block_proc());
3651}
3652
3653/*
3654 * call-seq:
3655 * obj.rewind -> obj
3656 *
3657 * Rewinds the product enumerator by calling the "rewind" method on
3658 * each enumerable in reverse order. Each call is performed only if
3659 * the enumerable responds to the method.
3660 */
3661static VALUE
3662enum_product_rewind(VALUE obj)
3663{
3664 struct enum_product *ptr = enum_product_ptr(obj);
3665 VALUE enums = ptr->enums;
3666 long i;
3667
3668 for (i = 0; i < RARRAY_LEN(enums); i++) {
3669 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3670 }
3671
3672 return obj;
3673}
3674
3675static VALUE
3676inspect_enum_product(VALUE obj, VALUE dummy, int recur)
3677{
3678 VALUE klass = rb_obj_class(obj);
3679 struct enum_product *ptr;
3680
3681 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3682
3683 if (!ptr || UNDEF_P(ptr->enums)) {
3684 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3685 }
3686
3687 if (recur) {
3688 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3689 }
3690
3691 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3692}
3693
3694/*
3695 * call-seq:
3696 * obj.inspect -> string
3697 *
3698 * Returns a printable version of the product enumerator.
3699 */
3700static VALUE
3701enum_product_inspect(VALUE obj)
3702{
3703 return rb_exec_recursive(inspect_enum_product, obj, 0);
3704}
3705
3706/*
3707 * call-seq:
3708 * Enumerator.product(*enums) -> enumerator
3709 * Enumerator.product(*enums) { |elts| ... } -> enumerator
3710 *
3711 * Generates a new enumerator object that generates a Cartesian
3712 * product of given enumerable objects. This is equivalent to
3713 * Enumerator::Product.new.
3714 *
3715 * e = Enumerator.product(1..3, [4, 5])
3716 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3717 * e.size #=> 6
3718 *
3719 * When a block is given, calls the block with each N-element array
3720 * generated and returns +nil+.
3721 */
3722static VALUE
3723enumerator_s_product(int argc, VALUE *argv, VALUE klass)
3724{
3725 VALUE enums = Qnil, options = Qnil, block = Qnil;
3726
3727 rb_scan_args(argc, argv, "*:&", &enums, &options, &block);
3728
3729 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3730 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3731 }
3732
3733 VALUE obj = enum_product_initialize(argc, argv, enum_product_allocate(rb_cEnumProduct));
3734
3735 if (!NIL_P(block)) {
3736 enum_product_run(obj, block);
3737 return Qnil;
3738 }
3739
3740 return obj;
3741}
3742
3744 struct enumerator enumerator;
3745 VALUE begin;
3746 VALUE end;
3747 VALUE step;
3748 bool exclude_end;
3749};
3750
3751RUBY_REFERENCES(arith_seq_refs) = {
3752 RUBY_REF_EDGE(struct enumerator, obj),
3753 RUBY_REF_EDGE(struct enumerator, args),
3754 RUBY_REF_EDGE(struct enumerator, fib),
3755 RUBY_REF_EDGE(struct enumerator, dst),
3756 RUBY_REF_EDGE(struct enumerator, lookahead),
3757 RUBY_REF_EDGE(struct enumerator, feedvalue),
3758 RUBY_REF_EDGE(struct enumerator, stop_exc),
3759 RUBY_REF_EDGE(struct enumerator, size),
3760 RUBY_REF_EDGE(struct enumerator, procs),
3761
3762 RUBY_REF_EDGE(struct arith_seq, begin),
3763 RUBY_REF_EDGE(struct arith_seq, end),
3764 RUBY_REF_EDGE(struct arith_seq, step),
3765 RUBY_REF_END
3766};
3767
3768static const rb_data_type_t arith_seq_data_type = {
3769 "arithmetic_sequence",
3770 {
3771 RUBY_REFS_LIST_PTR(arith_seq_refs),
3773 NULL, // Nothing allocated externally, so don't need a memsize function
3774 NULL,
3775 },
3776 .parent = &enumerator_data_type,
3777 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
3778};
3779
3780static VALUE
3781arith_seq_allocate(VALUE klass)
3782{
3783 struct arith_seq *ptr;
3784 VALUE enum_obj;
3785
3786 enum_obj = TypedData_Make_Struct(klass, struct arith_seq, &arith_seq_data_type, ptr);
3787 ptr->enumerator.obj = Qundef;
3788
3789 return enum_obj;
3790}
3791
3792/*
3793 * Document-class: Enumerator::ArithmeticSequence
3794 *
3795 * Enumerator::ArithmeticSequence is a subclass of Enumerator,
3796 * that is a representation of sequences of numbers with common difference.
3797 * Instances of this class can be generated by the Range#step and Numeric#step
3798 * methods.
3799 *
3800 * The class can be used for slicing Array (see Array#slice) or custom
3801 * collections.
3802 */
3803
3804VALUE
3805rb_arith_seq_new(VALUE obj, VALUE meth, int argc, VALUE const *argv,
3806 rb_enumerator_size_func *size_fn,
3807 VALUE beg, VALUE end, VALUE step, int excl)
3808{
3809 VALUE aseq = enumerator_init(arith_seq_allocate(rb_cArithSeq),
3810 obj, meth, argc, argv, size_fn, Qnil, rb_keyword_given_p());
3811 struct arith_seq *ptr;
3812 TypedData_Get_Struct(aseq, struct arith_seq, &enumerator_data_type, ptr);
3813
3814 RB_OBJ_WRITE(aseq, &ptr->begin, beg);
3815 RB_OBJ_WRITE(aseq, &ptr->end, end);
3816 RB_OBJ_WRITE(aseq, &ptr->step, step);
3817 ptr->exclude_end = excl;
3818
3819 return aseq;
3820}
3821
3822/*
3823 * call-seq: aseq.begin -> num or nil
3824 *
3825 * Returns the number that defines the first element of this arithmetic
3826 * sequence.
3827 */
3828static inline VALUE
3829arith_seq_begin(VALUE self)
3830{
3831 struct arith_seq *ptr;
3832 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3833 return ptr->begin;
3834}
3835
3836/*
3837 * call-seq: aseq.end -> num or nil
3838 *
3839 * Returns the number that defines the end of this arithmetic sequence.
3840 */
3841static inline VALUE
3842arith_seq_end(VALUE self)
3843{
3844 struct arith_seq *ptr;
3845 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3846 return ptr->end;
3847}
3848
3849/*
3850 * call-seq: aseq.step -> num
3851 *
3852 * Returns the number that defines the common difference between
3853 * two adjacent elements in this arithmetic sequence.
3854 */
3855static inline VALUE
3856arith_seq_step(VALUE self)
3857{
3858 struct arith_seq *ptr;
3859 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3860 return ptr->step;
3861}
3862
3863/*
3864 * call-seq: aseq.exclude_end? -> true or false
3865 *
3866 * Returns <code>true</code> if this arithmetic sequence excludes its end value.
3867 */
3868static inline VALUE
3869arith_seq_exclude_end(VALUE self)
3870{
3871 struct arith_seq *ptr;
3872 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3873 return RBOOL(ptr->exclude_end);
3874}
3875
3876static inline int
3877arith_seq_exclude_end_p(VALUE self)
3878{
3879 struct arith_seq *ptr;
3880 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3881 return ptr->exclude_end;
3882}
3883
3884int
3885rb_arithmetic_sequence_extract(VALUE obj, rb_arithmetic_sequence_components_t *component)
3886{
3887 if (rb_obj_is_kind_of(obj, rb_cArithSeq)) {
3888 component->begin = arith_seq_begin(obj);
3889 component->end = arith_seq_end(obj);
3890 component->step = arith_seq_step(obj);
3891 component->exclude_end = arith_seq_exclude_end_p(obj);
3892 return 1;
3893 }
3894 else if (rb_range_values(obj, &component->begin, &component->end, &component->exclude_end)) {
3895 component->step = INT2FIX(1);
3896 return 1;
3897 }
3898
3899 return 0;
3900}
3901
3902VALUE
3903rb_arithmetic_sequence_beg_len_step(VALUE obj, long *begp, long *lenp, long *stepp, long len, int err)
3904{
3905 RBIMPL_NONNULL_ARG(begp);
3906 RBIMPL_NONNULL_ARG(lenp);
3907 RBIMPL_NONNULL_ARG(stepp);
3908
3910 if (!rb_arithmetic_sequence_extract(obj, &aseq)) {
3911 return Qfalse;
3912 }
3913
3914 long step = NIL_P(aseq.step) ? 1 : NUM2LONG(aseq.step);
3915 *stepp = step;
3916
3917 if (step < 0) {
3918 if (aseq.exclude_end && !NIL_P(aseq.end)) {
3919 /* Handle exclusion before range reversal */
3920 aseq.end = LONG2NUM(NUM2LONG(aseq.end) + 1);
3921
3922 /* Don't exclude the previous beginning */
3923 aseq.exclude_end = 0;
3924 }
3925 VALUE tmp = aseq.begin;
3926 aseq.begin = aseq.end;
3927 aseq.end = tmp;
3928 }
3929
3930 if (err == 0 && (step < -1 || step > 1)) {
3931 if (rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, 1) == Qtrue) {
3932 if (*begp > len)
3933 goto out_of_range;
3934 if (*lenp > len)
3935 goto out_of_range;
3936 return Qtrue;
3937 }
3938 }
3939 else {
3940 return rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, err);
3941 }
3942
3943 out_of_range:
3944 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", obj);
3945 return Qnil;
3946}
3947
3948static VALUE
3949arith_seq_take(VALUE self, VALUE num)
3950{
3951 VALUE b, e, s, ary;
3952 long n;
3953 int x;
3954
3955 n = NUM2LONG(num);
3956 if (n < 0) {
3957 rb_raise(rb_eArgError, "attempt to take negative size");
3958 }
3959 if (n == 0) {
3960 return rb_ary_new_capa(0);
3961 }
3962
3963 b = arith_seq_begin(self);
3964 e = arith_seq_end(self);
3965 s = arith_seq_step(self);
3966 x = arith_seq_exclude_end_p(self);
3967
3968 if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(s)) {
3969 long i = FIX2LONG(b), unit = FIX2LONG(s);
3970 ary = rb_ary_new_capa(n);
3971 while (n > 0 && FIXABLE(i)) {
3972 rb_ary_push(ary, LONG2FIX(i));
3973 i += unit; // FIXABLE + FIXABLE never overflow;
3974 --n;
3975 }
3976 if (n > 0) {
3977 b = LONG2NUM(i);
3978 while (n > 0) {
3979 rb_ary_push(ary, b);
3980 b = rb_big_plus(b, s);
3981 --n;
3982 }
3983 }
3984 return ary;
3985 }
3986 else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(s)) {
3987 long i = FIX2LONG(b);
3988 long end = FIX2LONG(e);
3989 long unit = FIX2LONG(s);
3990 long len;
3991
3992 if (unit >= 0) {
3993 if (!x) end += 1;
3994
3995 len = end - i;
3996 if (len < 0) len = 0;
3997 ary = rb_ary_new_capa((n < len) ? n : len);
3998 while (n > 0 && i < end) {
3999 rb_ary_push(ary, LONG2FIX(i));
4000 if (i > LONG_MAX - unit) break;
4001 i += unit;
4002 --n;
4003 }
4004 }
4005 else {
4006 if (!x) end -= 1;
4007
4008 len = i - end;
4009 if (len < 0) len = 0;
4010 ary = rb_ary_new_capa((n < len) ? n : len);
4011 while (n > 0 && i > end) {
4012 rb_ary_push(ary, LONG2FIX(i));
4013 if (i < LONG_MIN - unit) break;
4014 i += unit;
4015 --n;
4016 }
4017 }
4018 return ary;
4019 }
4020 else if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4021 /* generate values like ruby_float_step */
4022
4023 double unit = NUM2DBL(s);
4024 double beg = NUM2DBL(b);
4025 double end = NIL_P(e) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(e);
4026 double len = ruby_float_step_size(beg, end, unit, x);
4027 long i;
4028
4029 if (n > len)
4030 n = (long)len;
4031
4032 if (isinf(unit)) {
4033 if (len > 0) {
4034 ary = rb_ary_new_capa(1);
4035 rb_ary_push(ary, DBL2NUM(beg));
4036 }
4037 else {
4038 ary = rb_ary_new_capa(0);
4039 }
4040 }
4041 else if (unit == 0) {
4042 VALUE val = DBL2NUM(beg);
4043 ary = rb_ary_new_capa(n);
4044 for (i = 0; i < len; ++i) {
4045 rb_ary_push(ary, val);
4046 }
4047 }
4048 else {
4049 ary = rb_ary_new_capa(n);
4050 for (i = 0; i < n; ++i) {
4051 double d = i*unit+beg;
4052 if (unit >= 0 ? end < d : d < end) d = end;
4053 rb_ary_push(ary, DBL2NUM(d));
4054 }
4055 }
4056
4057 return ary;
4058 }
4059
4060 {
4061 VALUE argv[1];
4062 argv[0] = num;
4063 return rb_call_super(1, argv);
4064 }
4065}
4066
4067/*
4068 * call-seq:
4069 * aseq.first -> num or nil
4070 * aseq.first(n) -> an_array
4071 *
4072 * Returns the first number in this arithmetic sequence,
4073 * or an array of the first +n+ elements.
4074 */
4075static VALUE
4076arith_seq_first(int argc, VALUE *argv, VALUE self)
4077{
4078 VALUE b, e, s;
4079
4080 rb_check_arity(argc, 0, 1);
4081
4082 b = arith_seq_begin(self);
4083 e = arith_seq_end(self);
4084 s = arith_seq_step(self);
4085 if (argc == 0) {
4086 if (NIL_P(b)) {
4087 return Qnil;
4088 }
4089 if (!NIL_P(e)) {
4090 VALUE zero = INT2FIX(0);
4091 int r = rb_cmpint(rb_num_coerce_cmp(s, zero, idCmp), s, zero);
4092 if (r > 0 && RTEST(rb_funcall(b, '>', 1, e))) {
4093 return Qnil;
4094 }
4095 if (r < 0 && RTEST(rb_funcall(b, '<', 1, e))) {
4096 return Qnil;
4097 }
4098 }
4099 return b;
4100 }
4101
4102 return arith_seq_take(self, argv[0]);
4103}
4104
4105static inline VALUE
4106num_plus(VALUE a, VALUE b)
4107{
4108 if (RB_INTEGER_TYPE_P(a)) {
4109 return rb_int_plus(a, b);
4110 }
4111 else if (RB_FLOAT_TYPE_P(a)) {
4112 return rb_float_plus(a, b);
4113 }
4114 else if (RB_TYPE_P(a, T_RATIONAL)) {
4115 return rb_rational_plus(a, b);
4116 }
4117 else {
4118 return rb_funcallv(a, '+', 1, &b);
4119 }
4120}
4121
4122static inline VALUE
4123num_minus(VALUE a, VALUE b)
4124{
4125 if (RB_INTEGER_TYPE_P(a)) {
4126 return rb_int_minus(a, b);
4127 }
4128 else if (RB_FLOAT_TYPE_P(a)) {
4129 return rb_float_minus(a, b);
4130 }
4131 else if (RB_TYPE_P(a, T_RATIONAL)) {
4132 return rb_rational_minus(a, b);
4133 }
4134 else {
4135 return rb_funcallv(a, '-', 1, &b);
4136 }
4137}
4138
4139static inline VALUE
4140num_mul(VALUE a, VALUE b)
4141{
4142 if (RB_INTEGER_TYPE_P(a)) {
4143 return rb_int_mul(a, b);
4144 }
4145 else if (RB_FLOAT_TYPE_P(a)) {
4146 return rb_float_mul(a, b);
4147 }
4148 else if (RB_TYPE_P(a, T_RATIONAL)) {
4149 return rb_rational_mul(a, b);
4150 }
4151 else {
4152 return rb_funcallv(a, '*', 1, &b);
4153 }
4154}
4155
4156static inline VALUE
4157num_idiv(VALUE a, VALUE b)
4158{
4159 VALUE q;
4160 if (RB_INTEGER_TYPE_P(a)) {
4161 q = rb_int_idiv(a, b);
4162 }
4163 else if (RB_FLOAT_TYPE_P(a)) {
4164 q = rb_float_div(a, b);
4165 }
4166 else if (RB_TYPE_P(a, T_RATIONAL)) {
4167 q = rb_rational_div(a, b);
4168 }
4169 else {
4170 q = rb_funcallv(a, idDiv, 1, &b);
4171 }
4172
4173 if (RB_INTEGER_TYPE_P(q)) {
4174 return q;
4175 }
4176 else if (RB_FLOAT_TYPE_P(q)) {
4177 return rb_float_floor(q, 0);
4178 }
4179 else if (RB_TYPE_P(q, T_RATIONAL)) {
4180 return rb_rational_floor(q, 0);
4181 }
4182 else {
4183 return rb_funcall(q, rb_intern("floor"), 0);
4184 }
4185}
4186
4187/*
4188 * call-seq:
4189 * aseq.last -> num or nil
4190 * aseq.last(n) -> an_array
4191 *
4192 * Returns the last number in this arithmetic sequence,
4193 * or an array of the last +n+ elements.
4194 */
4195static VALUE
4196arith_seq_last(int argc, VALUE *argv, VALUE self)
4197{
4198 VALUE b, e, s, len_1, len, last, nv, ary;
4199 int last_is_adjusted;
4200 long n;
4201
4202 e = arith_seq_end(self);
4203 if (NIL_P(e)) {
4204 rb_raise(rb_eRangeError,
4205 "cannot get the last element of endless arithmetic sequence");
4206 }
4207
4208 b = arith_seq_begin(self);
4209 s = arith_seq_step(self);
4210
4211 len_1 = num_idiv(num_minus(e, b), s);
4212 if (rb_num_negative_int_p(len_1)) {
4213 if (argc == 0) {
4214 return Qnil;
4215 }
4216 return rb_ary_new_capa(0);
4217 }
4218
4219 last = num_plus(b, num_mul(s, len_1));
4220 if ((last_is_adjusted = arith_seq_exclude_end_p(self) && rb_equal(last, e))) {
4221 last = num_minus(last, s);
4222 }
4223
4224 if (argc == 0) {
4225 return last;
4226 }
4227
4228 if (last_is_adjusted) {
4229 len = len_1;
4230 }
4231 else {
4232 len = rb_int_plus(len_1, INT2FIX(1));
4233 }
4234
4235 rb_scan_args(argc, argv, "1", &nv);
4236 if (!RB_INTEGER_TYPE_P(nv)) {
4237 nv = rb_to_int(nv);
4238 }
4239 if (RTEST(rb_int_gt(nv, len))) {
4240 nv = len;
4241 }
4242 n = NUM2LONG(nv);
4243 if (n < 0) {
4244 rb_raise(rb_eArgError, "negative array size");
4245 }
4246
4247 ary = rb_ary_new_capa(n);
4248 b = rb_int_minus(last, rb_int_mul(s, nv));
4249 while (n) {
4250 b = rb_int_plus(b, s);
4251 rb_ary_push(ary, b);
4252 --n;
4253 }
4254
4255 return ary;
4256}
4257
4258/*
4259 * call-seq:
4260 * aseq.inspect -> string
4261 *
4262 * Convert this arithmetic sequence to a printable form.
4263 */
4264static VALUE
4265arith_seq_inspect(VALUE self)
4266{
4267 struct enumerator *e;
4268 VALUE eobj, str, eargs;
4269 int range_p;
4270
4271 TypedData_Get_Struct(self, struct enumerator, &enumerator_data_type, e);
4272
4273 eobj = rb_attr_get(self, id_receiver);
4274 if (NIL_P(eobj)) {
4275 eobj = e->obj;
4276 }
4277
4278 range_p = RTEST(rb_obj_is_kind_of(eobj, rb_cRange));
4279 str = rb_sprintf("(%s%"PRIsVALUE"%s.", range_p ? "(" : "", eobj, range_p ? ")" : "");
4280
4281 rb_str_buf_append(str, rb_id2str(e->meth));
4282
4283 eargs = rb_attr_get(eobj, id_arguments);
4284 if (NIL_P(eargs)) {
4285 eargs = e->args;
4286 }
4287 if (eargs != Qfalse) {
4288 long argc = RARRAY_LEN(eargs);
4289 const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */
4290
4291 if (argc > 0) {
4292 VALUE kwds = Qnil;
4293
4294 rb_str_buf_cat2(str, "(");
4295
4296 if (RB_TYPE_P(argv[argc-1], T_HASH)) {
4297 int all_key = TRUE;
4298 rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key);
4299 if (all_key) kwds = argv[--argc];
4300 }
4301
4302 while (argc--) {
4303 VALUE arg = *argv++;
4304
4305 rb_str_append(str, rb_inspect(arg));
4306 rb_str_buf_cat2(str, ", ");
4307 }
4308 if (!NIL_P(kwds)) {
4309 rb_hash_foreach(kwds, kwd_append, str);
4310 }
4311 rb_str_set_len(str, RSTRING_LEN(str)-2); /* drop the last ", " */
4312 rb_str_buf_cat2(str, ")");
4313 }
4314 }
4315
4316 rb_str_buf_cat2(str, ")");
4317
4318 return str;
4319}
4320
4321/*
4322 * call-seq:
4323 * aseq == obj -> true or false
4324 *
4325 * Returns <code>true</code> only if +obj+ is an Enumerator::ArithmeticSequence,
4326 * has equivalent begin, end, step, and exclude_end? settings.
4327 */
4328static VALUE
4329arith_seq_eq(VALUE self, VALUE other)
4330{
4331 if (!RTEST(rb_obj_is_kind_of(other, rb_cArithSeq))) {
4332 return Qfalse;
4333 }
4334
4335 if (!rb_equal(arith_seq_begin(self), arith_seq_begin(other))) {
4336 return Qfalse;
4337 }
4338
4339 if (!rb_equal(arith_seq_end(self), arith_seq_end(other))) {
4340 return Qfalse;
4341 }
4342
4343 if (!rb_equal(arith_seq_step(self), arith_seq_step(other))) {
4344 return Qfalse;
4345 }
4346
4347 if (arith_seq_exclude_end_p(self) != arith_seq_exclude_end_p(other)) {
4348 return Qfalse;
4349 }
4350
4351 return Qtrue;
4352}
4353
4354/*
4355 * call-seq:
4356 * aseq.hash -> integer
4357 *
4358 * Compute a hash-value for this arithmetic sequence.
4359 * Two arithmetic sequences with same begin, end, step, and exclude_end?
4360 * values will generate the same hash-value.
4361 *
4362 * See also Object#hash.
4363 */
4364static VALUE
4365arith_seq_hash(VALUE self)
4366{
4367 st_index_t hash;
4368 VALUE v;
4369
4370 hash = rb_hash_start(arith_seq_exclude_end_p(self));
4371 v = rb_hash(arith_seq_begin(self));
4372 hash = rb_hash_uint(hash, NUM2LONG(v));
4373 v = rb_hash(arith_seq_end(self));
4374 hash = rb_hash_uint(hash, NUM2LONG(v));
4375 v = rb_hash(arith_seq_step(self));
4376 hash = rb_hash_uint(hash, NUM2LONG(v));
4377 hash = rb_hash_end(hash);
4378
4379 return ST2FIX(hash);
4380}
4381
4382#define NUM_GE(x, y) RTEST(rb_num_coerce_relop((x), (y), idGE))
4383
4385 VALUE current;
4386 VALUE end;
4387 VALUE step;
4388 int excl;
4389};
4390
4391/*
4392 * call-seq:
4393 * aseq.each {|i| block } -> aseq
4394 * aseq.each -> aseq
4395 */
4396static VALUE
4397arith_seq_each(VALUE self)
4398{
4399 VALUE c, e, s, len_1, last;
4400 int x;
4401
4402 if (!rb_block_given_p()) return self;
4403
4404 c = arith_seq_begin(self);
4405 e = arith_seq_end(self);
4406 s = arith_seq_step(self);
4407 x = arith_seq_exclude_end_p(self);
4408
4409 if (!RB_TYPE_P(s, T_COMPLEX) && ruby_float_step(c, e, s, x, TRUE)) {
4410 return self;
4411 }
4412
4413 if (NIL_P(e)) {
4414 while (1) {
4415 rb_yield(c);
4416 c = rb_int_plus(c, s);
4417 }
4418
4419 return self;
4420 }
4421
4422 if (rb_equal(s, INT2FIX(0))) {
4423 while (1) {
4424 rb_yield(c);
4425 }
4426
4427 return self;
4428 }
4429
4430 len_1 = num_idiv(num_minus(e, c), s);
4431 last = num_plus(c, num_mul(s, len_1));
4432 if (x && rb_equal(last, e)) {
4433 last = num_minus(last, s);
4434 }
4435
4436 if (rb_num_negative_int_p(s)) {
4437 while (NUM_GE(c, last)) {
4438 rb_yield(c);
4439 c = num_plus(c, s);
4440 }
4441 }
4442 else {
4443 while (NUM_GE(last, c)) {
4444 rb_yield(c);
4445 c = num_plus(c, s);
4446 }
4447 }
4448
4449 return self;
4450}
4451
4452/*
4453 * call-seq:
4454 * aseq.size -> num or nil
4455 *
4456 * Returns the number of elements in this arithmetic sequence if it is a finite
4457 * sequence. Otherwise, returns <code>nil</code>.
4458 */
4459static VALUE
4460arith_seq_size(VALUE self)
4461{
4462 VALUE b, e, s, len_1, len, last;
4463 int x;
4464
4465 b = arith_seq_begin(self);
4466 e = arith_seq_end(self);
4467 s = arith_seq_step(self);
4468 x = arith_seq_exclude_end_p(self);
4469
4470 if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4471 double ee, n;
4472
4473 if (NIL_P(e)) {
4474 if (rb_num_negative_int_p(s)) {
4475 ee = -HUGE_VAL;
4476 }
4477 else {
4478 ee = HUGE_VAL;
4479 }
4480 }
4481 else {
4482 ee = NUM2DBL(e);
4483 }
4484
4485 n = ruby_float_step_size(NUM2DBL(b), ee, NUM2DBL(s), x);
4486 if (isinf(n)) return DBL2NUM(n);
4487 if (POSFIXABLE(n)) return LONG2FIX((long)n);
4488 return rb_dbl2big(n);
4489 }
4490
4491 if (NIL_P(e)) {
4492 return DBL2NUM(HUGE_VAL);
4493 }
4494
4495 if (!rb_obj_is_kind_of(s, rb_cNumeric)) {
4496 s = rb_to_int(s);
4497 }
4498
4499 if (rb_equal(s, INT2FIX(0))) {
4500 return DBL2NUM(HUGE_VAL);
4501 }
4502
4503 len_1 = rb_int_idiv(rb_int_minus(e, b), s);
4504 if (rb_num_negative_int_p(len_1)) {
4505 return INT2FIX(0);
4506 }
4507
4508 last = rb_int_plus(b, rb_int_mul(s, len_1));
4509 if (x && rb_equal(last, e)) {
4510 len = len_1;
4511 }
4512 else {
4513 len = rb_int_plus(len_1, INT2FIX(1));
4514 }
4515
4516 return len;
4517}
4518
4519#define sym(name) ID2SYM(rb_intern_const(name))
4520void
4521InitVM_Enumerator(void)
4522{
4523 ID id_private = rb_intern_const("private");
4524
4525 rb_define_method(rb_mKernel, "to_enum", obj_to_enum, -1);
4526 rb_define_method(rb_mKernel, "enum_for", obj_to_enum, -1);
4527
4528 rb_cEnumerator = rb_define_class("Enumerator", rb_cObject);
4530
4531 rb_define_alloc_func(rb_cEnumerator, enumerator_allocate);
4532 rb_define_method(rb_cEnumerator, "initialize", enumerator_initialize, -1);
4533 rb_define_method(rb_cEnumerator, "initialize_copy", enumerator_init_copy, 1);
4534 rb_define_method(rb_cEnumerator, "each", enumerator_each, -1);
4535 rb_define_method(rb_cEnumerator, "each_with_index", enumerator_each_with_index, 0);
4536 rb_define_method(rb_cEnumerator, "each_with_object", enumerator_with_object, 1);
4537 rb_define_method(rb_cEnumerator, "with_index", enumerator_with_index, -1);
4538 rb_define_method(rb_cEnumerator, "with_object", enumerator_with_object, 1);
4539 rb_define_method(rb_cEnumerator, "next_values", enumerator_next_values, 0);
4540 rb_define_method(rb_cEnumerator, "peek_values", enumerator_peek_values_m, 0);
4541 rb_define_method(rb_cEnumerator, "next", enumerator_next, 0);
4542 rb_define_method(rb_cEnumerator, "peek", enumerator_peek, 0);
4543 rb_define_method(rb_cEnumerator, "feed", enumerator_feed, 1);
4544 rb_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
4545 rb_define_method(rb_cEnumerator, "inspect", enumerator_inspect, 0);
4546 rb_define_method(rb_cEnumerator, "size", enumerator_size, 0);
4547 rb_define_method(rb_cEnumerator, "+", enumerator_plus, 1);
4549
4550 /* Lazy */
4552 rb_define_method(rb_mEnumerable, "lazy", enumerable_lazy, 0);
4553
4554 rb_define_alias(rb_cLazy, "_enumerable_map", "map");
4555 rb_define_alias(rb_cLazy, "_enumerable_collect", "collect");
4556 rb_define_alias(rb_cLazy, "_enumerable_flat_map", "flat_map");
4557 rb_define_alias(rb_cLazy, "_enumerable_collect_concat", "collect_concat");
4558 rb_define_alias(rb_cLazy, "_enumerable_select", "select");
4559 rb_define_alias(rb_cLazy, "_enumerable_find_all", "find_all");
4560 rb_define_alias(rb_cLazy, "_enumerable_filter", "filter");
4561 rb_define_alias(rb_cLazy, "_enumerable_filter_map", "filter_map");
4562 rb_define_alias(rb_cLazy, "_enumerable_reject", "reject");
4563 rb_define_alias(rb_cLazy, "_enumerable_grep", "grep");
4564 rb_define_alias(rb_cLazy, "_enumerable_grep_v", "grep_v");
4565 rb_define_alias(rb_cLazy, "_enumerable_zip", "zip");
4566 rb_define_alias(rb_cLazy, "_enumerable_take", "take");
4567 rb_define_alias(rb_cLazy, "_enumerable_take_while", "take_while");
4568 rb_define_alias(rb_cLazy, "_enumerable_drop", "drop");
4569 rb_define_alias(rb_cLazy, "_enumerable_drop_while", "drop_while");
4570 rb_define_alias(rb_cLazy, "_enumerable_uniq", "uniq");
4571 rb_define_private_method(rb_cLazy, "_enumerable_with_index", enumerator_with_index, -1);
4572
4573 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_map"));
4574 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_collect"));
4575 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_flat_map"));
4576 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_collect_concat"));
4577 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_select"));
4578 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_find_all"));
4579 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_filter"));
4580 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_filter_map"));
4581 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_reject"));
4582 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_grep"));
4583 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_grep_v"));
4584 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_zip"));
4585 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_take"));
4586 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_take_while"));
4587 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_drop"));
4588 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_drop_while"));
4589 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_uniq"));
4590
4591 rb_define_method(rb_cLazy, "initialize", lazy_initialize, -1);
4592 rb_define_method(rb_cLazy, "to_enum", lazy_to_enum, -1);
4593 rb_define_method(rb_cLazy, "enum_for", lazy_to_enum, -1);
4594 rb_define_method(rb_cLazy, "eager", lazy_eager, 0);
4595 rb_define_method(rb_cLazy, "map", lazy_map, 0);
4596 rb_define_method(rb_cLazy, "collect", lazy_map, 0);
4597 rb_define_method(rb_cLazy, "flat_map", lazy_flat_map, 0);
4598 rb_define_method(rb_cLazy, "collect_concat", lazy_flat_map, 0);
4599 rb_define_method(rb_cLazy, "select", lazy_select, 0);
4600 rb_define_method(rb_cLazy, "find_all", lazy_select, 0);
4601 rb_define_method(rb_cLazy, "filter", lazy_select, 0);
4602 rb_define_method(rb_cLazy, "filter_map", lazy_filter_map, 0);
4603 rb_define_method(rb_cLazy, "reject", lazy_reject, 0);
4604 rb_define_method(rb_cLazy, "grep", lazy_grep, 1);
4605 rb_define_method(rb_cLazy, "grep_v", lazy_grep_v, 1);
4606 rb_define_method(rb_cLazy, "zip", lazy_zip, -1);
4607 rb_define_method(rb_cLazy, "take", lazy_take, 1);
4608 rb_define_method(rb_cLazy, "take_while", lazy_take_while, 0);
4609 rb_define_method(rb_cLazy, "drop", lazy_drop, 1);
4610 rb_define_method(rb_cLazy, "drop_while", lazy_drop_while, 0);
4611 rb_define_method(rb_cLazy, "lazy", lazy_lazy, 0);
4612 rb_define_method(rb_cLazy, "chunk", lazy_super, -1);
4613 rb_define_method(rb_cLazy, "slice_before", lazy_super, -1);
4614 rb_define_method(rb_cLazy, "slice_after", lazy_super, -1);
4615 rb_define_method(rb_cLazy, "slice_when", lazy_super, -1);
4616 rb_define_method(rb_cLazy, "chunk_while", lazy_super, -1);
4617 rb_define_method(rb_cLazy, "uniq", lazy_uniq, 0);
4618 rb_define_method(rb_cLazy, "compact", lazy_compact, 0);
4619 rb_define_method(rb_cLazy, "with_index", lazy_with_index, -1);
4620
4621 lazy_use_super_method = rb_hash_new_with_size(18);
4622 rb_hash_aset(lazy_use_super_method, sym("map"), sym("_enumerable_map"));
4623 rb_hash_aset(lazy_use_super_method, sym("collect"), sym("_enumerable_collect"));
4624 rb_hash_aset(lazy_use_super_method, sym("flat_map"), sym("_enumerable_flat_map"));
4625 rb_hash_aset(lazy_use_super_method, sym("collect_concat"), sym("_enumerable_collect_concat"));
4626 rb_hash_aset(lazy_use_super_method, sym("select"), sym("_enumerable_select"));
4627 rb_hash_aset(lazy_use_super_method, sym("find_all"), sym("_enumerable_find_all"));
4628 rb_hash_aset(lazy_use_super_method, sym("filter"), sym("_enumerable_filter"));
4629 rb_hash_aset(lazy_use_super_method, sym("filter_map"), sym("_enumerable_filter_map"));
4630 rb_hash_aset(lazy_use_super_method, sym("reject"), sym("_enumerable_reject"));
4631 rb_hash_aset(lazy_use_super_method, sym("grep"), sym("_enumerable_grep"));
4632 rb_hash_aset(lazy_use_super_method, sym("grep_v"), sym("_enumerable_grep_v"));
4633 rb_hash_aset(lazy_use_super_method, sym("zip"), sym("_enumerable_zip"));
4634 rb_hash_aset(lazy_use_super_method, sym("take"), sym("_enumerable_take"));
4635 rb_hash_aset(lazy_use_super_method, sym("take_while"), sym("_enumerable_take_while"));
4636 rb_hash_aset(lazy_use_super_method, sym("drop"), sym("_enumerable_drop"));
4637 rb_hash_aset(lazy_use_super_method, sym("drop_while"), sym("_enumerable_drop_while"));
4638 rb_hash_aset(lazy_use_super_method, sym("uniq"), sym("_enumerable_uniq"));
4639 rb_hash_aset(lazy_use_super_method, sym("with_index"), sym("_enumerable_with_index"));
4640 rb_obj_freeze(lazy_use_super_method);
4641 rb_vm_register_global_object(lazy_use_super_method);
4642
4643#if 0 /* for RDoc */
4644 rb_define_method(rb_cLazy, "to_a", lazy_to_a, 0);
4645 rb_define_method(rb_cLazy, "chunk", lazy_chunk, 0);
4646 rb_define_method(rb_cLazy, "chunk_while", lazy_chunk_while, 0);
4647 rb_define_method(rb_cLazy, "slice_after", lazy_slice_after, 0);
4648 rb_define_method(rb_cLazy, "slice_before", lazy_slice_before, 0);
4649 rb_define_method(rb_cLazy, "slice_when", lazy_slice_when, 0);
4650#endif
4651 rb_define_alias(rb_cLazy, "force", "to_a");
4652
4654 rb_define_method(rb_eStopIteration, "result", stop_result, 0);
4655
4656 /* Generator */
4657 rb_cGenerator = rb_define_class_under(rb_cEnumerator, "Generator", rb_cObject);
4658 rb_include_module(rb_cGenerator, rb_mEnumerable);
4659 rb_define_alloc_func(rb_cGenerator, generator_allocate);
4660 rb_define_method(rb_cGenerator, "initialize", generator_initialize, -1);
4661 rb_define_method(rb_cGenerator, "initialize_copy", generator_init_copy, 1);
4662 rb_define_method(rb_cGenerator, "each", generator_each, -1);
4663
4664 /* Yielder */
4665 rb_cYielder = rb_define_class_under(rb_cEnumerator, "Yielder", rb_cObject);
4666 rb_define_alloc_func(rb_cYielder, yielder_allocate);
4667 rb_define_method(rb_cYielder, "initialize", yielder_initialize, 0);
4668 rb_define_method(rb_cYielder, "yield", yielder_yield, -2);
4669 rb_define_method(rb_cYielder, "<<", yielder_yield_push, 1);
4670 rb_define_method(rb_cYielder, "to_proc", yielder_to_proc, 0);
4671
4672 /* Producer */
4673 rb_cEnumProducer = rb_define_class_under(rb_cEnumerator, "Producer", rb_cObject);
4674 rb_define_alloc_func(rb_cEnumProducer, producer_allocate);
4675 rb_define_method(rb_cEnumProducer, "each", producer_each, 0);
4676 rb_define_singleton_method(rb_cEnumerator, "produce", enumerator_s_produce, -1);
4677
4678 /* Chain */
4679 rb_cEnumChain = rb_define_class_under(rb_cEnumerator, "Chain", rb_cEnumerator);
4680 rb_define_alloc_func(rb_cEnumChain, enum_chain_allocate);
4681 rb_define_method(rb_cEnumChain, "initialize", enum_chain_initialize, -2);
4682 rb_define_method(rb_cEnumChain, "initialize_copy", enum_chain_init_copy, 1);
4683 rb_define_method(rb_cEnumChain, "each", enum_chain_each, -1);
4684 rb_define_method(rb_cEnumChain, "size", enum_chain_size, 0);
4685 rb_define_method(rb_cEnumChain, "rewind", enum_chain_rewind, 0);
4686 rb_define_method(rb_cEnumChain, "inspect", enum_chain_inspect, 0);
4687 rb_undef_method(rb_cEnumChain, "feed");
4688 rb_undef_method(rb_cEnumChain, "next");
4689 rb_undef_method(rb_cEnumChain, "next_values");
4690 rb_undef_method(rb_cEnumChain, "peek");
4691 rb_undef_method(rb_cEnumChain, "peek_values");
4692
4693 /* Product */
4694 rb_cEnumProduct = rb_define_class_under(rb_cEnumerator, "Product", rb_cEnumerator);
4695 rb_define_alloc_func(rb_cEnumProduct, enum_product_allocate);
4696 rb_define_method(rb_cEnumProduct, "initialize", enum_product_initialize, -1);
4697 rb_define_method(rb_cEnumProduct, "initialize_copy", enum_product_init_copy, 1);
4698 rb_define_method(rb_cEnumProduct, "each", enum_product_each, 0);
4699 rb_define_method(rb_cEnumProduct, "size", enum_product_size, 0);
4700 rb_define_method(rb_cEnumProduct, "rewind", enum_product_rewind, 0);
4701 rb_define_method(rb_cEnumProduct, "inspect", enum_product_inspect, 0);
4702 rb_undef_method(rb_cEnumProduct, "feed");
4703 rb_undef_method(rb_cEnumProduct, "next");
4704 rb_undef_method(rb_cEnumProduct, "next_values");
4705 rb_undef_method(rb_cEnumProduct, "peek");
4706 rb_undef_method(rb_cEnumProduct, "peek_values");
4707 rb_define_singleton_method(rb_cEnumerator, "product", enumerator_s_product, -1);
4708
4709 /* ArithmeticSequence */
4710 rb_cArithSeq = rb_define_class_under(rb_cEnumerator, "ArithmeticSequence", rb_cEnumerator);
4711 rb_undef_alloc_func(rb_cArithSeq);
4712 rb_undef_method(CLASS_OF(rb_cArithSeq), "new");
4713 rb_define_method(rb_cArithSeq, "begin", arith_seq_begin, 0);
4714 rb_define_method(rb_cArithSeq, "end", arith_seq_end, 0);
4715 rb_define_method(rb_cArithSeq, "exclude_end?", arith_seq_exclude_end, 0);
4716 rb_define_method(rb_cArithSeq, "step", arith_seq_step, 0);
4717 rb_define_method(rb_cArithSeq, "first", arith_seq_first, -1);
4718 rb_define_method(rb_cArithSeq, "last", arith_seq_last, -1);
4719 rb_define_method(rb_cArithSeq, "inspect", arith_seq_inspect, 0);
4720 rb_define_method(rb_cArithSeq, "==", arith_seq_eq, 1);
4721 rb_define_method(rb_cArithSeq, "===", arith_seq_eq, 1);
4722 rb_define_method(rb_cArithSeq, "eql?", arith_seq_eq, 1);
4723 rb_define_method(rb_cArithSeq, "hash", arith_seq_hash, 0);
4724 rb_define_method(rb_cArithSeq, "each", arith_seq_each, 0);
4725 rb_define_method(rb_cArithSeq, "size", arith_seq_size, 0);
4726
4727 rb_provide("enumerator.so"); /* for backward compatibility */
4728}
4729#undef sym
4730
4731void
4732Init_Enumerator(void)
4733{
4734 id_rewind = rb_intern_const("rewind");
4735 id_next = rb_intern_const("next");
4736 id_result = rb_intern_const("result");
4737 id_receiver = rb_intern_const("receiver");
4738 id_arguments = rb_intern_const("arguments");
4739 id_memo = rb_intern_const("memo");
4740 id_method = rb_intern_const("method");
4741 id_force = rb_intern_const("force");
4742 id_to_enum = rb_intern_const("to_enum");
4743 id_each_entry = rb_intern_const("each_entry");
4744 sym_each = ID2SYM(id_each);
4745 sym_yield = ID2SYM(rb_intern_const("yield"));
4746
4747 InitVM(Enumerator);
4748}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1695
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2868
void rb_need_block(void)
Declares that the current method needs a block.
Definition eval.c:1042
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2680
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3171
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3158
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1034
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1021
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2947
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition eval.c:1050
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
void rb_iter_break(void)
Breaks from a block.
Definition vm.c:2283
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1435
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:181
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1482
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1433
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_cEnumerator
Enumerator class.
Definition enumerator.c:164
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:198
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
VALUE rb_cRange
Range class.
Definition range.c:31
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:923
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3306
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1117
VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE procval)
Identical to rb_funcallv_public(), except you can pass a block.
Definition vm_eval.c:1194
#define rb_funcall2
Definition eval.h:207
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:362
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
VALUE rb_enumerator_size_func(VALUE recv, VALUE argv, VALUE eobj)
This is the type of functions that rb_enumeratorize_with_size() expects.
Definition enumerator.h:45
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:486
VALUE rb_obj_method(VALUE recv, VALUE mid)
Creates a method object.
Definition proc.c:2269
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:983
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1169
VALUE rb_proc_call_kw(VALUE recv, VALUE args, int kw_splat)
Identical to rb_proc_call(), except you can specify how to handle the last element of the given array...
Definition proc.c:1125
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:120
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1862
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3800
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1997
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3766
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3390
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1776
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5615
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1505
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3471
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1719
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:686
VALUE rb_check_funcall_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_check_funcall(), except you can specify how to handle the last element of the given a...
Definition vm_eval.c:680
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:993
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12675
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12665
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
int len
Length of the buffer.
Definition io.h:8
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1395
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1417
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
VALUE rb_yield_values_kw(int n, const VALUE *argv, int kw_splat)
Identical to rb_yield_values2(), except you can specify how to handle the last element of the given a...
Definition vm_eval.c:1423
VALUE rb_block_call_func(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
This is the type of a function that the interpreter expect for C-backended blocks.
Definition iterator.h:83
VALUE rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE *argv, rb_block_call_func_t proc, VALUE data2, int kw_splat)
Identical to rb_funcallv_kw(), except it additionally passes a function as a block.
Definition vm_eval.c:1570
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RB_SCAN_ARGS_LAST_HASH_KEYWORDS
Treat a final argument as keywords if it is a hash, and not as keywords otherwise.
Definition scan_args.h:59
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
MEMO.
Definition imemo.h:105
Definition enumerator.c:237
Decomposed Enumerator::ArithmeicSequence.
Definition enumerator.h:53
int exclude_end
Whether the endpoint is open or closed.
Definition enumerator.h:57
VALUE end
"Right" or "highest" endpoint of the sequence.
Definition enumerator.h:55
VALUE step
Step between a sequence.
Definition enumerator.h:56
VALUE begin
"Left" or "lowest" endpoint of the sequence.
Definition enumerator.h:54
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40