Class: TRuby::ParserCombinator::SepBy

Inherits:
Parser
  • Object
show all
Defined in:
lib/t_ruby/parser_combinator/combinators/sep_by.rb

Overview

Separated by delimiter

Instance Method Summary collapse

Methods inherited from Parser

#<<, #>>, #between, #flat_map, #label, #lookahead, #many, #many1, #map, #not_followed_by, #optional, #sep_by, #sep_by1, #|

Constructor Details

#initialize(parser, delimiter) ⇒ SepBy

Returns a new instance of SepBy.



7
8
9
10
# File 'lib/t_ruby/parser_combinator/combinators/sep_by.rb', line 7

def initialize(parser, delimiter)
  @parser = parser
  @delimiter = delimiter
end

Instance Method Details

#parse(input, position = 0) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/t_ruby/parser_combinator/combinators/sep_by.rb', line 12

def parse(input, position = 0)
  first = @parser.parse(input, position)
  return ParseResult.success([], input, position) if first.failure?

  results = [first.value]
  current_pos = first.position

  loop do
    delim_result = @delimiter.parse(input, current_pos)
    break if delim_result.failure?

    item_result = @parser.parse(input, delim_result.position)
    break if item_result.failure?

    results << item_result.value
    current_pos = item_result.position
  end

  ParseResult.success(results, input, current_pos)
end