diff --git a/changelog/fix_incorrect_autocorrect_for_lint_ambiguous_regexp_literal.md b/changelog/fix_incorrect_autocorrect_for_lint_ambiguous_regexp_literal.md new file mode 100644 index 00000000000..72baf596377 --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_lint_ambiguous_regexp_literal.md @@ -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][]) diff --git a/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb b/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb index 470d7c3aabf..b411791a95b 100644 --- a/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb +++ b/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb @@ -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) @@ -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) diff --git a/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb b/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb index 651d4580ee8..1226cf639e9 100644 --- a/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb +++ b/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb @@ -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