Sha256: 9b844e02275d3a700f85cdbd6729cd24424b454e55a0ae536234c95f8606c9a6

Contents?: true

Size: 1.81 KB

Versions: 13

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    # Help methods for working with nodes containing comments.
    module CommentsHelp
      def source_range_with_comment(node)
        begin_pos = begin_pos_with_comment(node)
        end_pos = end_position_for(node)

        Parser::Source::Range.new(buffer, begin_pos, end_pos)
      end

      def contains_comments?(node)
        start_line = node.source_range.line
        end_line = find_end_line(node)

        processed_source.each_comment_in_lines(start_line...end_line).any?
      end

      private

      def end_position_for(node)
        end_line = buffer.line_for_position(node.loc.expression.end_pos)
        buffer.line_range(end_line).end_pos
      end

      def begin_pos_with_comment(node)
        first_comment = processed_source.ast_with_comments[node].first

        if first_comment && (first_comment.loc.line < node.loc.line)
          start_line_position(first_comment)
        else
          start_line_position(node)
        end
      end

      def start_line_position(node)
        buffer.line_range(node.loc.line).begin_pos - 1
      end

      def buffer
        processed_source.buffer
      end

      # Returns the end line of a node, which might be a comment and not part of the AST
      # End line is considered either the line at which another node starts, or
      # the line at which the parent node ends.
      # rubocop:disable Metrics/AbcSize
      def find_end_line(node)
        if node.if_type? && node.loc.else
          node.loc.else.line
        elsif (next_sibling = node.right_sibling)
          next_sibling.loc.line
        elsif (parent = node.parent)
          parent.loc.end ? parent.loc.end.line : parent.loc.line
        else
          node.loc.end.line
        end
      end
      # rubocop:enable Metrics/AbcSize
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.31.2/lib/rubocop/cop/mixin/comments_help.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.31.2/lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.32.0 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.31.2 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.31.1 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.31.0 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.30.1 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.30.0 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.29.1 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.29.0 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.28.2 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.28.1 lib/rubocop/cop/mixin/comments_help.rb
rubocop-1.28.0 lib/rubocop/cop/mixin/comments_help.rb