Module: L43Peg::Combinators::Many

Extended by:
Many
Includes:
Helper
Included in:
Many
Defined in:
lib/l43_peg/combinators/many.rb

Instance Method Summary collapse

Methods included from Helper

#fail_parser, #succeed_parser

Instance Method Details

#many(input:, cache:, name:, parser:, min:, max:) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/l43_peg/combinators/many.rb', line 9

def many(input:, cache:, name:, parser:, min:, max:)
  curr_input = input
  curr_cache = cache
  count = 0
  ast   = []

  loop do
    if max && count == max
      return succeed_parser(ast, curr_input, cache: curr_cache)
    end
    case parser.(curr_input, cache: curr_cache)
    in L43Peg::Success => success
      ast.push(success.ast)
      curr_input = success.rest
      curr_cache = success.cache
      count += 1
    in L43Peg::Failure
      if count < min
        return fail_parser("many #{name} should match at least #{min} times but did only #{count} times", input:)
      end
      return succeed_parser(ast, curr_input, cache: curr_cache)
    in L43Peg::Stop
      if count < min
        return fail_parser("many #{name} should match at least #{min} times but did only #{count} times", input:)
      end
      return succeed_parser(ast, curr_input.drop, cache: curr_cache)
    end
  end
end