Sha256: 550974de8e9547f8eaa2e440f3a0b1ec8ece2934d119fbec52949a2cd1a95a70

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

module Regexp::Expression
  module Conditional
    class TooManyBranches < StandardError
      def initialize
        super('The conditional expression has more than 2 branches')
      end
    end

    class Condition < Regexp::Expression::Base
      attr_accessor :referenced_expression

      # Name or number of the referenced capturing group that determines state.
      # Returns a String if reference is by name, Integer if by number.
      def reference
        ref = text.tr("'<>()", "")
        ref =~ /\D/ ? ref : Integer(ref)
      end
    end

    class Branch < Regexp::Expression::Sequence; end

    class Expression < Regexp::Expression::Subexpression
      attr_accessor :referenced_expression

      def <<(exp)
        expressions.last << exp
      end

      def add_sequence
        raise TooManyBranches.new if branches.length == 2
        Branch.add_to(self, { conditional_level: conditional_level + 1 })
      end
      alias :branch :add_sequence

      def condition=(exp)
        expressions.delete(condition)
        expressions.unshift(exp)
      end

      def condition
        find { |subexp| subexp.is_a?(Condition) }
      end

      def branches
        select { |subexp| subexp.is_a?(Sequence) }
      end

      def reference
        condition.reference
      end

      def to_s(format = :full)
        "#{text}#{condition}#{branches.join('|')})#{quantifier_affix(format)}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
regexp_parser-1.5.0 lib/regexp_parser/expression/classes/conditional.rb