Skip to content

Commit

Permalink
[Fix rubocop#11549] Fix an error for third party cops
Browse files Browse the repository at this point in the history
Fixes rubocop#11549.

This PR fixes an error for third party cops when inheriting `RuboCop::Cop::Cop`.
It makes the same changes to `RuboCop::Cop::Cop` as `RuboCop::Cop::Base` in rubocop#10839.
Confirmed that rubocop-i18n tests pass again.
  • Loading branch information
koic committed Feb 8, 2023
1 parent 9ee83ab commit eaf6850
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_third_party_cops.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11549](https://github.com/rubocop/rubocop/issues/11549): Fix an error for third party cops when inheriting `RuboCop::Cop::Cop`. ([@koic][])
26 changes: 23 additions & 3 deletions lib/rubocop/cop/cop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ def self.qualified_cop_name(name, origin)
def add_offense(node_or_range, location: :expression, message: nil, severity: nil, &block)
@v0_argument = node_or_range
range = find_location(node_or_range, location)

# Since this range may be generated from Ruby code embedded in some
# template file, we convert it to location info in the original file.
range = range_for_original(range)

if block.nil? && !support_autocorrect?
super(range, message: message, severity: severity)
else
Expand Down Expand Up @@ -93,14 +98,21 @@ def on_investigation_end
super
end

private

def begin_investigation(processed_source)
# Called before any investigation
# @api private
def begin_investigation(processed_source, offset: 0, original: processed_source)
super
@offenses = current_offenses
@last_corrector = @current_corrector

# We need to keep track of the original source and offset,
# because `processed_source` here may be an embedded code in it.
@current_offset = offset
@current_original = original
end

private

# Override Base
def callback_argument(_range)
@v0_argument
Expand Down Expand Up @@ -141,6 +153,14 @@ def suppress_clobbering
rescue ::Parser::ClobberingError
# ignore Clobbering errors
end

def range_for_original(range)
::Parser::Source::Range.new(
@current_original.buffer,
range.begin_pos + @current_offset,
range.end_pos + @current_offset
)
end
end
end
end

0 comments on commit eaf6850

Please sign in to comment.