@@ -79,7 +79,7 @@ pub fn format_expr(
79
79
let callee_str = callee. rewrite ( context, shape) ?;
80
80
rewrite_call ( context, & callee_str, args, inner_span, shape)
81
81
}
82
- ast:: ExprKind :: Paren ( ref subexpr) => rewrite_paren ( context, subexpr, shape) ,
82
+ ast:: ExprKind :: Paren ( ref subexpr) => rewrite_paren ( context, subexpr, shape, expr . span ) ,
83
83
ast:: ExprKind :: Binary ( ref op, ref lhs, ref rhs) => {
84
84
// FIXME: format comments between operands and operator
85
85
rewrite_pair (
@@ -2425,8 +2425,36 @@ fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2425
2425
result
2426
2426
}
2427
2427
2428
- fn rewrite_paren ( context : & RewriteContext , subexpr : & ast:: Expr , shape : Shape ) -> Option < String > {
2428
+ fn rewrite_paren (
2429
+ context : & RewriteContext ,
2430
+ mut subexpr : & ast:: Expr ,
2431
+ shape : Shape ,
2432
+ mut span : Span ,
2433
+ ) -> Option < String > {
2429
2434
debug ! ( "rewrite_paren, shape: {:?}" , shape) ;
2435
+
2436
+ // Extract comments within parens.
2437
+ let mut pre_comment;
2438
+ let mut post_comment;
2439
+ loop {
2440
+ // 1 = "(" or ")"
2441
+ let pre_span = mk_sp ( span. lo ( ) + BytePos ( 1 ) , subexpr. span . lo ( ) ) ;
2442
+ let post_span = mk_sp ( subexpr. span . hi ( ) , span. hi ( ) - BytePos ( 1 ) ) ;
2443
+ pre_comment = rewrite_missing_comment ( pre_span, shape, context) ?;
2444
+ post_comment = rewrite_missing_comment ( post_span, shape, context) ?;
2445
+
2446
+ // Remove nested parens if there are no comments.
2447
+ if let ast:: ExprKind :: Paren ( ref subsubexpr) = subexpr. node {
2448
+ if pre_comment. is_empty ( ) && post_comment. is_empty ( ) {
2449
+ span = subexpr. span ;
2450
+ subexpr = subsubexpr;
2451
+ continue ;
2452
+ }
2453
+ }
2454
+
2455
+ break ;
2456
+ }
2457
+
2430
2458
let total_paren_overhead = paren_overhead ( context) ;
2431
2459
let paren_overhead = total_paren_overhead / 2 ;
2432
2460
let sub_shape = shape
@@ -2435,9 +2463,9 @@ fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) ->
2435
2463
2436
2464
let paren_wrapper = |s : & str | {
2437
2465
if context. config . spaces_within_parens_and_brackets ( ) && !s. is_empty ( ) {
2438
- format ! ( "( {} )" , s )
2466
+ format ! ( "( {}{}{} )" , pre_comment , s , post_comment )
2439
2467
} else {
2440
- format ! ( "({})" , s )
2468
+ format ! ( "({}{}{} )" , pre_comment , s , post_comment )
2441
2469
}
2442
2470
} ;
2443
2471
0 commit comments