Class: TRuby::ParserCombinator::Choice

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

Overview

Choice: try multiple parsers in order

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(*parsers) ⇒ Choice

Returns a new instance of Choice.



486
487
488
# File 'lib/t_ruby/parser_combinator.rb', line 486

def initialize(*parsers)
  @parsers = parsers
end

Instance Method Details

#parse(input, position = 0) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/t_ruby/parser_combinator.rb', line 490

def parse(input, position = 0)
  best_error = nil
  best_position = position

  @parsers.each do |parser|
    result = parser.parse(input, position)
    return result if result.success?

    if result.position >= best_position
      best_error = result.error
      best_position = result.position
    end
  end

  ParseResult.failure(best_error || "No alternative matched", input, best_position)
end