forked from rubocop/rubocop
/
base.rb
423 lines (344 loc) · 12.7 KB
/
base.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# frozen_string_literal: true
module RuboCop
module Cop
# A scaffold for concrete cops.
#
# The Cop::Base 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.
#
# First the callback `on_new_investigation` is called;
# if a cop needs to do its own processing of the AST or depends on
# something else.
#
# Then callbacks like `on_def`, `on_send` (see AST::Traversal) are called
# with their respective nodes.
#
# Finally the callback `on_investigation_end` is called.
#
# Within these callbacks, cops are meant to call `add_offense` or
# `add_global_offense`. Use the `processed_source` method to
# get the currently processed source being investigated.
#
# In case of invalid syntax / unparseable content,
# the callback `on_other_file` is called instead of all the other
# `on_...` callbacks.
#
# Private methods are not meant for custom cops consumption,
# nor are any instance variables.
#
class Base # rubocop:disable Metrics/ClassLength
extend RuboCop::AST::Sexp
extend NodePattern::Macros
include RuboCop::AST::Sexp
include Util
include IgnoredNode
include AutocorrectLogic
attr_reader :config, :processed_source
# Reports of an investigation.
# Immutable
# Consider creation API private
InvestigationReport = Struct.new(:cop, :processed_source, :offenses, :corrector)
# List of cops that should not try to autocorrect at the same
# time as this cop
#
# @return [Array<RuboCop::Cop::Cop>]
#
# @api public
def self.autocorrect_incompatible_with
[]
end
# Cops (other than builtin) are encouraged to implement this
# @return [String, nil]
#
# @api public
def self.documentation_url
Documentation.url_for(self) if builtin?
end
def initialize(config = nil, options = nil)
@config = config || Config.new
@options = options || { debug: false }
reset_investigation
end
# Called before all on_... have been called
# When refining this method, always call `super`
def on_new_investigation
# Typically do nothing here
end
# Called after all on_... have been called
# When refining this method, always call `super`
def on_investigation_end
# Typically do nothing here
end
# Called instead of all on_... callbacks for unrecognized files / syntax errors
# When refining this method, always call `super`
def on_other_file
# Typically do nothing here
end
# Override and return the Force class(es) you need to join
def self.joining_forces; end
# 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
def message(_range = nil)
self.class::MSG
end
# Adds an offense that has no particular location.
# No correction can be applied to global offenses
def add_global_offense(message = nil, severity: nil)
severity = find_severity(nil, severity)
message = find_message(nil, message)
@current_offenses <<
Offense.new(severity, Offense::NO_LOCATION, message, name, :unsupported)
end
# 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.
# If message is not specified, the method `message` will be called.
def add_offense(node_or_range, message: nil, severity: nil, &block)
range = range_from_node_or_range(node_or_range)
return unless current_offense_locations.add?(range)
range_to_pass = callback_argument(range)
severity = find_severity(range_to_pass, severity)
message = find_message(range_to_pass, message)
status, corrector = enabled_line?(range.line) ? correct(range, &block) : :disabled
@current_offenses << Offense.new(severity, range, message, name, status, corrector)
end
# This method should be overridden when a cop's behavior depends
# on state that lives outside of these locations:
#
# (1) the file under inspection
# (2) the cop's source code
# (3) the config (eg a .rubocop.yml file)
#
# For example, some cops may want to look at other parts of
# the codebase being inspected to find violations. A cop may
# use the presence or absence of file `foo.rb` to determine
# whether a certain violation exists in `bar.rb`.
#
# Overriding this method allows the cop to indicate to RuboCop's
# ResultCache system when those external dependencies change,
# ie when the ResultCache should be invalidated.
def external_dependency_checksum
nil
end
def self.inherited(subclass)
super
Registry.global.enlist(subclass)
end
# Call for abstract Cop classes
def self.exclude_from_registry
Registry.global.dismiss(self)
end
# Returns if class supports auto_correct.
# It is recommended to extend AutoCorrector instead of overriding
def self.support_autocorrect?
false
end
### Naming
def self.badge
@badge ||= Badge.for(name)
end
def self.cop_name
badge.to_s
end
def self.department
badge.department
end
def self.lint?
department == :Lint
end
# Returns true if the cop name or the cop namespace matches any of the
# given names.
def self.match?(given_names)
return false unless given_names
given_names.include?(cop_name) ||
given_names.include?(department.to_s)
end
def cop_name
@cop_name ||= self.class.cop_name
end
alias name cop_name
### Configuration Helpers
def cop_config
# Use department configuration as basis, but let individual cop
# configuration override.
@cop_config ||= @config.for_badge(self.class.badge)
end
def config_to_allow_offenses
Formatter::DisabledConfigFormatter
.config_to_allow_offenses[cop_name] ||= {}
end
def config_to_allow_offenses=(hash)
Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] =
hash
end
def target_ruby_version
@config.target_ruby_version
end
def target_rails_version
@config.target_rails_version
end
def relevant_file?(file)
file == RuboCop::AST::ProcessedSource::STRING_SOURCE_NAME ||
file_name_matches_any?(file, 'Include', true) &&
!file_name_matches_any?(file, 'Exclude', false)
end
def excluded_file?(file)
!relevant_file?(file)
end
### Persistence
# 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.
# You should invalidate any caches that depend on the current `processed_source`
# in the `on_new_investigation` callback.
# If your cop does autocorrections, be aware that your instance may be called
# multiple times with the same `processed_source.path` but different content.
def self.support_multiple_source?
false
end
# @api private
# Called between investigations
def ready
return self if self.class.support_multiple_source?
self.class.new(@config, @options)
end
### Reserved for Cop::Cop
# @deprecated Make potential errors with previous API more obvious
def offenses
raise 'The offenses are not directly available; ' \
'they are returned as the result of the investigation'
end
private
### Reserved for Cop::Cop
def callback_argument(range)
range
end
def apply_correction(corrector)
@current_corrector&.merge!(corrector) if corrector
end
def correction_strategy
return :unsupported unless correctable?
return :uncorrected unless autocorrect?
:attempt_correction
end
### Reserved for Commissioner:
def current_offense_locations
@current_offense_locations ||= Set.new
end
def currently_disabled_lines
@currently_disabled_lines ||= Set.new
end
# Called before any investigation
def begin_investigation(processed_source)
@current_offenses = []
@current_offense_locations = nil
@currently_disabled_lines = nil
@processed_source = processed_source
@current_corrector = Corrector.new(@processed_source) if @processed_source.valid_syntax?
end
# Called to complete an investigation
def complete_investigation
InvestigationReport.new(self, processed_source, @current_offenses, @current_corrector)
ensure
reset_investigation
end
### Actually private methods
def self.builtin?
return false unless (m = instance_methods(false).first) # any custom method will do
path, _line = instance_method(m).source_location
path.start_with?(__dir__)
end
private_class_method :builtin?
def reset_investigation
@currently_disabled_lines = @current_offenses = @processed_source = @current_corrector = nil
end
# @return [Symbol, Corrector] offense status
def correct(range)
status = correction_strategy
if block_given?
corrector = Corrector.new(self)
yield corrector
if !corrector.empty? && !self.class.support_autocorrect?
raise "The Cop #{name} must `extend AutoCorrector` to be able to autocorrect"
end
end
status = attempt_correction(range, corrector) if status == :attempt_correction
[status, corrector]
end
# @return [Symbol] offense status
def attempt_correction(range, corrector)
if corrector && !corrector.empty?
status = :corrected
elsif disable_uncorrectable?
corrector = disable_uncorrectable(range)
status = :corrected_with_todo
else
return :uncorrected
end
apply_correction(corrector) if corrector
status
end
def disable_uncorrectable(range)
line = range.line
return unless currently_disabled_lines.add?(line)
disable_offense(range)
end
def range_from_node_or_range(node_or_range)
if node_or_range.respond_to?(:loc)
node_or_range.loc.expression
elsif node_or_range.is_a?(::Parser::Source::Range)
node_or_range
else
extra = ' (call `add_global_offense`)' if node_or_range.nil?
raise "Expected a Source::Range, got #{node_or_range.inspect}#{extra}"
end
end
def find_message(range, message)
annotate(message || message(range))
end
def annotate(message)
RuboCop::Cop::MessageAnnotator.new(
config, cop_name, cop_config, @options
).annotate(message)
end
def file_name_matches_any?(file, parameter, default_result)
patterns = cop_config[parameter]
return default_result unless patterns
path = nil
patterns.any? do |pattern|
# Try to match the absolute path, as Exclude properties are absolute.
next true if match_path?(pattern, file)
# Try with relative path.
path ||= config.path_relative_to_config(file)
match_path?(pattern, path)
end
end
def enabled_line?(line_number)
return true if @options[:ignore_disable_comments] || !@processed_source
@processed_source.comment_config.cop_enabled_at_line?(self, line_number)
end
def find_severity(_range, severity)
custom_severity || severity || default_severity
end
def default_severity
self.class.lint? ? :warning : :convention
end
def custom_severity
severity = cop_config['Severity']
return unless severity
if Severity::NAMES.include?(severity.to_sym)
severity.to_sym
else
message = "Warning: Invalid severity '#{severity}'. " \
"Valid severities are #{Severity::NAMES.join(', ')}."
warn(Rainbow(message).red)
end
end
end
end
end