Skip to content

Commit

Permalink
Merge pull request #10003 from koic/fix_incorrect_autocorrect_for_lin…
Browse files Browse the repository at this point in the history
…t_ambiguous_regexp_literal

[Fix #10002] Fix an incorrect auto-correct for `Lint/AmbigousRegexpLiteral`
  • Loading branch information
dvandersluis committed Aug 11, 2021
2 parents 8588024 + d3d9488 commit 7c4c927
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
@@ -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

0 comments on commit 7c4c927

Please sign in to comment.