Class: Yaparc::Seq

Inherits:
Object
  • Object
show all
Includes:
Parsable
Defined in:
lib/yaparc.rb

Constant Summary

Constants included from Parsable

Parsable::IS_ALPHANUM, Parsable::IS_CR, Parsable::IS_DIGIT, Parsable::IS_LOWER, Parsable::IS_SPACE, Parsable::IS_WHITESPACE

Instance Attribute Summary

Attributes included from Parsable

#tree

Instance Method Summary collapse

Methods included from Parsable

#parse

Constructor Details

#initialize(*parsers, &block) ⇒ Seq

Returns a new instance of Seq.



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/yaparc.rb', line 148

def initialize(*parsers, &block)
  @parser = lambda do |input|
    args = []
    initial_result = Result::OK.new(:input => input)
    final_result = parsers.inject(initial_result) do |subsequent, parser|
      result = parser.parse(subsequent.input)
      if result.instance_of?(Result::Fail)
        break Result::Fail.new(:input => subsequent.input)
      else
        args << result.value
        result
      end
    end

    case final_result
    when Result::Fail
      Result::Fail.new(:input => final_result.input)
    when Result::OK
      final_value = if block_given?
                      yield(*args)
                    else
                      args.last
                    end
      Result::OK.new(:value => final_value, :input => final_result.input)
    else
      raise
    end
  end
end