diff --git a/changelog/fix_a_false_positive_for_style_double_negation.md b/changelog/fix_a_false_positive_for_style_double_negation.md new file mode 100644 index 000000000000..6a81166fa92a --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_double_negation.md @@ -0,0 +1 @@ +* [#10518](https://github.com/rubocop/rubocop/pull/10518): Fix a false positive for `Style/DoubleNegation` when inside returned conditional clauses with Ruby 2.7's pattern matching. ([@koic][]) diff --git a/rubocop.gemspec b/rubocop.gemspec index 2d0df5c854b4..a0aae198cd47 100644 --- a/rubocop.gemspec +++ b/rubocop.gemspec @@ -36,7 +36,7 @@ Gem::Specification.new do |s| s.add_runtime_dependency('rainbow', '>= 2.2.2', '< 4.0') s.add_runtime_dependency('regexp_parser', '>= 1.8', '< 3.0') s.add_runtime_dependency('rexml') - s.add_runtime_dependency('rubocop-ast', '>= 1.16.0', '< 2.0') + s.add_runtime_dependency('rubocop-ast', '>= 1.17.0', '< 2.0') s.add_runtime_dependency('ruby-progressbar', '~> 1.7') s.add_runtime_dependency('unicode-display_width', '>= 1.4.0', '< 3.0') diff --git a/spec/rubocop/cop/style/double_negation_spec.rb b/spec/rubocop/cop/style/double_negation_spec.rb index 4a1ddaed946a..149ff602eef0 100644 --- a/spec/rubocop/cop/style/double_negation_spec.rb +++ b/spec/rubocop/cop/style/double_negation_spec.rb @@ -291,6 +291,48 @@ def foo? RUBY end + # rubocop:disable RSpec/RepeatedExampleGroupDescription + context 'Ruby >= 2.7', :ruby27 do + # rubocop:enable RSpec/RepeatedExampleGroupDescription + it 'registers an offense and corrects for `!!` when not return location' \ + 'and using `case`, `in`, and `else`' do + expect_offense(<<~RUBY) + def foo? + case pattern + in foo + !!foo + ^ Avoid the use of double negation (`!!`). + do_something + in bar + !!bar + ^ Avoid the use of double negation (`!!`). + do_something + else + !!baz + ^ Avoid the use of double negation (`!!`). + do_something + end + end + RUBY + + expect_correction(<<~RUBY) + def foo? + case pattern + in foo + !foo.nil? + do_something + in bar + !bar.nil? + do_something + else + !baz.nil? + do_something + end + end + RUBY + end + end + it 'does not register an offense for `!!` when return location' do expect_no_offenses(<<~RUBY) def foo? @@ -544,6 +586,39 @@ def foo? end RUBY end + + # rubocop:disable RSpec/RepeatedExampleGroupDescription + context 'Ruby >= 2.7', :ruby27 do + # rubocop:enable RSpec/RepeatedExampleGroupDescription + it 'does not register an offense for `!!` when return location and using `case`, `in`, and `else`' do + expect_no_offenses(<<~RUBY) + def foo? + case condition + in foo + !!foo + in bar + !!bar + else + !!baz + end + end + + def bar? + case condition + in foo + do_something + !!foo + in bar + do_something + !!bar + else + do_something + !!baz + end + end + RUBY + end + end end context 'when `EnforcedStyle: forbidden`' do