From 1c20b60020bcf5c7fe9e5e9668fe24b965dbab0f Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Mon, 20 Sep 2021 10:18:58 -0400 Subject: [PATCH] [Fix #10096] Fix `Lint/AmbiguousOperatorPrecedence` with `and`/`or` operators. --- .../fix_fix_lintambiguousoperatorprecedence_with.md | 1 + .../cop/lint/ambiguous_operator_precedence.rb | 6 +++++- .../cop/lint/ambiguous_operator_precedence_spec.rb | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_fix_lintambiguousoperatorprecedence_with.md diff --git a/changelog/fix_fix_lintambiguousoperatorprecedence_with.md b/changelog/fix_fix_lintambiguousoperatorprecedence_with.md new file mode 100644 index 000000000000..336ed90e8a75 --- /dev/null +++ b/changelog/fix_fix_lintambiguousoperatorprecedence_with.md @@ -0,0 +1 @@ +* [#10096](https://github.com/rubocop/rubocop/issues/10096): Fix `Lint/AmbiguousOperatorPrecedence` with `and`/`or` operators. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb b/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb index 10969a5a3461..9d694ae8cc5b 100644 --- a/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb +++ b/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb @@ -87,7 +87,11 @@ def operator?(node) end def greater_precedence?(node1, node2) - precedence(node2) > precedence(node1) + node1_precedence = precedence(node1) + node2_precedence = precedence(node2) + return false unless node1_precedence && node2_precedence + + node2_precedence > node1_precedence end def operator_name(node) diff --git a/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb b/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb index 1d653212e7f2..f0188d4f86f4 100644 --- a/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb +++ b/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb @@ -120,4 +120,16 @@ a || (b && (c | d ^ (e & (f << g >> (h + i - (j * k / l % (n ** m))))))) RUBY end + + it 'allows an operator with `and`' do + expect_no_offenses(<<~RUBY) + array << i and next + RUBY + end + + it 'allows an operator with `or`' do + expect_no_offenses(<<~RUBY) + array << i or return + RUBY + end end