Skip to content

Commit 148b70e

Browse files
committed
Fix rewrite of closures with a return type
If the closure's body fits in a line, the block is removed but it is necessary if the closure has a return type.
1 parent 10b95e0 commit 148b70e

File tree

3 files changed

+44
-10
lines changed

3 files changed

+44
-10
lines changed

Diff for: src/formatting/closures.rs

+13-10
Original file line numberDiff line numberDiff line change
@@ -409,18 +409,21 @@ pub(crate) fn rewrite_last_closure(
409409
if is_block_closure_forced(context, body, capture) {
410410
return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
411411
|body_str| {
412-
// If the expression can fit in a single line, we need not force block closure.
413-
if body_str.lines().count() <= 7 {
414-
match rewrite_closure_expr(body, &prefix, context, shape) {
415-
Some(ref single_line_body_str)
416-
if !single_line_body_str.contains('\n') =>
417-
{
418-
single_line_body_str.clone()
412+
match fn_decl.output {
413+
ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
414+
// If the expression can fit in a single line, we need not force block
415+
// closure. However, if the closure has a return type, then we must
416+
// keep the blocks.
417+
match rewrite_closure_expr(body, &prefix, context, shape) {
418+
Some(ref single_line_body_str)
419+
if !single_line_body_str.contains('\n') =>
420+
{
421+
single_line_body_str.clone()
422+
}
423+
_ => body_str,
419424
}
420-
_ => body_str,
421425
}
422-
} else {
423-
body_str
426+
_ => body_str,
424427
}
425428
},
426429
);

Diff for: tests/source/issue-4577.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
fn main() {
2+
let s: String = "ABAABBAA".chars()
3+
.filter(|c| {
4+
if *c == 'A' {
5+
true
6+
}
7+
else {
8+
false
9+
}
10+
})
11+
.map(|c| -> char {
12+
if c == 'A' {
13+
'0'
14+
} else {
15+
'1'
16+
}
17+
}).collect();
18+
19+
println!("{}", s);
20+
}

Diff for: tests/target/issue-4577.rs

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fn main() {
2+
let s: String = "ABAABBAA"
3+
.chars()
4+
.filter(|c| if *c == 'A' { true } else { false })
5+
.map(|c| -> char {
6+
if c == 'A' { '0' } else { '1' }
7+
})
8+
.collect();
9+
10+
println!("{}", s);
11+
}

0 commit comments

Comments
 (0)