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.
This commit is contained in:
hotate29 2021-12-11 02:32:23 +09:00
parent 53059792e9
commit 13ad14b22d
No known key found for this signature in database
GPG key ID: DB720E72A6380B5A
3 changed files with 30 additions and 3 deletions

View file

@ -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)
}
}
}

View file

@ -6,7 +6,7 @@
fn main() {
if f() { g(); }
if !f() { g(); }
if !(1 == 2) { g(); }
if 1 != 2 { g(); }
}
fn f() -> bool {

View file

@ -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