From b32ad4ce0a7f4aeb4dbb63032d8f42f67b773b14 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 10 Feb 2025 10:47:50 +0100 Subject: [PATCH] Use parentheses when needed in `nonminimal_bool` lint Since comparisons on types not implementing `Ord` (such as `f32`) are not inverted, they must be enclosed in parentheses when they are negated. --- clippy_lints/src/booleans.rs | 4 +++- tests/ui/nonminimal_bool.rs | 6 ++++++ tests/ui/nonminimal_bool.stderr | 8 +++++++- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/booleans.rs b/clippy_lints/src/booleans.rs index f8c30d1c881d0..ee21f9379a527 100644 --- a/clippy_lints/src/booleans.rs +++ b/clippy_lints/src/booleans.rs @@ -3,6 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then}; use clippy_utils::eq_expr_value; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::SpanRangeExt; +use clippy_utils::sugg::Sugg; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use rustc_ast::ast::LitKind; use rustc_attr_parsing::RustcVersion; @@ -353,7 +354,8 @@ impl SuggestContext<'_, '_, '_> { self.output.push_str(&str); } else { self.output.push('!'); - self.output.push_str(&terminal.span.get_source_text(self.cx)?); + self.output + .push_str(&Sugg::hir_opt(self.cx, terminal)?.maybe_par().to_string()); } }, True | False | Not(_) => { diff --git a/tests/ui/nonminimal_bool.rs b/tests/ui/nonminimal_bool.rs index 52b0155a762ea..9d0a475064edb 100644 --- a/tests/ui/nonminimal_bool.rs +++ b/tests/ui/nonminimal_bool.rs @@ -183,3 +183,9 @@ fn issue_12371(x: usize) -> bool { fn many_ops(a: bool, b: bool, c: bool, d: bool, e: bool, f: bool) -> bool { (a && c && f) || (!a && b && !d) || (!b && !c && !e) || (d && e && !f) } + +fn issue14184(a: f32, b: bool) { + if !(a < 2.0 && !b) { + println!("Hi"); + } +} diff --git a/tests/ui/nonminimal_bool.stderr b/tests/ui/nonminimal_bool.stderr index 578f918f01392..129dadf315e41 100644 --- a/tests/ui/nonminimal_bool.stderr +++ b/tests/ui/nonminimal_bool.stderr @@ -213,5 +213,11 @@ error: this boolean expression can be simplified LL | if !b != !c {} | ^^^^^^^^ help: try: `b != c` -error: aborting due to 29 previous errors +error: this boolean expression can be simplified + --> tests/ui/nonminimal_bool.rs:188:8 + | +LL | if !(a < 2.0 && !b) { + | ^^^^^^^^^^^^^^^^ help: try: `!(a < 2.0) || b` + +error: aborting due to 30 previous errors