Sha256: f34b2c80a5db8a4f4cdf889342c081a44a816089b803110f74127ce74d35200e

Contents?: true

Size: 1.62 KB

Versions: 8

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

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

8 entries across 8 versions & 1 rubygems

Version Path
mutant-0.8.24 lib/mutant/expression/parser.rb
mutant-0.8.23 lib/mutant/expression/parser.rb
mutant-0.8.22 lib/mutant/expression/parser.rb
mutant-0.8.21 lib/mutant/expression/parser.rb
mutant-0.8.20 lib/mutant/expression/parser.rb
mutant-0.8.19 lib/mutant/expression/parser.rb
mutant-0.8.18 lib/mutant/expression/parser.rb
mutant-0.8.17 lib/mutant/expression/parser.rb