From 13ad14b22d77b2b9041c77cb70262db700fe1b02 Mon Sep 17 00:00:00 2001 From: hotate29 Date: Sat, 11 Dec 2021 02:32:23 +0900 Subject: [PATCH] update: ```Sugg::not()``` replacing the comparison operator. #7320 When inverting an expression, the output is now like ```foo != 0``` instead of ```!(foo == 0)```, the comparison operator is now replaced. --- clippy_utils/src/sugg.rs | 29 ++++++++++++++++++++++++- tests/ui/short_circuit_statement.fixed | 2 +- tests/ui/short_circuit_statement.stderr | 2 +- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index 586934df4..cf46a7579 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -394,7 +394,34 @@ impl Neg for Sugg<'_> { impl Not for Sugg<'_> { type Output = Sugg<'static>; fn not(self) -> Sugg<'static> { - make_unop("!", self) + use AssocOp::{Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual}; + + /// Convert ```AssocOp``` to a string of operators. + fn op_as_str(op: AssocOp) -> &'static str { + op.to_ast_binop().unwrap().to_string() + } + + /// Replace the operator in the Snippet. + fn replace_op(from_op: AssocOp, to_op: AssocOp, snip: Cow<'_, str>) -> Sugg<'static> { + let from = op_as_str(from_op); + let to = op_as_str(to_op); + let snip = snip.into_owned().replace(from, to); + Sugg::BinOp(to_op, Cow::Owned(snip)) + } + + if let Sugg::BinOp(op, snip) = self { + match op { + Equal => replace_op(op, NotEqual, snip), + NotEqual => replace_op(op, Equal, snip), + Less => replace_op(op, GreaterEqual, snip), + GreaterEqual => replace_op(op, Less, snip), + Greater => replace_op(op, LessEqual, snip), + LessEqual => replace_op(op, Greater, snip), + _ => make_unop("!", Sugg::BinOp(op, snip)), + } + } else { + make_unop("!", self) + } } } diff --git a/tests/ui/short_circuit_statement.fixed b/tests/ui/short_circuit_statement.fixed index af0a397bd..dd22ecab0 100644 --- a/tests/ui/short_circuit_statement.fixed +++ b/tests/ui/short_circuit_statement.fixed @@ -6,7 +6,7 @@ fn main() { if f() { g(); } if !f() { g(); } - if !(1 == 2) { g(); } + if 1 != 2 { g(); } } fn f() -> bool { diff --git a/tests/ui/short_circuit_statement.stderr b/tests/ui/short_circuit_statement.stderr index 0a3f60c3d..aa84ac3a7 100644 --- a/tests/ui/short_circuit_statement.stderr +++ b/tests/ui/short_circuit_statement.stderr @@ -16,7 +16,7 @@ error: boolean short circuit operator in statement may be clearer using an expli --> $DIR/short_circuit_statement.rs:9:5 | LL | 1 == 2 || g(); - | ^^^^^^^^^^^^^^ help: replace it with: `if !(1 == 2) { g(); }` + | ^^^^^^^^^^^^^^ help: replace it with: `if 1 != 2 { g(); }` error: aborting due to 3 previous errors