@@ -494,7 +494,17 @@ impl<T: Display> Display for ParenHelper<T> {
494
494
/// operators have the same
495
495
/// precedence.
496
496
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 ( ) )
498
508
}
499
509
500
510
/// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
@@ -1016,6 +1026,18 @@ mod test {
1016
1026
let sugg = Sugg :: BinOp ( AssocOp :: Binary ( ast:: BinOpKind :: Add ) , "(1 + 1)" . into ( ) , "(1 + 1)" . into ( ) ) ;
1017
1027
assert_eq ! ( "((1 + 1) + (1 + 1))" , sugg. maybe_paren( ) . to_string( ) ) ;
1018
1028
}
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
+
1019
1041
#[ test]
1020
1042
fn not_op ( ) {
1021
1043
use ast:: BinOpKind :: { Add , And , Eq , Ge , Gt , Le , Lt , Ne , Or } ;
0 commit comments