Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-enumerator/mrblib/enumerator.rb

raw
1 ##
2 # enumerator.rb Enumerator class
3 # See Copyright Notice in mruby.h
4
5 ##
6 # A class which allows both internal and external iteration.
7 #
8 # An Enumerator can be created by the following methods.
9 # - {Kernel#to_enum}
10 # - {Kernel#enum_for}
11 # - {Enumerator#initialize Enumerator.new}
12 #
13 # Most methods have two forms: a block form where the contents
14 # are evaluated for each item in the enumeration, and a non-block form
15 # which returns a new Enumerator wrapping the iteration.
16 #
17 # enumerator = %w(one two three).each
18 # puts enumerator.class # => Enumerator
19 #
20 # enumerator.each_with_object("foo") do |item, obj|
21 # puts "#{obj}: #{item}"
22 # end
23 #
24 # # foo: one
25 # # foo: two
26 # # foo: three
27 #
28 # enum_with_obj = enumerator.each_with_object("foo")
29 # puts enum_with_obj.class # => Enumerator
30 #
31 # enum_with_obj.each do |item, obj|
32 # puts "#{obj}: #{item}"
33 # end
34 #
35 # # foo: one
36 # # foo: two
37 # # foo: three
38 #
39 # This allows you to chain Enumerators together. For example, you
40 # can map a list's elements to strings containing the index
41 # and the element as a string via:
42 #
43 # puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" }
44 # # => ["0:foo", "1:bar", "2:baz"]
45 #
46 # An Enumerator can also be used as an external iterator.
47 # For example, Enumerator#next returns the next value of the iterator
48 # or raises StopIteration if the Enumerator is at the end.
49 #
50 # e = [1,2,3].each # returns an enumerator object.
51 # puts e.next # => 1
52 # puts e.next # => 2
53 # puts e.next # => 3
54 # puts e.next # raises StopIteration
55 #
56 # You can use this to implement an internal iterator as follows:
57 #
58 # def ext_each(e)
59 # while true
60 # begin
61 # vs = e.next_values
62 # rescue StopIteration
63 # return $!.result
64 # end
65 # y = yield(*vs)
66 # e.feed y
67 # end
68 # end
69 #
70 # o = Object.new
71 #
72 # def o.each
73 # puts yield
74 # puts yield(1)
75 # puts yield(1, 2)
76 # 3
77 # end
78 #
79 # # use o.each as an internal iterator directly.
80 # puts o.each {|*x| puts x; [:b, *x] }
81 # # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
82 #
83 # # convert o.each to an external iterator for
84 # # implementing an internal iterator.
85 # puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] }
86 # # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
87 #
88 class Enumerator
89 include Enumerable
90
91 ##
92 # @overload initialize(obj, method = :each, *args, **kwd)
93 #
94 # Creates a new Enumerator object, which can be used as an
95 # Enumerable.
96 #
97 # In the first form, iteration is defined by the given block, in
98 # which a "yielder" object, given as block parameter, can be used to
99 # yield a value by calling the +yield+ method (aliased as +<<+):
100 #
101 # fib = Enumerator.new do |y|
102 # a = b = 1
103 # loop do
104 # y << a
105 # a, b = b, a + b
106 # end
107 # end
108 #
109 # p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
110 #
111 # In the second, deprecated, form, a generated Enumerator iterates over the
112 # given object using the given method with the given arguments passed. This
113 # form is left only for internal use.
114 #
115 # Use of this form is discouraged. Use Kernel#enum_for or Kernel#to_enum
116 # instead.
117 def initialize(obj=NONE, meth=:each, *args, **kwd, &block)
118 if block
119 obj = Generator.new(&block)
120 elsif obj == NONE
121 raise ArgumentError, "wrong number of arguments (given 0, expected 1+)"
122 end
123
124 @obj = obj
125 @meth = meth
126 @args = args
127 @kwd = kwd
128 @fib = nil
129 @dst = nil
130 @lookahead = nil
131 @feedvalue = nil
132 @stop_exc = false
133 end
134
135 attr_accessor :obj, :meth, :args, :kwd
136 attr_reader :fib
137
138 def initialize_copy(obj)
139 raise TypeError, "can't copy type #{obj.class}" unless obj.kind_of? Enumerator
140 raise TypeError, "can't copy execution context" if obj.fib
141 @obj = obj.obj
142 @meth = obj.meth
143 @args = obj.args
144 @kwd = obj.kwd
145 @fib = nil
146 @lookahead = nil
147 @feedvalue = nil
148 self
149 end
150
151 ##
152 # call-seq:
153 # e.with_index(offset = 0) {|(*args), idx| ... }
154 # e.with_index(offset = 0)
155 #
156 # Iterates the given block for each element with an index, which
157 # starts from +offset+. If no block is given, returns a new Enumerator
158 # that includes the index, starting from +offset+
159 #
160 # +offset+:: the starting index to use
161 #
162 def with_index(offset=0, &block)
163 return to_enum :with_index, offset unless block
164
165 if offset.nil?
166 offset = 0
167 else
168 offset = offset.__to_int
169 end
170
171 n = offset - 1
172 enumerator_block_call do |*i|
173 n += 1
174 block.call i.__svalue, n
175 end
176 end
177
178 ##
179 # call-seq:
180 # e.each_with_index {|(*args), idx| ... }
181 # e.each_with_index
182 #
183 # Same as Enumerator#with_index(0), i.e. there is no starting offset.
184 #
185 # If no block is given, a new Enumerator is returned that includes the index.
186 #
187 def each_with_index(&block)
188 with_index(0, &block)
189 end
190
191 ##
192 # call-seq:
193 # e.each_with_object(obj) {|(*args), obj| ... }
194 # e.each_with_object(obj)
195 # e.with_object(obj) {|(*args), obj| ... }
196 # e.with_object(obj)
197 #
198 # Iterates the given block for each element with an arbitrary object, +obj+,
199 # and returns +obj+
200 #
201 # If no block is given, returns a new Enumerator.
202 #
203 # @example
204 # to_three = Enumerator.new do |y|
205 # 3.times do |x|
206 # y << x
207 # end
208 # end
209 #
210 # to_three_with_string = to_three.with_object("foo")
211 # to_three_with_string.each do |x,string|
212 # puts "#{string}: #{x}"
213 # end
214 #
215 # # => foo:0
216 # # => foo:1
217 # # => foo:2
218 #
219 def with_object(object, &block)
220 return to_enum(:with_object, object) unless block
221
222 enumerator_block_call do |i|
223 block.call [i,object]
224 end
225 object
226 end
227
228 def inspect
229 if @args && @args.size > 0
230 args = @args.join(", ")
231 "#<#{self.class}: #{@obj.inspect}:#{@meth}(#{args})>"
232 else
233 "#<#{self.class}: #{@obj.inspect}:#{@meth}>"
234 end
235 end
236
237 ##
238 # call-seq:
239 # enum.each { |elm| block } -> obj
240 # enum.each -> enum
241 # enum.each(*appending_args) { |elm| block } -> obj
242 # enum.each(*appending_args) -> an_enumerator
243 #
244 # Iterates over the block according to how this Enumerator was constructed.
245 # If no block and no arguments are given, returns self.
246 #
247 # === Examples
248 #
249 # Array.new(3) #=> [nil, nil, nil]
250 # Array.new(3) { |i| i } #=> [0, 1, 2]
251 # Array.to_enum(:new, 3).to_a #=> [0, 1, 2]
252 # Array.to_enum(:new).each(3).to_a #=> [0, 1, 2]
253 #
254 # obj = Object.new
255 #
256 # def obj.each_arg(a, b=:b, *rest)
257 # yield a
258 # yield b
259 # yield rest
260 # :method_returned
261 # end
262 #
263 # enum = obj.to_enum :each_arg, :a, :x
264 #
265 # enum.each.to_a #=> [:a, :x, []]
266 # enum.each.equal?(enum) #=> true
267 # enum.each { |elm| elm } #=> :method_returned
268 #
269 # enum.each(:y, :z).to_a #=> [:a, :x, [:y, :z]]
270 # enum.each(:y, :z).equal?(enum) #=> false
271 # enum.each(:y, :z) { |elm| elm } #=> :method_returned
272 #
273 def each(*argv, &block)
274 obj = self
275 if 0 < argv.length
276 obj = self.dup
277 args = obj.args
278 if !args.empty?
279 args = args.dup
280 args.concat argv
281 else
282 args = argv.dup
283 end
284 obj.args = args
285 end
286 return obj unless block
287 enumerator_block_call(&block)
288 end
289
290 def enumerator_block_call(&block)
291 @obj.__send__ @meth, *@args, **@kwd, &block
292 end
293 private :enumerator_block_call
294
295 ##
296 # call-seq:
297 # e.next -> object
298 #
299 # Returns the next object in the enumerator, and move the internal position
300 # forward. When the position reached at the end, StopIteration is raised.
301 #
302 # === Example
303 #
304 # a = [1,2,3]
305 # e = a.to_enum
306 # p e.next #=> 1
307 # p e.next #=> 2
308 # p e.next #=> 3
309 # p e.next #raises StopIteration
310 #
311 # Note that enumeration sequence by +next+ does not affect other non-external
312 # enumeration methods, unless the underlying iteration methods itself has
313 # side-effect
314 #
315 def next
316 next_values.__svalue
317 end
318
319 ##
320 # call-seq:
321 # e.next_values -> array
322 #
323 # Returns the next object as an array in the enumerator, and move the
324 # internal position forward. When the position reached at the end,
325 # StopIteration is raised.
326 #
327 # This method can be used to distinguish <code>yield</code> and <code>yield
328 # nil</code>.
329 #
330 # === Example
331 #
332 # o = Object.new
333 # def o.each
334 # yield
335 # yield 1
336 # yield 1, 2
337 # yield nil
338 # yield [1, 2]
339 # end
340 # e = o.to_enum
341 # p e.next_values
342 # p e.next_values
343 # p e.next_values
344 # p e.next_values
345 # p e.next_values
346 # e = o.to_enum
347 # p e.next
348 # p e.next
349 # p e.next
350 # p e.next
351 # p e.next
352 #
353 # ## yield args next_values next
354 # # yield [] nil
355 # # yield 1 [1] 1
356 # # yield 1, 2 [1, 2] [1, 2]
357 # # yield nil [nil] nil
358 # # yield [1, 2] [[1, 2]] [1, 2]
359 #
360 # Note that +next_values+ does not affect other non-external enumeration
361 # methods unless underlying iteration method itself has side-effect
362 #
363 def next_values
364 if @lookahead
365 vs = @lookahead
366 @lookahead = nil
367 return vs
368 end
369 raise @stop_exc if @stop_exc
370
371 curr = Fiber.current
372
373 if !@fib || [email protected]?
374 @dst = curr
375 @fib = Fiber.new do
376 result = each do |*args|
377 feedvalue = nil
378 Fiber.yield args
379 if @feedvalue
380 feedvalue = @feedvalue
381 @feedvalue = nil
382 end
383 feedvalue
384 end
385 @stop_exc = StopIteration.new "iteration reached an end"
386 @stop_exc.result = result
387 Fiber.yield nil
388 end
389 @lookahead = nil
390 end
391
392 vs = @fib.resume curr
393 if @stop_exc
394 @fib = nil
395 @dst = nil
396 @lookahead = nil
397 @feedvalue = nil
398 raise @stop_exc
399 end
400 vs
401 end
402
403 ##
404 # call-seq:
405 # e.peek -> object
406 #
407 # Returns the next object in the enumerator, but doesn't move the internal
408 # position forward. If the position is already at the end, StopIteration
409 # is raised.
410 #
411 # === Example
412 #
413 # a = [1,2,3]
414 # e = a.to_enum
415 # p e.next #=> 1
416 # p e.peek #=> 2
417 # p e.peek #=> 2
418 # p e.peek #=> 2
419 # p e.next #=> 2
420 # p e.next #=> 3
421 # p e.next #raises StopIteration
422 #
423 def peek
424 peek_values.__svalue
425 end
426
427 ##
428 # call-seq:
429 # e.peek_values -> array
430 #
431 # Returns the next object as an array, similar to Enumerator#next_values, but
432 # doesn't move the internal position forward. If the position is already at
433 # the end, StopIteration is raised.
434 #
435 # === Example
436 #
437 # o = Object.new
438 # def o.each
439 # yield
440 # yield 1
441 # yield 1, 2
442 # end
443 # e = o.to_enum
444 # p e.peek_values #=> []
445 # e.next
446 # p e.peek_values #=> [1]
447 # p e.peek_values #=> [1]
448 # e.next
449 # p e.peek_values #=> [1, 2]
450 # e.next
451 # p e.peek_values # raises StopIteration
452 #
453 def peek_values
454 if @lookahead.nil?
455 @lookahead = next_values
456 end
457 @lookahead.dup
458 end
459
460 ##
461 # call-seq:
462 # e.rewind -> e
463 #
464 # Rewinds the enumeration sequence to the beginning.
465 #
466 # If the enclosed object responds to a "rewind" method, it is called.
467 #
468 def rewind
469 @obj.rewind if @obj.respond_to? :rewind
470 @fib = nil
471 @dst = nil
472 @lookahead = nil
473 @feedvalue = nil
474 @stop_exc = false
475 self
476 end
477
478 ##
479 # call-seq:
480 # e.feed obj -> nil
481 #
482 # Sets the value to be returned by the next yield inside +e+.
483 #
484 # If the value is not set, the yield returns nil.
485 #
486 # This value is cleared after being yielded.
487 #
488 # # Array#map passes the array's elements to "yield" and collects the
489 # # results of "yield" as an array.
490 # # Following example shows that "next" returns the passed elements and
491 # # values passed to "feed" are collected as an array which can be
492 # # obtained by StopIteration#result.
493 # e = [1,2,3].map
494 # p e.next #=> 1
495 # e.feed "a"
496 # p e.next #=> 2
497 # e.feed "b"
498 # p e.next #=> 3
499 # e.feed "c"
500 # begin
501 # e.next
502 # rescue StopIteration
503 # p $!.result #=> ["a", "b", "c"]
504 # end
505 #
506 # o = Object.new
507 # def o.each
508 # x = yield # (2) blocks
509 # p x # (5) => "foo"
510 # x = yield # (6) blocks
511 # p x # (8) => nil
512 # x = yield # (9) blocks
513 # p x # not reached w/o another e.next
514 # end
515 #
516 # e = o.to_enum
517 # e.next # (1)
518 # e.feed "foo" # (3)
519 # e.next # (4)
520 # e.next # (7)
521 # # (10)
522 #
523 def feed(value)
524 raise TypeError, "feed value already set" if @feedvalue
525 @feedvalue = value
526 nil
527 end
528
529 # just for internal
530 class Generator
531 include Enumerable
532 def initialize(&block)
533 raise TypeError, "wrong argument type #{self.class} (expected Proc)" unless block.kind_of? Proc
534
535 @proc = block
536 end
537
538 def each(*args, &block)
539 args.unshift Yielder.new(&block)
540 @proc.call(*args)
541 end
542 end
543
544 # just for internal
545 class Yielder
546 def initialize(&block)
547 raise LocalJumpError, "no block given" unless block
548
549 @proc = block
550 end
551
552 def yield(*args)
553 @proc.call(*args)
554 end
555
556 def << *args
557 self.yield(*args)
558 self
559 end
560 end
561
562 ##
563 # call-seq:
564 # Enumerator.produce(initial = nil) { |val| } -> enumerator
565 #
566 # Creates an infinite enumerator from any block, just called over and
567 # over. Result of the previous iteration is passed to the next one.
568 # If +initial+ is provided, it is passed to the first iteration, and
569 # becomes the first element of the enumerator; if it is not provided,
570 # first iteration receives +nil+, and its result becomes first
571 # element of the iterator.
572 #
573 # Raising StopIteration from the block stops an iteration.
574 #
575 # Examples of usage:
576 #
577 # Enumerator.produce(1, &:succ) # => enumerator of 1, 2, 3, 4, ...
578 #
579 # Enumerator.produce { rand(10) } # => infinite random number sequence
580 #
581 # ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
582 # enclosing_section = ancestors.find { |n| n.type == :section }
583 def Enumerator.produce(init=NONE, &block)
584 raise ArgumentError, "no block given" if block.nil?
585 Enumerator.new do |y|
586 if init == NONE
587 val = nil
588 else
589 val = init
590 y.yield(val)
591 end
592 begin
593 while true
594 y.yield(val = block.call(val))
595 end
596 rescue StopIteration
597 # do nothing
598 end
599 end
600 end
601 end
602
603 module Kernel
604 ##
605 # call-seq:
606 # obj.to_enum(method = :each, *args) -> enum
607 # obj.enum_for(method = :each, *args) -> enum
608 #
609 # Creates a new Enumerator which will enumerate by calling +method+ on
610 # +obj+, passing +args+ if any.
611 #
612 # === Examples
613 #
614 # str = "xyz"
615 #
616 # enum = str.enum_for(:each_byte)
617 # enum.each { |b| puts b }
618 # # => 120
619 # # => 121
620 # # => 122
621 #
622 # # protect an array from being modified by some_method
623 # a = [1, 2, 3]
624 # some_method(a.to_enum)
625 #
626 # It is typical to call to_enum when defining methods for
627 # a generic Enumerable, in case no block is passed.
628 #
629 # Here is such an example with parameter passing:
630 #
631 # module Enumerable
632 # # a generic method to repeat the values of any enumerable
633 # def repeat(n)
634 # raise ArgumentError, "#{n} is negative!" if n < 0
635 # unless block_given?
636 # return to_enum(__callee__, n) do # __callee__ is :repeat here
637 # end
638 # each do |*val|
639 # n.times { yield *val }
640 # end
641 # end
642 # end
643 #
644 # %i[hello world].repeat(2) { |w| puts w }
645 # # => Prints 'hello', 'hello', 'world', 'world'
646 # enum = (1..14).repeat(3)
647 # # => returns an Enumerator when called without a block
648 # enum.first(4) # => [1, 1, 1, 2]
649 #
650 def to_enum(meth=:each, *args)
651 Enumerator.new self, meth, *args
652 end
653 alias enum_for to_enum
654 end
655
656 module Enumerable
657 # use Enumerator to use infinite sequence
658 def zip(*args, &block)
659 args = args.map do |a|
660 if a.respond_to?(:each)
661 a.to_enum(:each)
662 else
663 raise TypeError, "wrong argument type #{a.class} (must respond to :each)"
664 end
665 end
666
667 result = block ? nil : []
668
669 each do |*val|
670 tmp = [val.__svalue]
671 args.each do |arg|
672 v = if arg.nil?
673 nil
674 else
675 begin
676 arg.next
677 rescue StopIteration
678 nil
679 end
680 end
681 tmp.push(v)
682 end
683 if result.nil?
684 block.call(tmp)
685 else
686 result.push(tmp)
687 end
688 end
689
690 result
691 end
692 end