Sha256: aa4c0642fabee24e46e50d63e73584b8c1fe91aafc51dabe61e6626bac038d5b

Contents?: true

Size: 1.84 KB

Versions: 9

Compression:

Stored size: 1.84 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Ext
    # Extensions to AST::RegexpNode for our cached parsed regexp info
    module RegexpNode
      ANY = Object.new
      def ANY.==(_)
        true
      end
      private_constant :ANY

      # @return [Regexp::Expression::Root, nil]
      # Note: we extend Regexp nodes to provide `loc` and `expression`
      # see `ext/regexp_parser`.
      attr_reader :parsed_tree

      def assign_properties(*)
        super

        str = with_interpolations_blanked
        @parsed_tree = begin
          Regexp::Parser.parse(str, options: options)
        rescue StandardError
          nil
        end
        origin = loc.begin.end
        @parsed_tree&.each_expression(true) { |e| e.origin = origin }
      end

      def each_capture(named: ANY)
        return enum_for(__method__, named: named) unless block_given?

        parsed_tree&.traverse do |event, exp, _index|
          yield(exp) if named_capturing?(exp, event, named)
        end

        self
      end

      private

      def named_capturing?(exp, event, named)
        event == :enter &&
          named == exp.respond_to?(:name) &&
          !exp.text.start_with?('(?<=') &&
          exp.respond_to?(:capturing?) &&
          exp.capturing?
      end

      def with_interpolations_blanked
        # Ignore the trailing regopt node
        children[0...-1].map do |child|
          source = child.source

          # We don't want to consider the contents of interpolations as part of the pattern source,
          # but need to preserve their width, to allow offsets to correctly line up with the
          # original source: spaces have no effect, and preserve width.
          if child.begin_type?
            ' ' * source.length
          else
            source
          end
        end.join
      end

      AST::RegexpNode.include self
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rubocop-1.70.0 lib/rubocop/ext/regexp_node.rb
rubocop-1.69.2 lib/rubocop/ext/regexp_node.rb
rubocop-1.69.1 lib/rubocop/ext/regexp_node.rb
rubocop-1.69.0 lib/rubocop/ext/regexp_node.rb
rubocop-1.68.0 lib/rubocop/ext/regexp_node.rb
rubocop-1.67.0 lib/rubocop/ext/regexp_node.rb
rubocop-1.66.1 lib/rubocop/ext/regexp_node.rb
rubocop-1.66.0 lib/rubocop/ext/regexp_node.rb
rubocop-1.65.1 lib/rubocop/ext/regexp_node.rb