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 #10002] Fix an incorrect auto-correct for Lint/AmbigousRegexpLiteral #10003

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 @@
* [#10002](https://github.com/rubocop/rubocop/issues/10002): Fix an incorrect auto-correct for `Lint/AmbigousRegexpLiteral` when using nested method arguments without parentheses. ([@koic][])
7 changes: 5 additions & 2 deletions lib/rubocop/cop/lint/ambiguous_regexp_literal.rb
Expand Up @@ -46,12 +46,11 @@ def find_offense_node_by(diagnostic)
node = processed_source.ast.each_node(:regexp).find do |regexp_node|
regexp_node.source_range.begin_pos == diagnostic.location.begin_pos
end

find_offense_node(node.parent, node)
end

def find_offense_node(node, regexp_receiver)
return node unless node.parent
return node if first_argument_is_regexp?(node) || !node.parent

if (node.parent.send_type? && node.receiver) ||
method_chain_to_regexp_receiver?(node, regexp_receiver)
Expand All @@ -61,6 +60,10 @@ def find_offense_node(node, regexp_receiver)
node
end

def first_argument_is_regexp?(node)
node.send_type? && node.first_argument&.regexp_type?
end

def method_chain_to_regexp_receiver?(node, regexp_receiver)
return false unless (parent = node.parent)
return false unless (parent_receiver = parent.receiver)
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb
Expand Up @@ -127,6 +127,17 @@ class MyTest
end
RUBY
end

it 'registers an offense and corrects when using nested method arguments without parentheses' do
expect_offense(<<~RUBY)
puts line.grep /pattern/
^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division.
RUBY

expect_correction(<<~RUBY)
puts line.grep(/pattern/)
RUBY
end
end

context 'with parentheses' do
Expand Down