Sha256: 745d718645c76d83433d0d7500227aa49ec01e396bbd6024c0b6e294a05bfc42

Contents?: true

Size: 1.77 KB

Versions: 3

Compression:

Stored size: 1.77 KB

Contents

module Regexp::Expression
  module Conditional
    class TooManyBranches < Regexp::Parser::Error
      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

      def initialize_copy(orig)
        self.referenced_expression = orig.referenced_expression.dup
        super
      end

      def referential?
        true
      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(active_opts = {})
        raise TooManyBranches.new if branches.length == 2
        params = { conditional_level: conditional_level + 1 }
        Branch.add_to(self, params, active_opts)
      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 referential?
        true
      end

      def parts
        [text.dup, condition, *intersperse(branches, '|'), ')']
      end

      def initialize_copy(orig)
        self.referenced_expression = orig.referenced_expression.dup
        super
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 3 rubygems

Version Path
call_your_name-0.1.0 vendor/bundle/ruby/3.1.0/gems/regexp_parser-2.7.0/lib/regexp_parser/expression/classes/conditional.rb
zilla-0.2.0 vendor/bundle/ruby/3.2.0/gems/regexp_parser-2.7.0/lib/regexp_parser/expression/classes/conditional.rb
regexp_parser-2.7.0 lib/regexp_parser/expression/classes/conditional.rb