Skip to content

Commit 13ad14b

Browse files
committed
update: Sugg::not() replacing the comparison operator. rust-lang#7320
When inverting an expression, the output is now like ```foo != 0``` instead of ```!(foo == 0)```, the comparison operator is now replaced.
1 parent 5305979 commit 13ad14b

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

clippy_utils/src/sugg.rs

+28-1
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,34 @@ impl Neg for Sugg<'_> {
394394
impl Not for Sugg<'_> {
395395
type Output = Sugg<'static>;
396396
fn not(self) -> Sugg<'static> {
397-
make_unop("!", self)
397+
use AssocOp::{Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual};
398+
399+
/// Convert ```AssocOp``` to a string of operators.
400+
fn op_as_str(op: AssocOp) -> &'static str {
401+
op.to_ast_binop().unwrap().to_string()
402+
}
403+
404+
/// Replace the operator in the Snippet.
405+
fn replace_op(from_op: AssocOp, to_op: AssocOp, snip: Cow<'_, str>) -> Sugg<'static> {
406+
let from = op_as_str(from_op);
407+
let to = op_as_str(to_op);
408+
let snip = snip.into_owned().replace(from, to);
409+
Sugg::BinOp(to_op, Cow::Owned(snip))
410+
}
411+
412+
if let Sugg::BinOp(op, snip) = self {
413+
match op {
414+
Equal => replace_op(op, NotEqual, snip),
415+
NotEqual => replace_op(op, Equal, snip),
416+
Less => replace_op(op, GreaterEqual, snip),
417+
GreaterEqual => replace_op(op, Less, snip),
418+
Greater => replace_op(op, LessEqual, snip),
419+
LessEqual => replace_op(op, Greater, snip),
420+
_ => make_unop("!", Sugg::BinOp(op, snip)),
421+
}
422+
} else {
423+
make_unop("!", self)
424+
}
398425
}
399426
}
400427

tests/ui/short_circuit_statement.fixed

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
fn main() {
77
if f() { g(); }
88
if !f() { g(); }
9-
if !(1 == 2) { g(); }
9+
if 1 != 2 { g(); }
1010
}
1111

1212
fn f() -> bool {

tests/ui/short_circuit_statement.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ error: boolean short circuit operator in statement may be clearer using an expli
1616
--> $DIR/short_circuit_statement.rs:9:5
1717
|
1818
LL | 1 == 2 || g();
19-
| ^^^^^^^^^^^^^^ help: replace it with: `if !(1 == 2) { g(); }`
19+
| ^^^^^^^^^^^^^^ help: replace it with: `if 1 != 2 { g(); }`
2020

2121
error: aborting due to 3 previous errors
2222

0 commit comments

Comments
 (0)