Class: RuboCop::Cop::Cop

Inherits:
Object
  • Object
show all
Extended by:
AST::Sexp, NodePattern::Macros
Includes:
AutocorrectLogic, IgnoredNode, Util
Defined in:
lib/rubocop/cop/cop.rb

Overview

A scaffold for concrete cops.

The Cop class is meant to be extended.

Cops track offenses and can autocorrect them on the fly.

A commissioner object is responsible for traversing the AST and invoking the specific callbacks on each cop. If a cop needs to do its own processing of the AST or depends on something else, it should define the #investigate method and do the processing there.

Examples:


class CustomCop < Cop
  def investigate(processed_source)
    # Do custom processing
  end
end

Direct Known Subclasses

Lint::AmbiguousOperator, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BlockAlignment, Lint::CircularArgumentReference, Lint::ConditionPosition, Lint::Debugger, Lint::DefEndAlignment, Lint::DeprecatedClassMethods, Lint::DuplicateMethods, Lint::DuplicatedKey, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyEnsure, Lint::EmptyInterpolation, Lint::EndAlignment, Lint::EndInMethod, Lint::EnsureReturn, Lint::Eval, Lint::FormatParameterMismatch, Lint::HandleExceptions, Lint::InvalidCharacterLiteral, Lint::LiteralInCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::NestedMethodDefinition, Lint::NonLocalExitFromIterator, Lint::ParenthesesAsGroupedExpression, Lint::RequireParentheses, Lint::RescueException, Lint::ShadowingOuterLocalVariable, Lint::SpaceBeforeFirstArg, Lint::StringConversionInInterpolation, Lint::UnderscorePrefixedVariableName, Lint::UnneededDisable, Lint::UnreachableCode, Lint::UnusedBlockArgument, Lint::UnusedMethodArgument, Lint::UselessAccessModifier, Lint::UselessAssignment, Lint::UselessComparison, Lint::UselessElseWithoutRescue, Lint::UselessSetterCall, Lint::Void, Metrics::AbcSize, Metrics::BlockNesting, Metrics::ClassLength, Metrics::CyclomaticComplexity, Metrics::LineLength, Metrics::MethodLength, Metrics::ModuleLength, Metrics::ParameterLists, Metrics::PerceivedComplexity, Performance::CaseWhenSplat, Performance::Count, Performance::Detect, Performance::FixedSize, Performance::FlatMap, Performance::ReverseEach, Performance::Sample, Performance::Size, Performance::StringReplacement, Rails::ActionFilter, Rails::Date, Rails::DefaultScope, Rails::Delegate, Rails::FindBy, Rails::FindEach, Rails::HasAndBelongsToMany, Rails::Output, Rails::PluralizationGrammar, Rails::ReadWriteAttribute, Rails::ScopeArgs, Rails::TimeZone, Rails::Validation, Style::AccessModifierIndentation, Style::AccessorMethodName, Style::Alias, Style::AlignArray, Style::AlignHash, Style::AlignParameters, Style::AndOr, Style::ArrayJoin, Style::AsciiComments, Style::AsciiIdentifiers, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BlockComments, Style::BlockDelimiters, Style::BlockEndNewline, Style::BracesAroundHashParameters, Style::CaseEquality, Style::CaseIndentation, Style::CharacterLiteral, Style::ClassAndModuleCamelCase, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassMethods, Style::ClassVars, Style::ClosingParenthesisIndentation, Style::CollectionMethods, Style::ColonMethodCall, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentIndentation, Style::ConstantName, Style::Copyright, Style::DefWithParentheses, Style::DeprecatedHashMethods, Style::Documentation, Style::DotPosition, Style::DoubleNegation, Style::EachWithObject, Style::ElseAlignment, Style::EmptyElse, Style::EmptyLineBetweenDefs, Style::EmptyLines, Style::EmptyLinesAroundAccessModifier, Style::EmptyLinesAroundBlockBody, Style::EmptyLinesAroundClassBody, Style::EmptyLinesAroundMethodBody, Style::EmptyLinesAroundModuleBody, Style::EmptyLiteral, Style::Encoding, Style::EndBlock, Style::EndOfLine, Style::EvenOdd, Style::ExtraSpacing, Style::FileName, Style::FirstArrayElementLineBreak, Style::FirstHashElementLineBreak, Style::FirstMethodArgumentLineBreak, Style::FirstMethodParameterLineBreak, Style::FirstParameterIndentation, Style::FlipFlop, Style::For, Style::FormatString, Style::GlobalVars, Style::GuardClause, Style::HashSyntax, Style::IfUnlessModifier, Style::IfWithSemicolon, Style::IndentArray, Style::IndentHash, Style::IndentationConsistency, Style::IndentationWidth, Style::InfiniteLoop, Style::InitialIndentation, Style::InlineComment, Style::Lambda, Style::LambdaCall, Style::LeadingCommentSpace, Style::LineEndConcatenation, Style::MethodCallParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MethodName, Style::MissingElse, Style::ModuleFunction, Style::MultilineBlockChain, Style::MultilineBlockLayout, Style::MultilineIfThen, Style::MultilineOperationIndentation, Style::MultilineTernaryOperator, Style::MutableConstant, Style::NegatedIf, Style::NegatedWhile, Style::NestedModifier, Style::NestedTernaryOperator, Style::Next, Style::NilComparison, Style::NonNilCheck, Style::Not, Style::NumericLiterals, Style::OneLineConditional, Style::OpMethod, Style::OptionHash, Style::OptionalArguments, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PredicateName, Style::Proc, Style::RaiseArgs, Style::RedundantBegin, Style::RedundantException, Style::RedundantFreeze, Style::RedundantReturn, Style::RedundantSelf, Style::RegexpLiteral, Style::RescueEnsureAlignment, Style::RescueModifier, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SignalException, Style::SingleLineBlockParams, Style::SingleLineMethods, Style::SingleSpaceBeforeFirstArg, Style::SpaceAfterColon, Style::SpaceAfterComma, Style::SpaceAfterControlKeyword, Style::SpaceAfterMethodName, Style::SpaceAfterNot, Style::SpaceAfterSemicolon, Style::SpaceAroundBlockParameters, Style::SpaceAroundEqualsInParameterDefault, Style::SpaceAroundOperators, Style::SpaceBeforeBlockBraces, Style::SpaceBeforeComma, Style::SpaceBeforeComment, Style::SpaceBeforeModifierKeyword, Style::SpaceBeforeSemicolon, Style::SpaceInsideBlockBraces, Style::SpaceInsideBrackets, Style::SpaceInsideHashLiteralBraces, Style::SpaceInsideParens, Style::SpaceInsideRangeLiteral, Style::SpaceInsideStringInterpolation, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StringLiterals, Style::StringLiteralsInInterpolation, Style::StringMethods, Style::StructInheritance, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::Tab, Style::TrailingBlankLines, Style::TrailingComma, Style::TrailingUnderscoreVariable, Style::TrailingWhitespace, Style::TrivialAccessors, Style::UnlessElse, Style::UnneededCapitalW, Style::UnneededPercentQ, Style::VariableInterpolation, Style::VariableName, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray

Constant Summary

Constants included from Util

Util::ASGN_NODES, Util::BASIC_LITERALS, Util::EQUALS_ASGN_NODES, Util::LITERALS, Util::OPERATOR_METHODS, Util::PROC_NEW_NODE, Util::SHORTHAND_ASGN_NODES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from NodePattern::Macros

def_node_matcher, def_node_search

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

begins_its_line?, block_length, command?, comment_line?, const_name, directions, first_part_of_call_chain, lambda?, lambda_or_proc?, line_range, move_pos, numeric_range_size, on_node, operator?, parentheses?, proc?, range_with_surrounding_comma, range_with_surrounding_space, source_range, strip_quotes, within_node?

Methods included from PathUtil

hidden?, issue_deprecation_warning, match_path?, relative_path

Constructor Details

#initialize(config = nil, options = nil) ⇒ Cop

Returns a new instance of Cop.


111
112
113
114
115
116
117
# File 'lib/rubocop/cop/cop.rb', line 111

def initialize(config = nil, options = nil)
  @config = config || Config.new
  @options = options || { debug: false }

  @offenses = []
  @corrections = []
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config


74
75
76
# File 'lib/rubocop/cop/cop.rb', line 74

def config
  @config
end

#correctionsObject (readonly)

Returns the value of attribute corrections


74
75
76
# File 'lib/rubocop/cop/cop.rb', line 74

def corrections
  @corrections
end

#offensesObject (readonly)

Returns the value of attribute offenses


74
75
76
# File 'lib/rubocop/cop/cop.rb', line 74

def offenses
  @offenses
end

#processed_sourceObject

TODO: Bad design.


75
76
77
# File 'lib/rubocop/cop/cop.rb', line 75

def processed_source
  @processed_source
end

Class Method Details

.allObject


79
80
81
# File 'lib/rubocop/cop/cop.rb', line 79

def self.all
  @all.without_type(:test)
end

.cop_nameObject


95
96
97
# File 'lib/rubocop/cop/cop.rb', line 95

def self.cop_name
  @cop_name ||= name.to_s.split('::').last(2).join('/')
end

.cop_typeObject


99
100
101
# File 'lib/rubocop/cop/cop.rb', line 99

def self.cop_type
  name.to_s.split('::')[-2].downcase.to_sym
end

.inherited(subclass) ⇒ Object


91
92
93
# File 'lib/rubocop/cop/cop.rb', line 91

def self.inherited(subclass)
  @all << subclass
end

.lint?Boolean

Returns:

  • (Boolean)

103
104
105
# File 'lib/rubocop/cop/cop.rb', line 103

def self.lint?
  cop_type == :lint
end

.match?(given_names) ⇒ Boolean

Returns true if the cop name or the cop namespace matches any of the given names.

Returns:

  • (Boolean)

149
150
151
152
153
154
# File 'lib/rubocop/cop/cop.rb', line 149

def self.match?(given_names)
  return false unless given_names

  given_names.include?(cop_name) ||
    given_names.include?(cop_type.to_s.capitalize)
end

.non_railsObject


87
88
89
# File 'lib/rubocop/cop/cop.rb', line 87

def self.non_rails
  all.without_type(:rails)
end

.qualified_cop_name(name, origin) ⇒ Object


83
84
85
# File 'lib/rubocop/cop/cop.rb', line 83

def self.qualified_cop_name(name, origin)
  @all.qualified_cop_name(name, origin)
end

.rails?Boolean

Returns:

  • (Boolean)

107
108
109
# File 'lib/rubocop/cop/cop.rb', line 107

def self.rails?
  cop_type == :rails
end

Instance Method Details

#add_offense(node, loc, message = nil, severity = nil) ⇒ Object


160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/rubocop/cop/cop.rb', line 160

def add_offense(node, loc, message = nil, severity = nil)
  location = loc.is_a?(Symbol) ? node.loc.send(loc) : loc

  # Don't include the same location twice for one cop.
  return if @offenses.any? { |o| o.location == location }

  severity = custom_severity || severity || default_severity

  message ||= message(node)
  message = annotate_message(message)

  status = enabled_line?(location.line) ? correct(node) : :disabled

  @offenses << Offense.new(severity, location, message, name, status)
  yield if block_given? && status != :disabled
end

#config_to_allow_offensesObject


187
188
189
190
# File 'lib/rubocop/cop/cop.rb', line 187

def config_to_allow_offenses
  Formatter::DisabledConfigFormatter
    .config_to_allow_offenses[cop_name] ||= {}
end

#config_to_allow_offenses=(hash) ⇒ Object


192
193
194
195
# File 'lib/rubocop/cop/cop.rb', line 192

def config_to_allow_offenses=(hash)
  Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] =
    hash
end

#cop_configObject


123
124
125
# File 'lib/rubocop/cop/cop.rb', line 123

def cop_config
  @config.for_cop(self)
end

#cop_nameObject Also known as: name


197
198
199
# File 'lib/rubocop/cop/cop.rb', line 197

def cop_name
  self.class.cop_name
end

#correct(node) ⇒ Object


177
178
179
180
181
182
183
184
185
# File 'lib/rubocop/cop/cop.rb', line 177

def correct(node)
  return :unsupported unless support_autocorrect?
  return :uncorrected unless autocorrect?

  correction = autocorrect(node)
  return :uncorrected unless correction
  @corrections << correction
  :corrected
end

#debug?Boolean

Returns:

  • (Boolean)

127
128
129
# File 'lib/rubocop/cop/cop.rb', line 127

def debug?
  @options[:debug]
end

#detailsObject


222
223
224
225
# File 'lib/rubocop/cop/cop.rb', line 222

def details
  details = cop_config && cop_config['Details']
  (details.nil? || details.empty?) ? nil : details
end

#display_cop_names?Boolean

Returns:

  • (Boolean)

131
132
133
134
# File 'lib/rubocop/cop/cop.rb', line 131

def display_cop_names?
  debug? || @options[:display_cop_names] ||
    config['AllCops'] && config['AllCops']['DisplayCopNames']
end

#display_style_guide?Boolean

Returns:

  • (Boolean)

136
137
138
139
140
# File 'lib/rubocop/cop/cop.rb', line 136

def display_style_guide?
  (style_guide_url || reference_url) &&
    (@options[:display_style_guide] ||
      config['AllCops'] && config['AllCops']['DisplayStyleGuide'])
end

#excluded_file?(file) ⇒ Boolean

Returns:

  • (Boolean)

208
209
210
# File 'lib/rubocop/cop/cop.rb', line 208

def excluded_file?(file)
  !relevant_file?(file)
end

#extra_details?Boolean

Returns:

  • (Boolean)

142
143
144
145
# File 'lib/rubocop/cop/cop.rb', line 142

def extra_details?
  @options[:extra_details] ||
    config['AllCops'] && config['AllCops']['ExtraDetails']
end

#join_force?(_force_class) ⇒ Boolean

Returns:

  • (Boolean)

119
120
121
# File 'lib/rubocop/cop/cop.rb', line 119

def join_force?(_force_class)
  false
end

#message(_node = nil) ⇒ Object


156
157
158
# File 'lib/rubocop/cop/cop.rb', line 156

def message(_node = nil)
  self.class::MSG
end

#reference_urlObject


217
218
219
220
# File 'lib/rubocop/cop/cop.rb', line 217

def reference_url
  url = cop_config['Reference']
  (url.nil? || url.empty?) ? nil : url
end

#relevant_file?(file) ⇒ Boolean

Returns:

  • (Boolean)

203
204
205
206
# File 'lib/rubocop/cop/cop.rb', line 203

def relevant_file?(file)
  file_name_matches_any?(file, 'Include', true) &&
    !file_name_matches_any?(file, 'Exclude', false)
end

#style_guide_urlObject


212
213
214
215
# File 'lib/rubocop/cop/cop.rb', line 212

def style_guide_url
  url = cop_config['StyleGuide']
  (url.nil? || url.empty?) ? nil : url
end