Sha256: 0529d422e28c4f2a6bef5655ee88f5a5c316f975c67a2508a441917284e5ae3b

Contents?: true

Size: 1.57 KB

Versions: 11

Compression:

Stored size: 1.57 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Lint
      # Checks for space between a the name of a called method and a left
      # parenthesis.
      #
      # @example
      #
      #   puts (x + y)
      class ParenthesesAsGroupedExpression < Cop
        MSG = '`(...)` interpreted as grouped expression.'

        def on_send(node)
          _receiver, method_name, args = *node
          return if operator?(method_name) || method_name.to_s.end_with?('=')
          return unless args && args.loc.expression.source.start_with?('(')

          space_length = spaces_before_left_parenthesis(node)
          return unless space_length > 0
          expr = args.loc.expression
          space_range =
            Parser::Source::Range.new(expr.source_buffer,
                                      expr.begin_pos - space_length,
                                      expr.begin_pos)

          add_offense(nil, space_range)
        end

        private

        def spaces_before_left_parenthesis(node)
          receiver, method_name, _args = *node
          receiver_length = if receiver
                              receiver.loc.expression.source.length
                            else
                              0
                            end
          without_receiver = node.loc.expression.source[receiver_length..-1]

          # Escape question mark if any.
          method_regexp = Regexp.escape(method_name)

          match = without_receiver.match(/^\s*\.?\s*#{method_regexp}(\s+)\(/)
          match ? match.captures[0].length : 0
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
rubocop-0.34.2 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.34.1 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.34.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.33.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.32.1 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.32.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.31.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.30.1 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.30.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.29.1 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
rubocop-0.29.0 lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb