Sha256: 65e782d480343d7f703f6a89019e2d1f911715cf7b78554cae11bc67ddd8d3e3

Contents?: true

Size: 1.58 KB

Versions: 6

Compression:

Stored size: 1.58 KB

Contents

module Mutant
  class Expression
    class Parser
      include Concord.new(:types)

      class ParserError < RuntimeError
        include AbstractType
      end # ParserError

      # Error raised on invalid expressions
      class InvalidExpressionError < ParserError; end

      # Error raised on ambiguous expressions
      class AmbiguousExpressionError < ParserError; end

      # Parse input into expression or raise
      #
      # @param [String] syntax
      #
      # @return [Expression]
      #   if expression is valid
      #
      # @raise [ParserError]
      #   otherwise
      def call(input)
        try_parse(input) or fail InvalidExpressionError, "Expression: #{input.inspect} is not valid"
      end

      # Try to parse input into expression
      #
      # @param [String] input
      #
      # @return [Expression]
      #   if expression is valid
      #
      # @return [nil]
      #   otherwise
      def try_parse(input)
        expressions = expressions(input)
        case expressions.length
        when 0, 1
          expressions.first
        else
          fail AmbiguousExpressionError, "Ambiguous expression: #{input.inspect}"
        end
      end

    private

      # Expressions parsed from input
      #
      # @param [String] input
      #
      # @return [Array<Expression>]
      #   if expressions can be parsed from input
      def expressions(input)
        types.each_with_object([]) do |type, aggregate|
          expression = type.try_parse(input)
          aggregate << expression if expression
        end
      end

    end # Parser
  end # Expression
end # Mutant

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mutant-0.8.16 lib/mutant/expression/parser.rb
mutant-0.8.15 lib/mutant/expression/parser.rb
mutant-0.8.14 lib/mutant/expression/parser.rb
mutant-0.8.13 lib/mutant/expression/parser.rb
mutant-0.8.12 lib/mutant/expression/parser.rb
mutant-0.8.11 lib/mutant/expression/parser.rb