Sha256: ba90e769b3516201c477b6ad7f8c75de9b1e6d6cb80091c36f818747cbeda317

Contents?: true

Size: 913 Bytes

Versions: 2

Compression:

Stored size: 913 Bytes

Contents

# Alternative during matching. Contains a list of parslets that is tried each
# one in turn. Only fails if all alternatives fail. 
#
# Example: 
# 
#   str('a') | str('b')   # matches either 'a' or 'b'
#
class Parslet::Atoms::Alternative < Parslet::Atoms::Base
  attr_reader :alternatives
  def initialize(*alternatives)
    @alternatives = alternatives
  end
  
  def |(parslet)
    @alternatives << parslet
    self
  end
  
  def try(io)
    alternatives.each { |a|
      begin
        return a.apply(io)
      rescue Parslet::ParseFailed => ex
      end
    }
    # If we reach this point, all alternatives have failed. 
    error(io, "Expected one of #{alternatives.inspect}.")
  end

  precedence ALTERNATE
  def to_s_inner(prec)
    alternatives.map { |a| a.to_s(prec) }.join(' | ')
  end

  def error_tree
    Parslet::ErrorTree.new(self, *alternatives.
      map { |child| child.error_tree })
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
parslet-0.11.0 lib/parslet/atoms/alternative.rb
parslet-0.10.1 lib/parslet/atoms/alternative.rb