Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion clippy_utils/src/sugg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,17 @@ impl<T: Display> Display for ParenHelper<T> {
/// operators have the same
/// precedence.
pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
Sugg::MaybeParen(format!("{op}{}", expr.maybe_paren()).into())
// If the `expr` starts with `op` already, do not add wrap it in
// parentheses.
let expr = if let Sugg::MaybeParen(ref sugg) = expr
&& !has_enclosing_paren(sugg)
&& sugg.starts_with(op)
{
expr
} else {
expr.maybe_paren()
};
Sugg::MaybeParen(format!("{op}{expr}").into())
}

/// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
Expand Down Expand Up @@ -1016,6 +1026,16 @@ mod test {
let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
}

#[test]
fn unop_parenthesize() {
let sugg = Sugg::NonParen("x".into()).mut_addr();
assert_eq!("&mut x", sugg.to_string());
let sugg = sugg.mut_addr();
assert_eq!("&mut &mut x", sugg.to_string());
assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
}

#[test]
fn not_op() {
use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/nonminimal_bool.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ error: inequality checks against true can be replaced by a negation
--> tests/ui/nonminimal_bool.rs:186:8
|
LL | if !b != true {}
| ^^^^^^^^^^ help: try simplifying it as shown: `!(!b)`
| ^^^^^^^^^^ help: try simplifying it as shown: `!!b`

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

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