Skip to content

Commit

Permalink
Fix possible wrong autocorrection in namespace on Style/PerlBackrefs
Browse files Browse the repository at this point in the history
  • Loading branch information
r7kamura committed Aug 29, 2022
1 parent 65de62e commit bad82a0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
@@ -0,0 +1 @@
* [#10975](https://github.com/rubocop/rubocop/pull/10975): Fix possible wrong autocorrection in namespace on `Style/PerlBackrefs`. ([@r7kamura][])
23 changes: 22 additions & 1 deletion lib/rubocop/cop/style/perl_backrefs.rb
Expand Up @@ -83,10 +83,31 @@ def preferred_expression_to(node)
end
end

# @private
# @param [RuboCop::AST::Node] node
# @return [String, nil]
def preferred_expression_to_node_with_constant_prefix(node)
expression = preferred_expression_to(node)
return unless expression

"#{constant_prefix(node)}#{expression}"
end

# @private
# @param [RuboCop::AST::Node] node
# @return [String]
def constant_prefix(node)
if node.each_ancestor(:class, :module).any?
'::'
else
''
end
end

# @private
# @param [RuboCop::AST::Node] node
def on_back_ref_or_gvar_or_nth_ref(node)
preferred_expression = preferred_expression_to(node)
preferred_expression = preferred_expression_to_node_with_constant_prefix(node)
return unless preferred_expression

add_offense(
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/perl_backrefs_spec.rb
Expand Up @@ -143,4 +143,25 @@
/#{Regexp.last_match(1)}/
RUBY
end

it 'autocorrects $1 to ::Regexp.last_match(1) in namespace' do
expect_offense(<<~RUBY)
module Foo
class Regexp
end
puts $1
^^ Prefer `::Regexp.last_match(1)` over `$1`.
end
RUBY

expect_correction(<<~RUBY)
module Foo
class Regexp
end
puts ::Regexp.last_match(1)
end
RUBY
end
end

0 comments on commit bad82a0

Please sign in to comment.