Skip to content

Commit

Permalink
[Fix #8053] Fix an incorrect auto-correct for Style/AndOr
Browse files Browse the repository at this point in the history
Fixes #8053.

This PR fixes an incorrect auto-correct for `Style/AndOr`
when `or` precedes `and`.
  • Loading branch information
koic authored and bbatsov committed Nov 25, 2020
1 parent 978d563 commit e20ea9d
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_incorrect_autocorrect_for_style_and_or.md
@@ -0,0 +1 @@
* [#8053](https://github.com/rubocop-hq/rubocop/issues/8053): Fix an incorrect auto-correct for `Style/AndOr` when `or` precedes `and`. ([@koic][])
10 changes: 10 additions & 0 deletions lib/rubocop/cop/style/and_or.rb
Expand Up @@ -72,6 +72,8 @@ def process_logical_operator(node)
end

corrector.replace(node.loc.operator, node.alternate_operator)

keep_operator_precedence(corrector, node)
end
end

Expand Down Expand Up @@ -123,6 +125,14 @@ def correct_other(node, corrector)
corrector.wrap(node, '(', ')')
end

def keep_operator_precedence(corrector, node)
if node.or_type? && node.parent&.and_type?
corrector.wrap(node, '(', ')')
elsif node.and_type? && node.rhs.or_type?
corrector.wrap(node.rhs, '(', ')')
end
end

def correctable_send?(node)
!node.parenthesized? && node.arguments? && !node.method?(:[])
end
Expand Down
54 changes: 54 additions & 0 deletions spec/rubocop/cop/style/and_or_spec.rb
Expand Up @@ -508,6 +508,60 @@ def y
end
end

context 'when `or` precedes `and`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo or bar and baz
^^ Use `||` instead of `or`.
^^^ Use `&&` instead of `and`.
RUBY

expect_correction(<<~RUBY)
(foo || bar) && baz
RUBY
end
end

context 'when `or` precedes `&&`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo or bar && baz
^^ Use `||` instead of `or`.
RUBY

expect_correction(<<~RUBY)
foo || bar && baz
RUBY
end
end

context 'when `and` precedes `or`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo and bar or baz
^^^ Use `&&` instead of `and`.
^^ Use `||` instead of `or`.
RUBY

expect_correction(<<~RUBY)
foo && bar || baz
RUBY
end
end

context 'when `and` precedes `||`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo and bar || baz
^^^ Use `&&` instead of `and`.
RUBY

expect_correction(<<~RUBY)
foo && (bar || baz)
RUBY
end
end

context 'within a nested begin node with one child only' do
# regression test; see GH issue 2531
it 'autocorrects "and" with && and adds parens' do
Expand Down

0 comments on commit e20ea9d

Please sign in to comment.