Class: TRuby::ParserCombinator::ChainLeft

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

Overview

Chainl: left-associative chain

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(term, op) ⇒ ChainLeft

Returns a new instance of ChainLeft.



506
507
508
509
# File 'lib/t_ruby/parser_combinator.rb', line 506

def initialize(term, op)
  @term = term
  @op = op
end

Instance Method Details

#parse(input, position = 0) ⇒ Object



511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/t_ruby/parser_combinator.rb', line 511

def parse(input, position = 0)
  first = @term.parse(input, position)
  return first if first.failure?

  result = first.value
  current_pos = first.position

  loop do
    op_result = @op.parse(input, current_pos)
    break if op_result.failure?

    term_result = @term.parse(input, op_result.position)
    break if term_result.failure?

    result = op_result.value.call(result, term_result.value)
    current_pos = term_result.position
  end

  ParseResult.success(result, input, current_pos)
end