123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::InternalAffairs::NodeMatcherDirective

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/internal_affairs/node_matcher_directive.rb

Overview

Checks that node matcher definitions are tagged with a YARD @!method directive so that editors are able to find the dynamically defined method.

Examples:

# bad
def_node_matcher :foo?, <<~PATTERN
  ...
PATTERN

# good
# @!method foo?(node)
def_node_matcher :foo?, <<~PATTERN
  ...
PATTERN

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.

.builtin?

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

Cops (other than builtin) are encouraged to implement this.

.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, #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_newline?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 202

def add_newline?(node)
  # Determine if a blank line should be inserted before the new directive
  # in order to spread out pattern matchers
  return false if node.sibling_index&.zero?
  return false unless node.parent

  prev_sibling = node.parent.child_nodes[node.sibling_index - 1]
  return false unless prev_sibling && pattern_matcher?(prev_sibling)

  node.loc.line == last_line(prev_sibling) + 1
end

#correct_method_directive(corrector, directive, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 222

def correct_method_directive(corrector, directive, actual_name)
  correct = "@!method #{remove_receiver(actual_name)}"
  current_name = (directive[:receiver] || '') + directive[:method_name]
  regexp = /@!method\s+#{Regexp.escape(current_name)}/

  replacement = directive[:node_method].text.gsub(regexp, correct)
  corrector.replace(directive[:node_method], replacement)
end

#directive_offense_type(directive, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 110

def directive_offense_type(directive, actual_name)
  return :missing_directive unless directive

  return :wrong_scope if wrong_scope(directive, actual_name)
  return :no_scope if no_scope(directive, actual_name)

  # The method directive being prefixed by 'self.' is always an offense.
  # The matched method_name does not contain the receiver but the
  # def_node_match method name may so it must be removed.
  if directive[:method_name] != remove_receiver(actual_name) || directive[:receiver]
    :wrong_name
  end
end

#formatted_message(offense_type, directive, actual_name, method_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 150

def formatted_message(offense_type, directive, actual_name, method_name)
  case offense_type
  when :wrong_name
    # Add the receiver to the name when showing an offense
    current_name = if directive[:receiver]
                     directive[:receiver] + directive[:method_name]
                   else
                     directive[:method_name]
                   end
    # The correct name will never include a receiver, remove it
    format(MSG_WRONG_NAME, expected: remove_receiver(actual_name), actual: current_name)
  when :wrong_scope
    MSG_WRONG_SCOPE_SELF
  when :no_scope
    MSG_MISSING_SCOPE_SELF
  when :missing_directive
    format(MSG, method: method_name)
  end
end

#group_comments(comments) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 85

def group_comments(comments)
  result = []
  comments.each.with_index do |comment, index|
    # Grab the scope directive if it is preceded by a method directive
    if comment.text.include?('@!method')
      result << if (next_comment = comments[index + 1])&.text&.include?('@!scope')
                  [comment, next_comment]
                else
                  [comment, nil]
                end
    end
  end
  result
end

#insert_method_directive(corrector, node, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 175

def insert_method_directive(corrector, node, actual_name)
  # If the pattern matcher uses arguments (`%1`, `%2`, etc.), include them in the directive
  arguments = pattern_arguments(node.arguments[1].source)

  range = range_with_surrounding_space(node.source_range, side: :left, newlines: false)
  indentation = range.source.match(/^\s*/)[0]
  directive = "#{indentation}# @!method #{actual_name}(#{arguments.join(', ')})\n"
  directive = "\n#{directive}" if add_newline?(node)

  corrector.insert_before(range, directive)
end

#insert_scope_directive(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 187

def insert_scope_directive(corrector, node)
  range = range_with_surrounding_space(node.source_range, side: :left, newlines: false)
  indentation = range.source.match(/^\s*/)[0]
  directive = "\n#{indentation}# @!scope class"

  corrector.insert_after(node, directive)
end

#last_line(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 214

def last_line(node)
  if node.last_argument.heredoc?
    node.last_argument.loc.heredoc_end.line
  else
    node.loc.last_line
  end
end

#method_directives(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 68

def method_directives(node)
  comments = processed_source.ast_with_comments[node]
  group_comments(comments).filter_map do |comment_method, comment_scope|
    match = comment_method.text.match(REGEXP_METHOD)
    next unless match

    {
      node_method: comment_method,
      node_scope: comment_scope,
      method_name: match[:method_name],
      args: match[:args],
      receiver: match[:receiver],
      has_scope_directive: comment_scope&.text&.match?(REGEXP_SCOPE)
    }
  end
end

#no_scope(directive, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 128

def no_scope(directive, actual_name)
  actual_name.start_with?('self.') && !directive[:has_scope_directive]
end

#on_send(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 47

def on_send(node)
  return if node.arguments.none?
  return unless valid_method_name?(node)

  actual_name = node.first_argument.value.to_s

  # Ignore cases where the method has a receiver that isn't self
  return if actual_name.include?('.') && !actual_name.start_with?('self.')

  directives = method_directives(node)
  return too_many_directives(node) if directives.size > 1

  process_directive(node, actual_name, directives.first)
end

#pattern_arguments(pattern) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 195

def pattern_arguments(pattern)
  arguments = %w[node]
  max_pattern_var = pattern.scan(/(?<=%)\d+/).map(&:to_i).max
  max_pattern_var&.times { |i| arguments << "arg#{i + 1}" }
  arguments
end

#pattern_matcher?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 43

def_node_matcher :pattern_matcher?, <<~PATTERN
  (send _ %RESTRICT_ON_SEND {str sym} {str dstr})
PATTERN

#process_directive(node, actual_name, directive) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 104

def process_directive(node, actual_name, directive)
  return unless (offense_type = directive_offense_type(directive, actual_name))

  register_offense(offense_type, node, directive, actual_name)
end

#register_offense(offense_type, node, directive, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 132

def register_offense(offense_type, node, directive, actual_name)
  message = formatted_message(offense_type, directive, actual_name, node.method_name)

  add_offense(node, message: message) do |corrector|
    case offense_type
    when :wrong_name
      correct_method_directive(corrector, directive, actual_name)
    when :wrong_scope
      remove_scope_directive(corrector, directive)
    when :no_scope
      insert_scope_directive(corrector, directive[:node_method])
    when :missing_directive
      insert_method_directive(corrector, node, actual_name)
    end
  end
end

#remove_receiver(current) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 171

def remove_receiver(current)
  current.delete_prefix('self.')
end

#remove_scope_directive(corrector, directive) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 231

def remove_scope_directive(corrector, directive)
  range = range_by_whole_lines(
    directive[:node_scope].source_range,
    include_final_newline: true
  )
  corrector.remove(range)
end

#too_many_directives(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 100

def too_many_directives(node)
  add_offense(node, message: MSG_TOO_MANY)
end

#valid_method_name?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 64

def valid_method_name?(node)
  node.first_argument.str_type? || node.first_argument.sym_type?
end

#wrong_scope(directive, actual_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/internal_affairs/node_matcher_directive.rb', line 124

def wrong_scope(directive, actual_name)
  !actual_name.start_with?('self.') && directive[:has_scope_directive]
end