123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::SuperArgumentMismatch

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/super_argument_mismatch.rb

Overview

Checks for super calls with explicit arguments that pass the wrong number of positional arguments to the overridden implementation, using the project index.

The check is powered by the project-wide index, so it only runs when AllCops/UseProjectIndex is enabled and the rubydex gem is installed. Without the index the cop does nothing.

Only super inside a plain instance method defined directly in a class body is considered, and only when the enclosing class resolves in the index and its entire ancestry is resolved, so a superclass method coming from a gem, the standard library, or a dynamic definition never produces an offense. The overridden implementation is the first ancestor after the enclosing class in the index’s method resolution order that defines the method; when it is not a plain method definition (an attr_* or an alias) or its definitions disagree on arity, the call is not checked. Calls that forward arguments (, *, …​) are skipped, and bare super (which forwards the current method’s parameters) is not checked. Methods the index attributes to Object, Kernel, or BasicObject are never used as the overridden implementation, since a def inside a block at the top level (Struct.new do …​ end) is indexed under Object even though it defines a method somewhere else entirely.

Examples:

# Given the project defines:
#   class Base
#     def initialize(name, size); end
#   end

# bad
class Widget < Base
  def initialize(name)
    super(name)
  end
end

# good
class Widget < Base
  def initialize(name)
    super(name, 0)
  end
end

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ProjectIndexHelp - Included

BUILTIN_DOCUMENT_URI, FILE_URI_PREFIX, WINDOWS_DRIVE_PREFIX

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

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

  • #on_super(node)
  • #declared_at?(declaration, class_node) ⇒ Boolean private

    Whether one of the declaration’s definitions is the given class node, anchoring the name-based lookup to the source being inspected (a qualified identifier like class Foo::Bar can resolve to a namespace other than the joined nesting names).

  • #enclosing_class_declaration(def_node) private

    The index declaration of the class whose body directly contains def_node, or nil when the method is not defined directly in a class body (module methods are excluded because their super target depends on where the module is mixed in) or the class does not resolve in the index.

  • #enclosing_instance_method(node) private

    The def node whose method the super call re-dispatches, or nil when the context is not statically known: super inside a singleton method, inside define_method or an eval/refine block, or outside any method.

  • #message(method_name, parent, given, min, max) private
  • #resolved_super_shape(def_node) private

    [[min, max, has_keywords], parent] for the implementation super dispatches to, or nil when the enclosing class or the overridden method is not statically known.

  • #super_method_shape(declaration, method_name) private

    The shape of the first implementation of method_name after the enclosing class in the index’s method resolution order, or nil when no indexed ancestor defines it (e.g.

::RuboCop::Cop::IndexedMethodArity - Included

#arity_satisfied?, #double_splat?, #expected_range, #forwards_arguments?,
#indexed_member_shape

The agreed [min, max, has_keywords] shape of an indexed member’s method definitions, or nil when the member is not backed by plain method definitions (attr, alias), has no signature, forwards arguments, or its definitions disagree on arity (e.g.

#keyword_hash, #keyword_parameters?, #maximum_positional,
#positional_argument_count

The number of positional arguments the call passes, or nil when it cannot be determined statically (argument forwarding).

#shape_for, #signature_shape

::RuboCop::Cop::ProjectIndexHelp - Included

#external_dependency_checksum, #compute_project_index_signature,
#definitions_in_other_files

Returns the definitions among definitions that live in a file other than the one being inspected, ordered by path and line.

#fully_resolved_index_ancestry?

Whether every link of the declaration’s ancestry is resolved in the index: no definition of any ancestor has an unresolved superclass or mixin reference.

#indexed_singleton_member

A namespace without any singleton method has no singleton-class declaration of its own, so the lookup starts from the first ancestor that has one; its find_member covers the rest of the chain.

#indexed_singleton_of

The declaration of `declaration’s singleton class, or nil when no singleton method is defined on it anywhere in the project.

#inherited_index_member?

Whether an ancestor of scope other than scope itself defines member_name.

#lexical_nesting_of

The lexical nesting the node’s constants resolve through, outermost first.

#prior_definition_in_other_file, #project_index_signature,
#resolve_constant_in_index

Resolves a constant node the way Ruby does: the first segment through the lexical nesting and every following segment inside the previous one.

#resolved_mixin_references?, #resolved_superclass_reference?, #same_file?

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

#declared_at?(declaration, class_node) ⇒ Boolean (private)

Whether one of the declaration’s definitions is the given class node, anchoring the name-based lookup to the source being inspected (a qualified identifier like class Foo::Bar can resolve to a namespace other than the joined nesting names).

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 143

def declared_at?(declaration, class_node)
  declaration.definitions.any? do |definition|
    location = definition.location
    location.uri.start_with?(FILE_URI_PREFIX) &&
      location.to_display.start_line == class_node.first_line &&
      same_file?(location.to_file_path, processed_source.file_path)
  end
end

#enclosing_class_declaration(def_node) (private)

The index declaration of the class whose body directly contains def_node, or nil when the method is not defined directly in a class body (module methods are excluded because their super target depends on where the module is mixed in) or the class does not resolve in the index.

[ GitHub ]

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

def enclosing_class_declaration(def_node)
  class_node = def_node.each_ancestor(:class, :module, :sclass, :any_block).first
  return nil unless class_node&.class_type?

  declaration = project_index[lexical_nesting_of(def_node).join('::')]
  return nil unless declaration.is_a?(Rubydex::Namespace)
  return nil unless declared_at?(declaration, class_node)

  declaration
end

#enclosing_instance_method(node) (private)

The def node whose method the super call re-dispatches, or nil when the context is not statically known: super inside a singleton method, inside define_method or an eval/refine block, or outside any method.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 97

def enclosing_instance_method(node)
  node.each_ancestor(:any_def, :any_block, :sclass).each do |ancestor|
    case ancestor.type
    when :def then return ancestor
    when :defs, :sclass then return nil
    else
      return nil if CONTEXT_CHANGING_BLOCKS.include?(ancestor.method_name)
    end
  end

  nil
end

#message(method_name, parent, given, min, max) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 88

def message(method_name, parent, given, min, max)
  format(MSG, given: given, expected: expected_range(min, max),
              parent: parent.name, method: method_name)
end

#on_super(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 69

def on_super(node)
  return unless project_index

  def_node = enclosing_instance_method(node)
  return unless def_node

  shape, parent = resolved_super_shape(def_node)
  return unless shape

  min, max, has_keywords = shape
  given = positional_argument_count(node, has_keywords)
  return if given.nil? || arity_satisfied?(given, min, max)

  add_offense(node.loc.keyword,
              message: message(def_node.method_name, parent, given, min, max))
end

#resolved_super_shape(def_node) (private)

[[min, max, has_keywords], parent] for the implementation super dispatches to, or nil when the enclosing class or the overridden method is not statically known.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 113

def resolved_super_shape(def_node)
  declaration = enclosing_class_declaration(def_node)
  return nil unless declaration
  return nil unless fully_resolved_index_ancestry?(declaration, ignore_extend: true)

  super_method_shape(declaration, def_node.method_name)
rescue StandardError
  nil
end

#super_method_shape(declaration, method_name) (private)

The shape of the first implementation of method_name after the enclosing class in the index’s method resolution order, or nil when no indexed ancestor defines it (e.g. it comes from a gem or the standard library, which are not indexed).

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/super_argument_mismatch.rb', line 156

def super_method_shape(declaration, method_name)
  ancestors = declaration.ancestors.to_a
  position = ancestors.index { |ancestor| ancestor.name == declaration.name }
  return nil unless position

  ancestors.drop(position + 1).each do |ancestor|
    return nil if BUILTIN_ROOTS.include?(ancestor.name)

    member = ancestor.member("#{method_name}()")
    next unless member

    # The first definer along the chain is the receiving
    # implementation; when its shape is unknown there is nothing
    # further to check.
    shape = indexed_member_shape(member)
    return shape && [shape, ancestor]
  end

  nil
end