Class: DParse::Parsers::Repeat

Inherits:
DParse::Parser show all
Defined in:
lib/d-parse/parsers/combinators/repeat.rb

Instance Method Summary collapse

Methods inherited from DParse::Parser

#apply, #bind, #capture, #compact, #expectation_message, #first, #flatten, #ignore, #map, #match?, #second, #select_even, #select_odd, #to_s

Constructor Details

#initialize(parser) ⇒ Repeat

Returns a new instance of Repeat.



4
5
6
# File 'lib/d-parse/parsers/combinators/repeat.rb', line 4

def initialize(parser)
  @parser = parser
end

Instance Method Details

#inspectObject



29
30
31
# File 'lib/d-parse/parsers/combinators/repeat.rb', line 29

def inspect
  "repeat(#{@parser})"
end

#read(input, pos) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/d-parse/parsers/combinators/repeat.rb', line 8

def read(input, pos)
  prev_res = Success.new(input, pos, data: [])
  best_failure = nil

  loop do
    new_res = @parser.read(input, prev_res.pos)
    best_failure = find_best_failure(best_failure, new_res)

    if prev_res.pos.index == new_res.pos.index
      return prev_res.with_best_failure(best_failure)
    end

    case new_res
    when Success
      prev_res = new_res.map { |d| prev_res.data + [d] }
    else
      return prev_res.with_best_failure(best_failure)
    end
  end
end