Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix possible wrong autocorrection in namespace on Style/PerlBackrefs #10975

Merged
merged 1 commit into from Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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