Sha256: d8d9bbd6bc4198907e6bdb88cde5606a39cd7c359e740d4f65e6c1434a67e471

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # This cop enforces the use the shorthand for self-assignment.
      #
      # @example
      #
      #   # bad
      #   x = x + 1
      #
      #   # good
      #   x += 1
      class SelfAssignment < Cop
        include AST::Sexp

        OPS = [:+, :-, :*, :**, :/, :|, :&]

        def on_lvasgn(node)
          check(node, :lvar)
        end

        def on_ivasgn(node)
          check(node, :ivar)
        end

        def on_cvasgn(node)
          check(node, :cvar)
        end

        def check(node, var_type)
          var_name, rhs = *node

          return unless rhs

          if rhs.type == :send
            check_send_node(node, rhs, var_name, var_type)
          elsif [:and, :or].include?(rhs.type)
            check_boolean_node(node, rhs, var_name, var_type)
          end
        end

        def check_send_node(node, rhs, var_name, var_type)
          receiver, method_name, *_args = *rhs

          return unless OPS.include?(method_name)

          target_node = s(var_type, var_name)

          if receiver == target_node
            add_offense(node,
                        :expression,
                        "Use self-assignment shorthand #{method_name}=.")
          end
        end

        def check_boolean_node(node, rhs, var_name, var_type)
          first_operand, _second_operand = *rhs

          target_node = s(var_type, var_name)

          if first_operand == target_node
            operator = rhs.loc.operator.source
            add_offense(node,
                        :expression,
                        "Use self-assignment shorthand #{operator}=.")
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubocop-0.19.1 lib/rubocop/cop/style/self_assignment.rb
rubocop-0.19.0 lib/rubocop/cop/style/self_assignment.rb