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

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/lint/useless_assignment.rb

Overview

This cop 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.

Constant Summary collapse

MSG =
'Useless assignment to variable - `%s`.'
MINIMUM_SIMILARITY_TO_SUGGEST =
0.9

Constants included from Util

Util::ASGN_NODES, Util::BASIC_LITERALS, Util::EQUALS_ASGN_NODES, Util::LITERALS, Util::OPERATOR_METHODS, Util::PROC_NEW_NODE, Util::SHORTHAND_ASGN_NODES

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offenses, #processed_source

Instance Method Summary collapse

Methods inherited from Cop

#add_offense, all, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, #cop_name, cop_name, cop_type, #correct, #debug?, #details, #display_cop_names?, #display_style_guide?, #excluded_file?, #extra_details?, inherited, #initialize, lint?, match?, #message, non_rails, qualified_cop_name, rails?, #reference_url, #relevant_file?, #style_guide_url

Methods included from NodePattern::Macros

#def_node_matcher, #def_node_search

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

begins_its_line?, block_length, command?, comment_line?, const_name, directions, first_part_of_call_chain, lambda?, lambda_or_proc?, line_range, move_pos, numeric_range_size, on_node, operator?, parentheses?, proc?, range_with_surrounding_comma, range_with_surrounding_space, source_range, strip_quotes, within_node?

Methods included from PathUtil

hidden?, issue_deprecation_warning, match_path?, relative_path

Constructor Details

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

Instance Method Details

#after_leaving_scope(scope, _variable_table) ⇒ Object



23
24
25
26
27
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 23

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

#check_for_unused_assignments(variable) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 29

def check_for_unused_assignments(variable)
  return if variable.should_be_unused?

  variable.assignments.each do |assignment|
    next if assignment.used?

    message = message_for_useless_assignment(assignment)

    location = if assignment.regexp_named_capture?
                 assignment.node.children.first.loc.expression
               else
                 assignment.node.loc.name
               end

    add_offense(nil, location, message)
  end
end

#collect_variable_like_names(scope) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 93

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

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

#find_similar_name(target_name, scope) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 80

def find_similar_name(target_name, scope)
  names = collect_variable_like_names(scope)
  names.delete(target_name)

  scores = names.each_with_object({}) do |name, hash|
    score = StringUtil.similarity(target_name, name)
    hash[name] = score if score >= MINIMUM_SIMILARITY_TO_SUGGEST
  end

  most_similar_name, _max_score = scores.max_by { |_, score| score }
  most_similar_name
end

#join_force?(force_class) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 19

def join_force?(force_class)
  force_class == VariableForce
end

#message_for_useless_assignment(assignment) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 47

def message_for_useless_assignment(assignment)
  variable = assignment.variable

  message = format(MSG, variable.name)

  if assignment.multiple_assignment?
    message << " Use `_` or `_#{variable.name}` as a variable name " \
               "to indicate that it won't be used."
  elsif assignment.operator_assignment?
    return_value_node = return_value_node_of_scope(variable.scope)
    if assignment.meta_assignment_node.equal?(return_value_node)
      non_assignment_operator = assignment.operator.sub(/=$/, '')
      message << " Use just operator `#{non_assignment_operator}`."
    end
  else
    similar_name = find_similar_name(variable.name, variable.scope)
    message << " Did you mean `#{similar_name}`?" if similar_name
  end

  message
end

#return_value_node_of_scope(scope) ⇒ Object

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



70
71
72
73
74
75
76
77
78
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 70

def return_value_node_of_scope(scope)
  body_node = scope.body_node

  if body_node.type == :begin
    body_node.children.last
  else
    body_node
  end
end

#variable_like_method_invocation?(node) ⇒ Boolean

Returns:

  • (Boolean)


105
106
107
108
109
# File 'lib/rubocop/cop/lint/useless_assignment.rb', line 105

def variable_like_method_invocation?(node)
  return false unless node.send_type?
  receiver, _method_name, *args = *node
  receiver.nil? && args.empty?
end