Class: RuboCop::Cop::Style::NegativeArrayIndex
| 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:
self,
::RuboCop::Cop::RangeHelp,
::RuboCop::Cop::Base,
::RuboCop::Cop::AutocorrectLogic,
::RuboCop::Cop::IgnoredNode,
::RuboCop::Util,
RuboCop::AST::Sexp
|
|
| Inherits: |
RuboCop::Cop::Base
|
| Defined in: | lib/rubocop/cop/style/negative_array_index.rb |
Overview
Identifies usages of arr[arr.length - n], arr[arr.size - n], or
arr[arr.count - n] and suggests to change them to use arr[-n] instead.
Also handles range patterns like arr[0..(arr.length - n)].
The cop recognizes preserving methods (sort, reverse, shuffle, rotate)
and their combinations, allowing safe replacement when the receiver matches.
It works with variables, instance variables, class variables, and constants.
Constant Summary
-
LENGTH_METHODS =
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 37%i[length size count].freeze
-
MSG =
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 33'Use `%<receiver>s[-%<index>s]` instead of `%<current>s`.' -
MSG_RANGE =
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 34'Use `%<receiver>s[%<start>s%<range_op>s-%<index>s]` instead of `%<current>s`.' -
PRESERVING_METHODS =
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 39%i[sort reverse shuffle rotate].freeze
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 35%i[[]].freeze
::RuboCop::Cop::Base - Inherited
EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::RangeHelp - Included
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 |
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
::RuboCop::Cop::Base - Inherited
::RuboCop::Cop::AutocorrectLogic - Included
Instance Method Summary
- #length_subtraction?(node)
-
#on_csend(node)
Alias for #on_send.
- #on_send(node) (also: #on_csend)
- #add_offense_for_subtraction(node, index_arg, negative_index) private
- #build_current_source(receiver, range_without_parens, index_arg) private
- #build_message_for_range(receiver, start, range_op, index, current) private
- #build_range_offense_data(receiver, range_node, range_end, inner_end, negative_index, index_arg) private
- #build_range_without_parens(range_start, range_op, range_end, inner_end) private
- #build_replacement_string(range_start, range_op, negative_index, index_arg) private
- #extract_base_receiver(node) private
- #extract_inner_end(node) private
- #extract_range_from_begin(node) private
- #format_range_message_parts(range_start, negative_index, index_arg) private
- #handle_range_pattern(receiver, range_node, index_arg) private
- #handle_simple_index_pattern(node, index_arg) private
- #preserving_method?(node) ⇒ Boolean private
- #range_with_length_subtraction?(range_node, array_receiver) ⇒ Boolean private
- #receivers_match?(length_receiver, array_receiver) ⇒ Boolean private
- #receivers_match_strict?(length_receiver, array_receiver) ⇒ Boolean private
::RuboCop::Cop::RangeHelp - Included
| #add_range, | |
| #arguments_range | A range containing the first to the last argument of a method call or method definition. |
| #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 |
| #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
#add_offense_for_subtraction(node, index_arg, negative_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 82
def add_offense_for_subtraction(node, index_arg, negative_index) receiver = node.receiver.source offense_range = index_arg.source_range current = "#{receiver}[#{index_arg.source}]" = format(MSG, receiver: receiver, index: negative_index, current: current) add_offense(offense_range, message: ) do |corrector| corrector.replace(offense_range, "-#{negative_index}") end end
#build_current_source(receiver, range_without_parens, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 168
def build_current_source(receiver, range_without_parens, index_arg) has_parentheses = index_arg.begin_type? if has_parentheses "#{receiver}[(#{range_without_parens})]" else "#{receiver}[#{range_without_parens}]" end end
#build_message_for_range(receiver, start, range_op, index, current) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 151
def (receiver, start, range_op, index, current) format( MSG_RANGE, receiver: receiver, start: start, range_op: range_op, index: index, current: current ) end
#build_range_offense_data(receiver, range_node, range_end, inner_end, negative_index, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 126
def build_range_offense_data(receiver, range_node, range_end, inner_end, negative_index, index_arg) range_op = range_node.erange_type? ? '...' : '..' range_start = range_node.begin.source range_without_parens = build_range_without_parens(range_start, range_op, range_end, inner_end) current_source = build_current_source(receiver, range_without_parens, index_arg) start, index = (range_start, negative_index, index_arg) = (receiver, start, range_op, index, current_source) replacement = build_replacement_string(range_start, range_op, negative_index, index_arg) [, replacement] end
#build_range_without_parens(range_start, range_op, range_end, inner_end) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 178
def build_range_without_parens(range_start, range_op, range_end, inner_end) end_expression = range_end.begin_type? ? range_end.source : inner_end.source "#{range_start}#{range_op}#{end_expression}" end
#build_replacement_string(range_start, range_op, negative_index, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 158
def build_replacement_string(range_start, range_op, negative_index, index_arg) has_parentheses = index_arg.begin_type? if has_parentheses "(#{range_start}#{range_op}-#{negative_index})" else "#{range_start}#{range_op}-#{negative_index}" end end
#extract_base_receiver(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 198
def extract_base_receiver(node) receiver = node.receiver return nil unless receiver return receiver unless receiver.receiver extract_base_receiver(receiver) end
#extract_inner_end(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 78
def extract_inner_end(node) node.children.size == 1 ? node.children.first : node end
#extract_range_from_begin(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 74
def extract_range_from_begin(node) node.begin_type? ? node.children.first : node end
#format_range_message_parts(range_start, negative_index, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 143
def (range_start, negative_index, index_arg) has_parentheses = index_arg.begin_type? start = has_parentheses ? "(#{range_start}" : range_start index = has_parentheses ? "#{negative_index})" : negative_index [start, index] end
#handle_range_pattern(receiver, range_node, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 111
def handle_range_pattern(receiver, range_node, index_arg) range_end = range_node.end inner_end = extract_inner_end(range_end) _length_receiver, negative_index = length_subtraction?(inner_end) , replacement = build_range_offense_data( receiver, range_node, range_end, inner_end, negative_index, index_arg ) add_offense(range_end, message: ) do |corrector| corrector.replace(index_arg, replacement) end end
#handle_simple_index_pattern(node, index_arg) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 65
def handle_simple_index_pattern(node, index_arg) length_receiver, negative_index = length_subtraction?(index_arg) return unless negative_index&.positive? return unless receivers_match?(length_receiver, node.receiver) add_offense_for_subtraction(node, index_arg, negative_index) end
#length_subtraction?(node)
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 42
def_node_matcher :length_subtraction?, <<~PATTERN (send (send $_ {:length :size :count}) :- (int $_)) PATTERN
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 61
alias on_csend on_send
#on_send(node) Also known as: #on_csend
[ GitHub ]# File 'lib/rubocop/cop/style/negative_array_index.rb', line 48
def on_send(node) return if node.arguments.empty? index_arg = node.first_argument range_node = extract_range_from_begin(index_arg) if range_with_length_subtraction?(range_node, node.receiver) receiver = node.receiver.source return handle_range_pattern(receiver, range_node, index_arg) end handle_simple_index_pattern(node, index_arg) end
#preserving_method?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 207
def preserving_method?(node) return true if node.receiver.nil? method_name = node.method_name return false unless PRESERVING_METHODS.include?(method_name) preserving_method?(node.receiver) end
#range_with_length_subtraction?(range_node, array_receiver) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 94
def range_with_length_subtraction?(range_node, array_receiver) return false unless range_node.range_type? range_end = range_node.end range_start = range_node.begin return false unless range_end && range_start return false unless preserving_method?(range_start) inner_end = extract_inner_end(range_end) length_receiver, negative_index = length_subtraction?(inner_end) return false unless negative_index&.positive? receivers_match_strict?(length_receiver, array_receiver) end
#receivers_match?(length_receiver, array_receiver) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 184
def receivers_match?(length_receiver, array_receiver) unless preserving_method?(array_receiver) && preserving_method?(length_receiver) return false end return true if length_receiver.source == array_receiver.source !extract_base_receiver(array_receiver).nil? end
#receivers_match_strict?(length_receiver, array_receiver) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/negative_array_index.rb', line 193
def receivers_match_strict?(length_receiver, array_receiver) preserving_method?(array_receiver) && length_receiver.source == array_receiver.source end