123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::UnmodifiedReduceAccumulator

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

Overview

Looks for reduce or inject blocks where the value returned (implicitly or explicitly) does not include the accumulator. A block is considered valid as long as at least one return value includes the accumulator.

If the accumulator is not included in the return value, then the entire block will just return a transformation of the last element value, and could be rewritten as such without a loop.

Also catches instances where an index of the accumulator is returned, as this may change the type of object being retained.

Note
For the purpose of reducing false positives, this cop only flags returns in reduce blocks where the element is the only variable in the expression (since we will not be able to tell what other variables relate to via static analysis).

Examples:

# bad
(1..4).reduce(0) do |acc, el|
  el * 2
end

# bad, may raise a NoMethodError after the first iteration
%w(a b c).reduce({}) do |acc, letter|
  acc[letter] = true
end

# good
(1..4).reduce(0) do |acc, el|
  acc + el * 2
end

# good, element is returned but modified using the accumulator
values.reduce do |acc, el|
  el << acc
  el
end

# good, returns the accumulator instead of the index
%w(a b c).reduce({}) do |acc, letter|
  acc[letter] = true
  acc
end

# good, at least one branch returns the accumulator
values.reduce(nil) do |result, value|
  break result if something?
  value
end

# good, recursive
keys.reduce(self) { |result, key| result[key] }

# ignored as the return value cannot be determined
enum.reduce do |acc, el|
  x = foo(acc, el)
  bar(x)
end

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

Class Attribute Summary

::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 a 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::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_gem_version

Returns a gems locked versions (i.e.

#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

Instance Method Details

#acceptable_return?(return_val, element_name) ⇒ Boolean (private)

Determine if a return value is acceptable for the purposes of this cop If it is an expression containing the accumulator, it is acceptable Otherwise, it is only unacceptable if it contains the iterated element, since we otherwise do not have enough information to prevent false positives.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 191

def acceptable_return?(return_val, element_name)
  vars = expression_values(return_val).uniq
  return true if vars.none? || (vars - [element_name]).any?

  false
end

#accumulator_index?(node, accumulator_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 78

def_node_matcher :accumulator_index?, <<~PATTERN
  (send (lvar %1) {:[] :[]=} ...)
PATTERN

#allowed_type?(parent_node) ⇒ Boolean (private)

Exclude begin nodes inside a dstr from being collected by return_values

[ GitHub ]

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

def allowed_type?(parent_node)
  !parent_node.dstr_type?
end

#block_arg_name(node, index) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 159

def block_arg_name(node, index)
  node.argument_list[index].name
end

#check_return_values(block_node) (private)

[ GitHub ]

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

def check_return_values(block_node)
  return_values = return_values(block_node.body)
  accumulator_name = block_arg_name(block_node, 0)
  element_name = block_arg_name(block_node, 1)
  message_opts = { method: block_node.method_name, accum: accumulator_name }

  if (node = returned_accumulator_index(return_values, accumulator_name, element_name))
    add_offense(node, message: format(MSG_INDEX, message_opts))
  elsif potential_offense?(return_values, block_node.body, element_name, accumulator_name)
    return_values.each do |return_val|
      unless acceptable_return?(return_val, element_name)
        add_offense(return_val, message: format(MSG, message_opts))
      end
    end
  end
end

#element_modified?(node, element_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 83

def_node_search :element_modified?, <<~PATTERN
  {
    (send _receiver !{:[] :[]=} <`(lvar %1) `_ ...>)               # method(el, ...)
    (send (lvar %1) _message <{ivar gvar cvar lvar send} ...>)     # el.method(...)
    (lvasgn %1 _)                                                  # el = ...
    (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (lvasgn %1) ... _) # el += ...
  }
PATTERN

#expression_values(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 104

def_node_search :expression_values, <<~PATTERN
  {
    (%RuboCop::AST::Node::VARIABLES $_)
    (%RuboCop::AST::Node::EQUALS_ASSIGNMENTS $_ ...)
    (send (%RuboCop::AST::Node::VARIABLES $_) :<< ...)
    $(send _ _)
    (dstr (begin {(%RuboCop::AST::Node::VARIABLES $_)}))
    (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (%RuboCop::AST::Node::EQUALS_ASSIGNMENTS $_) ...)
  }
PATTERN

#lvar_used?(node, name)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 93

def_node_matcher :lvar_used?, <<~PATTERN
  {
    (lvar %1)
    (lvasgn %1 ...)
    (send (lvar %1) :<< ...)
    (dstr (begin (lvar %1)))
    (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (lvasgn %1))
  }
PATTERN

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 115

def on_block(node)
  return unless node.body
  return unless reduce_with_block?(node)
  return unless node.argument_list.length >= 2

  check_return_values(node)
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 122

alias on_numblock on_block

#potential_offense?(return_values, block_body, element_name, accumulator_name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 176

def potential_offense?(return_values, block_body, element_name, accumulator_name)
  !(element_modified?(block_body, element_name) ||
    returns_accumulator_anywhere?(return_values, accumulator_name))
end

#reduce_with_block?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 70

def_node_matcher :reduce_with_block?, <<~PATTERN
  {
    (block (call _recv {:reduce :inject} ...) args ...)
    (numblock (call _recv {:reduce :inject} ...) ...)
  }
PATTERN

#return_values(block_body_node) (private)

Return values in a block are either the value given to next, the last line of a multiline block, or the only line of the block

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 128

def return_values(block_body_node)
  nodes = [block_body_node.begin_type? ? block_body_node.child_nodes.last : block_body_node]

  block_body_node.each_descendant(:next, :break) do |n|
    # Ignore `next`/`break` inside an inner block
    next if n.each_ancestor(:block).first != block_body_node.parent
    next unless n.first_argument

    nodes << n.first_argument
  end

  nodes
end

#returned_accumulator_index(return_values, accumulator_name, element_name) (private)

Look for an index of the accumulator being returned, except where the index is the element. This is always an offense, in order to try to catch potential exceptions due to type mismatches

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 167

def returned_accumulator_index(return_values, accumulator_name, element_name)
  return_values.detect do |val|
    next unless accumulator_index?(val, accumulator_name)
    next true if val.method?(:[]=)

    val.arguments.none? { |arg| lvar_used?(arg, element_name) }
  end
end

#returns_accumulator_anywhere?(return_values, accumulator_name) ⇒ Boolean (private)

If the accumulator is used in any return value, the node is acceptable since the accumulator has a chance to change each iteration

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb', line 183

def returns_accumulator_anywhere?(return_values, accumulator_name)
  return_values.any? { |node| lvar_used?(node, accumulator_name) }
end