Skip to content

Commit

Permalink
Use parentheses when needed in nonminimal_bool lint (#14187)
Browse files Browse the repository at this point in the history
Since comparisons on types not implementing `Ord` (such as `f32`) are
not inverted, they must be enclosed in parentheses when they are
negated.

Fix #14184

changelog: [`nonminimal_bool`]: add required parentheses when negating a
binary expression
  • Loading branch information
llogiq authored Feb 10, 2025
2 parents 521a800 + b32ad4c commit 8939915
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
4 changes: 3 additions & 1 deletion clippy_lints/src/booleans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(_) => {
Expand Down
6 changes: 6 additions & 0 deletions tests/ui/nonminimal_bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
8 changes: 7 additions & 1 deletion tests/ui/nonminimal_bool.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 8939915

Please sign in to comment.