@@ -494,7 +494,17 @@ impl<T: Display> Display for ParenHelper<T> {
494494/// operators have the same
495495/// precedence.
496496pub 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 } ;
0 commit comments