123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Layout::ExtraSpacing

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/layout/extra_spacing.rb

Overview

Checks for extra/unnecessary whitespace.

Examples:

# good if AllowForAlignment is true
name      = "RuboCop"
# Some comment and an empty line

website  += "/rubocop/rubocop" unless cond
puts        "rubocop"          if     debug

# bad for any configuration
set_app("RuboCop")
website  = "https://github.com/rubocop/rubocop"

# good only if AllowBeforeTrailingComments is true
object.method(arg)  # this is a comment

# good even if AllowBeforeTrailingComments is false or not set
object.method(arg) # this is a comment

# good with either AllowBeforeTrailingComments or AllowForAlignment
object.method(arg)         # this is a comment
another_object.method(arg) # this is another comment
some_object.method(arg)    # this is some comment

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::PrecedingFollowingAlignment - Included

ASSIGNMENT_OR_COMPARISON_TOKENS

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

Reserved for Commissioner.

::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,
#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

rubocop:disable-next Metrics/ParameterLists.

#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::PrecedingFollowingAlignment - Included

#aligned_comment_lines, #aligned_equals_operator?, #aligned_identical?, #aligned_operator?, #aligned_token?, #aligned_with_adjacent_line?, #aligned_with_any_line?, #aligned_with_any_line_range?, #aligned_with_append_operator?, #aligned_with_equals_sign, #aligned_with_line?, #aligned_with_operator?, #aligned_with_preceding_equals?,
#aligned_with_preceding_equals_operator

Allows alignment with a preceding operator that ends with an =, including assignment and comparison operators.

#aligned_with_something?,
#aligned_with_subsequent_equals_operator

Allows alignment with a subsequent operator that ends with an =, including assignment and comparison operators.

#aligned_words?, #alignment_line_ranges, #alignment_lines, #assignment_lines, #assignment_tokens, #definition_boundary_lines,
#relevant_assignment_lines

Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength.

#relevant_lines,
#remove_equals_in_def

Metrics/CyclomaticComplexity rubocop:enable Metrics/PerceivedComplexity, Metrics/MethodLength.

::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, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Instance Attribute Details

#allow_for_trailing_comments?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 281

def allow_for_trailing_comments?
  cop_config['AllowBeforeTrailingComments']
end

#force_equal_sign_alignment?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 235

def force_equal_sign_alignment?
  cop_config['ForceEqualSignAlignment']
end

Instance Method Details

#align_column(asgn_token) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 272

def align_column(asgn_token)
  # if we removed unneeded spaces from the beginning of this =,
  # what column would it end from?
  line    = processed_source.lines[asgn_token.line - 1]
  leading = line[0...asgn_token.column]
  spaces  = leading.size - (leading =~ / *\Z/)
  asgn_token.pos.last_column - spaces + 1
end

#align_equal_sign(corrector, token, align_to) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 249

def align_equal_sign(corrector, token, align_to)
  return unless @corrected.add?(token)

  diff = align_to - token.pos.last_column

  if diff.positive?
    corrector.insert_before(token.pos, ' ' * diff)
  elsif diff.negative?
    corrector.remove_preceding(token.pos, -diff)
  end
end

#align_equal_signs(range, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 239

def align_equal_signs(range, corrector)
  lines  = all_relevant_assignment_lines(range.line)
  tokens = assignment_tokens.select { |t| lines.include?(t.line) }

  columns  = tokens.map { |t| align_column(t) }
  align_to = columns.max

  tokens.each { |token| align_equal_sign(corrector, token, align_to) }
end

#aligned_locations(locs) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 53

def aligned_locations(locs)
  return [] if locs.empty?

  aligned = Set.new
  locs.each_cons(2) do |loc1, loc2|
    aligned << loc1.line << loc2.line if loc1.column == loc2.column
  end
  aligned
end

#aligned_on_other_column?(token, lines) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 136

def aligned_on_other_column?(token, lines)
  line_set = Set.new(lines)
  by_column, = group_profile(token.line)

  by_column.any? do |column, entries|
    next false if column == token.pos.column

    shared = entries.filter_map { |line, spacing| spacing if line_set.include?(line) }
    shared.uniq.size > 1
  end
end

#aligned_tok?(previous_token, token) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 104

def aligned_tok?(previous_token, token)
  if token.comment?
    @aligned_comments.include?(token.line)
  else
    aligned_with_something?(token.pos) &&
      (ASSIGNMENT_OR_COMPARISON_TOKENS.include?(token.type) ||
       spacing_varies?(previous_token, token))
  end
end

#all_relevant_assignment_lines(line_number) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 261

def all_relevant_assignment_lines(line_number)
  last_line_number = processed_source.lines.size

  (
    relevant_assignment_lines(line_number.downto(1)) +
    relevant_assignment_lines(line_number.upto(last_line_number))
  )
    .uniq
    .sort
end

#build_group_profile(group) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 158

def build_group_profile(group)
  by_column = Hash.new { |hash, key| hash[key] = [] }
  typed = Hash.new { |hash, key| hash[key] = [[], []] }

  group.each { |line| record_line_spacings(by_column, typed, line) }

  [by_column, typed]
end

#check_assignment(token) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 73

def check_assignment(token)
  return unless aligned_with_preceding_equals_operator(token) == :no

  message = format(MSG_UNALIGNED_ASGN, location: 'preceding')
  add_offense(token.pos, message: message) do |corrector|
    align_equal_signs(token.pos, corrector)
  end
end

#check_other(token1, token2, ast) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 82

def check_other(token1, token2, ast)
  return false if allow_for_trailing_comments? && token2.text.start_with?('#')

  extra_space_range(token1, token2) do |range|
    next if ignored_range?(ast, range.begin_pos)

    add_offense(range, message: MSG_UNNECESSARY) { |corrector| corrector.remove(range) }
  end
end

#check_tokens(ast, token1, token2) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 63

def check_tokens(ast, token1, token2)
  return if token2.type == :tNL

  if force_equal_sign_alignment? && assignment_tokens.include?(token2)
    check_assignment(token2)
  else
    check_other(token1, token2, ast)
  end
end

#distinct_spacings(entries) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 148

def distinct_spacings(entries)
  entries.map(&:last).uniq
end

#extra_space_range(token1, token2) {|range_between(start_pos, end_pos)| ... } (private)

Yields:

  • (range_between(start_pos, end_pos))
[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 92

def extra_space_range(token1, token2)
  return if token1.line != token2.line

  start_pos = token1.end_pos
  end_pos = token2.begin_pos - 1
  return if end_pos <= start_pos

  return if allow_for_alignment? && aligned_tok?(token1, token2)

  yield range_between(start_pos, end_pos)
end

#group_profile(line_number) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 152

def group_profile(line_number)
  group = alignment_lines(line_number)

  @group_profiles[group] ||= build_group_profile(group)
end

#ignored_range?(ast, start_pos) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 213

def ignored_range?(ast, start_pos)
  ignored_ranges(ast).any? { |r| r.include?(start_pos) }
end

#ignored_ranges(ast) (private)

Returns an array of ranges that should not be reported. It’s the extra spaces between the keys and values in a multiline hash, since those are handled by the Layout/HashAlignment cop.

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 220

def ignored_ranges(ast)
  return [] unless ast

  @ignored_ranges ||= begin
    ranges = []
    on_node(:pair, ast) do |pair|
      next if pair.parent.single_line?

      key, value = *pair
      ranges << (key.source_range.end_pos...value.source_range.begin_pos)
    end
    ranges
  end
end

#nearest_spacing_differs?(line_numbers, token, spacing) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 187

def nearest_spacing_differs?(line_numbers, token, spacing)
  line_numbers.each do |line|
    break if definition_boundary_lines.include?(line)
    next if aligned_comment_lines.include?(line)

    other_spacing = spacing_before_token_at(line, token.pos.column)
    return other_spacing != spacing if other_spacing
  end

  false
end

#nearest_spacing_varies?(previous_token, token) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 177

def nearest_spacing_varies?(previous_token, token)
  spacing = token.begin_pos - previous_token.end_pos
  line_ranges = [(token.line - 1).downto(1),
                 (token.line + 1).upto(processed_source.lines.length)]

  line_ranges.any? do |line_numbers|
    nearest_spacing_differs?(line_numbers, token, spacing)
  end
end

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 39

def on_new_investigation
  return if processed_source.blank?

  @aligned_comments = aligned_locations(processed_source.comments.map(&:loc))
  @corrected = Set.new if force_equal_sign_alignment?
  prepare_alignment_data

  processed_source.tokens.each_cons(2) do |token1, token2|
    check_tokens(processed_source.ast, token1, token2)
  end
end

#prepare_alignment_data (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 207

def prepare_alignment_data
  @group_profiles = {}.compare_by_identity
  @alignment_verdicts = {}.compare_by_identity
  @tokens_by_line = processed_source.tokens.group_by(&:line)
end

#record_line_spacings(by_column, typed, line) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 167

def record_line_spacings(by_column, typed, line)
  @tokens_by_line[line]&.each_cons(2) do |previous_token, token|
    spacing = token.begin_pos - previous_token.end_pos
    by_column[token.pos.column] << [line, spacing]
    lines, spacings = typed[[token.pos.column, token.type]]
    lines << line
    spacings << spacing
  end
end

#spacing_before_token_at(line_number, column) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 199

def spacing_before_token_at(line_number, column)
  tokens = @tokens_by_line[line_number]
  index = tokens&.index { |token| token.pos.column == column }
  return unless index&.positive?

  tokens[index].begin_pos - tokens[index - 1].end_pos
end

#spacing_varies?(previous_token, token) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 114

def spacing_varies?(previous_token, token)
  by_column, typed = group_profile(token.line)
  column = token.pos.column
  lines, spacings = typed[[column, token.type]]
  entries = by_column[column]

  if lines.size > 1
    uniform_alignment_allowed?(token, lines, spacings)
  elsif entries.size > 1
    distinct_spacings(entries).size > 1
  else
    nearest_spacing_varies?(previous_token, token)
  end
end

#uniform_alignment_allowed?(token, lines, spacings) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 129

def uniform_alignment_allowed?(token, lines, spacings)
  return @alignment_verdicts[lines] if @alignment_verdicts.key?(lines)

  @alignment_verdicts[lines] =
    spacings.uniq.size > 1 || aligned_on_other_column?(token, lines)
end