Skip to content

Commit 2f94401

Browse files
committed
Sugg: do not parenthesize a double unary operator
For example, adding `*` in front of `*expression` is best shown as `**expression` rather than `*(*expression)`.
1 parent f8a3929 commit 2f94401

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

clippy_utils/src/sugg.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,17 @@ impl<T: Display> Display for ParenHelper<T> {
494494
/// operators have the same
495495
/// precedence.
496496
pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
497-
Sugg::MaybeParen(format!("{op}{}", expr.maybe_paren()).into())
497+
// If the `expr` starts with `op` already, do not add wrap it in
498+
// parentheses.
499+
let expr = if let Sugg::MaybeParen(ref sugg) = expr
500+
&& !has_enclosing_paren(sugg)
501+
&& sugg.starts_with(op)
502+
{
503+
expr
504+
} else {
505+
expr.maybe_paren()
506+
};
507+
Sugg::MaybeParen(format!("{op}{expr}").into())
498508
}
499509

500510
/// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
@@ -1016,6 +1026,18 @@ mod test {
10161026
let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
10171027
assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
10181028
}
1029+
1030+
#[test]
1031+
fn unop_parenthesize() {
1032+
let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::And), "true".into(), "false".into());
1033+
assert_eq!("true && false", sugg.to_string());
1034+
let sugg = !sugg;
1035+
assert_eq!("!(true && false)", sugg.to_string());
1036+
let sugg = !sugg;
1037+
assert_eq!("!!(true && false)", sugg.to_string());
1038+
assert_eq!("(!!(true && false))", sugg.maybe_paren().to_string());
1039+
}
1040+
10191041
#[test]
10201042
fn not_op() {
10211043
use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};

tests/ui/nonminimal_bool.stderr

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ error: inequality checks against true can be replaced by a negation
179179
--> tests/ui/nonminimal_bool.rs:186:8
180180
|
181181
LL | if !b != true {}
182-
| ^^^^^^^^^^ help: try simplifying it as shown: `!(!b)`
182+
| ^^^^^^^^^^ help: try simplifying it as shown: `!!b`
183183

184184
error: this boolean expression can be simplified
185185
--> tests/ui/nonminimal_bool.rs:189:8
@@ -209,7 +209,7 @@ error: inequality checks against true can be replaced by a negation
209209
--> tests/ui/nonminimal_bool.rs:193:8
210210
|
211211
LL | if true != !b {}
212-
| ^^^^^^^^^^ help: try simplifying it as shown: `!(!b)`
212+
| ^^^^^^^^^^ help: try simplifying it as shown: `!!b`
213213

214214
error: this boolean expression can be simplified
215215
--> tests/ui/nonminimal_bool.rs:196:8

0 commit comments

Comments
 (0)