123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::NameTypo

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

Overview

Checks for probable typos in constant and method names: a name that does not resolve anywhere in the project, used in a namespace the project does define, with a close-named sibling to suggest instead.

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.

Constants are checked only in qualified references (Foo::Bar) whose namespace resolves in the index; bare names cannot be distinguished from constants provided by gems or the standard library. Methods are checked only in calls on constant receivers (Foo.bar) whose entire indexed ancestry is resolved, so methods gained through gem classes or dynamic definitions never produce offenses. In both cases an offense requires a similarly named alternative to exist — an unknown name alone is not reported, since the index does not see gems or the standard library.

For the same reason, a namespace whose root segment names a gem in the bundle (Flipper for the flipper gem) is left alone: a project that reopens it (module Flipper; module Adapters; …​) makes it resolve in the index, while the members the gem itself defines stay invisible and would look like typos. Enabling AllCops/ProjectIndexIncludesGems indexes those sources and restores the check.

Names that appear as symbols or inside string literals in the same file are never reported, since they usually belong to runtime definitions the index cannot see (stub_const, const_set, define_method, and the like).

Examples:

# bad - Services::UserCraetor is not defined, Services::UserCreator is
Services::UserCraetor.new

# good
Services::UserCreator.new

# bad - Report.generate_sumary is not defined, Report.generate_summary is
Report.generate_sumary

# good
Report.generate_summary

CheckConstants: false

# good - constant references are not checked
Services::UserCraetor.new

CheckMethods: false

# good - method calls are not checked
Report.generate_sumary

AllowedNames: ['generate_sumary']

# good - the name is explicitly allowed
Report.generate_sumary

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

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

#allowed_name?(name) ⇒ Boolean (private)

[ GitHub ]

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

def allowed_name?(name)
  cop_config.fetch('AllowedNames', []).include?(name.to_s)
end

#bundled_gem_names (private)

The bundle’s gems except those sourced from a local path, whose code lives in the project and is indexed like the rest of it — among them the project’s own gem, which its lockfile lists in the PATH section.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 181

def bundled_gem_names
  (config.gem_versions_in_target || {}).keys - (config.path_sourced_gems_in_target || [])
end

#bundled_gem_namespaces (private)

Gem names normalized towards the constant they conventionally provide: flipper for Flipper, activerecord for ActiveRecord.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 174

def bundled_gem_namespaces
  @bundled_gem_namespaces ||= bundled_gem_names.to_set { |name| name.delete('-_').downcase }
end

#check?(key) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 112

def check?(key)
  project_index && defined?(DidYouMean::SpellChecker) && cop_config.fetch(key, true)
end

#checkable_constant?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 116

def checkable_constant?(node)
  node.namespace&.const_type? &&
    !allowed_name?(node.short_name) &&
    !definition_identifier?(node) && !defined_check?(node)
end

#complete_index_members?(declaration) ⇒ Boolean (private)

Whether the index can be trusted to list everything the namespace defines. A name missing from an incomplete member list is not evidence of a typo, so both gaps have to be ruled out first: an ancestor that does not resolve may contribute the name, and so may a gem that reopens the namespace.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 155

def complete_index_members?(declaration)
  fully_resolved_index_ancestry?(declaration) && !gem_owned_namespace?(declaration)
end

#constant_member_names(namespace) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 246

def constant_member_names(namespace)
  namespace.members.filter_map do |member|
    name = member.name
    name.split('::').last unless name.include?('#') || name.include?('<')
  end
end

#constant_typo_suggestion(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 138

def constant_typo_suggestion(node)
  namespace = resolve_constant_in_index(node.namespace)
  return nil unless namespace.is_a?(Rubydex::Namespace)
  return nil if namespace.find_member(node.short_name.to_s)
  return nil unless complete_index_members?(namespace)
  return nil if literal_names.include?(node.short_name.to_s)

  spell_check(node.short_name, constant_member_names(namespace))
rescue StandardError
  nil
end

#defined_check?(node) ⇒ Boolean (private)

defined?(Foo::Bar) probes whether a name exists; unknown names there are deliberate.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 134

def defined_check?(node)
  node.each_ancestor(:defined?).any?
end

#definition_identifier?(node) ⇒ Boolean (private)

The last segment of a class, module or constant definition is being defined, not referenced.

[ GitHub ]

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

def definition_identifier?(node)
  node.parent&.defined_module
end

#gem_owned_namespace?(declaration) ⇒ Boolean (private)

Whether the namespace’s root segment names a gem in the bundle, which is then free to define members the index never sees: gem sources are only indexed when AllCops/ProjectIndexIncludesGems is enabled. A project that reopens such a namespace to add its own members (module Flipper; module Adapters; …​) makes it resolve in the index while most of what it holds stays invisible.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 165

def gem_owned_namespace?(declaration)
  return false if config.for_all_cops['ProjectIndexIncludesGems']

  root = declaration.name.to_s.split('::').first.to_s
  bundled_gem_namespaces.include?(root.downcase)
end

#literal_names (private)

Names mentioned as symbols or inside string literals in the current file belong to runtime definitions (stub_const, const_set, define_method) that the index cannot see.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 231

def literal_names
  @literal_names ||=
    processed_source.ast.each_descendant(:sym, :str)
                    .with_object(Set.new) do |literal, names|
      if literal.sym_type?
        names << literal.value.to_s
      else
        # `scan` raises on binary string literals with invalid byte sequences.
        value = literal.value
        value = value.scrub unless value.valid_encoding?
        value.scan(LITERAL_IDENTIFIER_PATTERN) { |token| names << token }
      end
    end
end

#method_member_names(declaration) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 253

def method_member_names(declaration)
  scopes = declaration.ancestors.filter_map { |ancestor| indexed_singleton_of(ancestor) }
  scopes << declaration

  scopes.flat_map do |scope|
    scope.members.filter_map { |member| member.name[METHOD_MEMBER_REGEXP, 1] }
  end
end

#method_typo_suggestion(node) (private)

Writers are indexed under the reader’s name, so setter calls are verified and spell-checked through the base name.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 187

def method_typo_suggestion(node)
  setter = setter_call?(node)
  base = setter ? node.method_name.to_s.delete_suffix('=') : node.method_name.to_s

  declaration = unknown_method_owner(node, base)
  return nil unless declaration
  return nil if literal_names.include?(base)

  suggestion = spell_check(base, method_member_names(declaration))
  suggestion && setter ? "#{suggestion}=" : suggestion
rescue StandardError
  nil
end

#on_const(node)

[ GitHub ]

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

def on_const(node)
  return unless check?('CheckConstants') && checkable_constant?(node)

  suggestion = constant_typo_suggestion(node)
  return unless suggestion

  message = format(CONSTANT_MSG, name: node.short_name,
                                 namespace: node.namespace.const_name,
                                 suggestion: suggestion)
  add_offense(node.loc.name, message: message)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 103

alias on_csend on_send

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 105

def on_new_investigation
  @literal_names = nil
  super
end

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 90

def on_send(node)
  return unless check?('CheckMethods')
  return unless node.receiver&.const_type?
  return if allowed_name?(node.method_name) || defined_check?(node)

  suggestion = method_typo_suggestion(node)
  return unless suggestion

  message = format(METHOD_MSG, receiver: node.receiver.const_name,
                               name: node.method_name,
                               suggestion: suggestion)
  add_offense(node.loc.selector, message: message)
end

#responds_in_index?(declaration, name, base) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 218

def responds_in_index?(declaration, name, base)
  # Instance methods of a module are also callable on the module
  # itself when exposed with `module_function`.
  [name, base].uniq.any? do |candidate|
    member_name = "#{candidate}()"
    indexed_singleton_member(declaration, member_name) ||
      declaration.find_member(member_name)
  end
end

#setter_call?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 214

def setter_call?(node)
  node.assignment_method? && !node.operator_method?
end

#spell_check(name, dictionary) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 262

def spell_check(name, dictionary)
  return nil if dictionary.empty?

  DidYouMean::SpellChecker.new(dictionary: dictionary.uniq).correct(name.to_s).first
end

#unknown_method_owner(node, base) (private)

The receiver’s declaration when it resolves in the index, everything it can inherit or be reopened with is visible there, and the method is not found — nil otherwise.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/name_typo.rb', line 204

def unknown_method_owner(node, base)
  declaration = resolve_constant_in_index(node.receiver)
  return nil unless declaration.is_a?(Rubydex::Namespace)
  return nil if responds_in_index?(declaration, node.method_name.to_s, base)
  return nil unless fully_resolved_index_ancestry?(declaration)
  return nil if gem_owned_namespace?(declaration)

  declaration
end