diff --git a/CHANGELOG.md b/CHANGELOG.md index 460a457cf2a..0ad1e87ba57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ * [#8354](https://github.com/rubocop-hq/rubocop/issues/8354): Detect regexp named captures in `Style/CaseLikeIf` cop. ([@dsavochkin][]) * [#8830](https://github.com/rubocop-hq/rubocop/issues/8830): Fix bad autocorrect of `Style/StringConcatenation` when string includes double quotes. ([@tleish][]) * [#8807](https://github.com/rubocop-hq/rubocop/pull/8807): Fix a false positive for `Style/RedundantCondition` when using assignment by hash key access. ([@koic][]) +* [#8843](https://github.com/rubocop-hq/rubocop/issues/8843): Fix invalid `Lint/AmbiguousRegexpLiteral` autocorrect when the original node had internal parentheses. ([@dvandersluis][]) ### Changes diff --git a/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb b/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb index 87a70ff284a..d2133b23608 100644 --- a/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb +++ b/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb @@ -35,7 +35,8 @@ def on_new_investigation offense_node = find_offense_node_by(diagnostic) add_offense(diagnostic.location, severity: diagnostic.level) do |corrector| - add_parentheses(offense_node, corrector) + corrector.replace(diagnostic.location.begin.adjust(begin_pos: -1), '(') + corrector.insert_after(offense_node, ')') end end end diff --git a/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb b/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb index 47e3e211528..597e7847db4 100644 --- a/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb +++ b/spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb @@ -55,6 +55,17 @@ end RUBY end + + it 'correctly handles inner parentheses' do + expect_offense(<<~RUBY) + assert /foobar/.match('foo') + ^ 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) + assert(/foobar/.match('foo')) + RUBY + end end context 'with parentheses' do