123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::UselessAssignment

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/lint/useless_assignment.rb

Overview

Checks for every useless assignment to local variable in every scope. The basic idea for this cop was from the warning of ruby -cw:

assigned but unused variable - foo

Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc.

Note
Given the assignment foo = 1, bar = 2, removing unused variables can lead to a syntax error, so this case is not autocorrected.

Examples:

# bad
def some_method
  some_var = 1
  do_something
end

# good
def some_method
  some_var = 1
  do_something(some_var)
end

Cop Safety Information:

  • This cop’s autocorrection is unsafe because removing assignment from operator assignment can cause NameError if this assignment has been used to declare local variable. For example, replacing a ||= 1 to a || 1 may cause "undefined local variable or method `a' for main:Object (NameError)".

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns an url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Class Method Details

.joining_forces

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 48

def self.joining_forces
  VariableForce
end

Instance Method Details

#after_leaving_scope(scope, _variable_table)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 52

def after_leaving_scope(scope, _variable_table)
  scope.variables.each_value { |variable| check_for_unused_assignments(variable) }
end

#autocorrect(corrector, assignment)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 158

def autocorrect(corrector, assignment)
  if assignment.exception_assignment?
    remove_exception_assignment_part(corrector, assignment.node)
  elsif assignment.multiple_assignment? || assignment.rest_assignment? ||
        assignment.for_assignment?
    rename_variable_with_underscore(corrector, assignment.node)
  elsif assignment.operator_assignment?
    remove_trailing_character_from_operator(corrector, assignment.node)
  elsif assignment.regexp_named_capture?
    replace_named_capture_group_with_non_capturing_group(corrector, assignment.node,
                                                         assignment.variable.name)
  else
    remove_local_variable_assignment_part(corrector, assignment.node)
  end
end

#chained_assignment?(node) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 99

def chained_assignment?(node)
  node.respond_to?(:expression) && node.expression&.lvasgn_type?
end

#check_for_unused_assignments(variable)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 57

def check_for_unused_assignments(variable)
  return if variable.should_be_unused?

  variable.assignments.each do |assignment|
    next if assignment.used? || part_of_ignored_node?(assignment.node)

    message = message_for_useless_assignment(assignment)
    range = offense_range(assignment)

    add_offense(range, message: message) do |corrector|
      autocorrect(corrector, assignment) unless sequential_assignment?(assignment.node)
    end

    ignore_node(assignment.node) if chained_assignment?(assignment.node)
  end
end

#collect_variable_like_names(scope)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 142

def collect_variable_like_names(scope)
  names = scope.each_node.with_object(Set.new) do |node, set|
    set << node.method_name if variable_like_method_invocation?(node)
  end

  variable_names = scope.variables.each_value.map(&:name)
  names.merge(variable_names)
end

#message_for_useless_assignment(assignment)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 75

def message_for_useless_assignment(assignment)
  variable = assignment.variable

  format(MSG, variable: variable.name) + message_specification(assignment, variable).to_s
end

#message_specification(assignment, variable)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 103

def message_specification(assignment, variable)
  if assignment.multiple_assignment?
    multiple_assignment_message(variable.name)
  elsif assignment.operator_assignment?
    operator_assignment_message(variable.scope, assignment)
  else
    similar_name_message(variable)
  end
end

#multiple_assignment_message(variable_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 113

def multiple_assignment_message(variable_name)
  " Use `_` or `_#{variable_name}` as a variable name to indicate " \
    "that it won't be used."
end

#offense_range(assignment)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 81

def offense_range(assignment)
  if assignment.regexp_named_capture?
    assignment.node.children.first.source_range
  else
    assignment.node.loc.name
  end
end

#operator_assignment_message(scope, assignment)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 118

def operator_assignment_message(scope, assignment)
  return_value_node = return_value_node_of_scope(scope)
  return unless assignment.meta_assignment_node.equal?(return_value_node)

  " Use `#{assignment.operator.delete_suffix('=')}` instead of `#{assignment.operator}`."
end

#remove_exception_assignment_part(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 175

def remove_exception_assignment_part(corrector, node)
  corrector.remove(
    range_between(
      (node.parent.children.first&.source_range || node.parent.location.keyword).end_pos,
      node.source_range.end_pos
    )
  )
end

#remove_local_variable_assignment_part(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 199

def remove_local_variable_assignment_part(corrector, node)
  corrector.replace(node, node.expression.source)
end

#remove_trailing_character_from_operator(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 188

def remove_trailing_character_from_operator(corrector, node)
  corrector.remove(node.parent.location.operator.end.adjust(begin_pos: -1))
end

#rename_variable_with_underscore(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 184

def rename_variable_with_underscore(corrector, node)
  corrector.replace(node, '_')
end

#replace_named_capture_group_with_non_capturing_group(corrector, node, variable_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 192

def replace_named_capture_group_with_non_capturing_group(corrector, node, variable_name)
  corrector.replace(
    node.children.first,
    node.children.first.source.sub(/\(\?<#{variable_name}>/, '(?:')
  )
end

#return_value_node_of_scope(scope)

TODO: More precise handling (rescue, ensure, nested begin, etc.)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 132

def return_value_node_of_scope(scope)
  body_node = scope.body_node

  if body_node.begin_type?
    body_node.children.last
  else
    body_node
  end
end

#sequential_assignment?(node) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 89

def sequential_assignment?(node)
  if node.lvasgn_type? && node.expression&.array_type? &&
     node.each_descendant.any?(&:assignment?)
    return true
  end
  return false unless node.parent

  sequential_assignment?(node.parent)
end

#similar_name_message(variable)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 125

def similar_name_message(variable)
  variable_like_names = collect_variable_like_names(variable.scope)
  similar_name = NameSimilarity.find_similar_name(variable.name, variable_like_names)
  " Did you mean `#{similar_name}`?" if similar_name
end

#variable_like_method_invocation?(node) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 151

def variable_like_method_invocation?(node)
  return false unless node.send_type?

  node.receiver.nil? && !node.arguments?
end