Skip to content

Commit ca8776a

Browse files
scampicalebcartwright
authored andcommitted
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 5092b63 commit ca8776a

File tree

3 files changed

+48
-10
lines changed

3 files changed

+48
-10
lines changed

Diff for: src/closures.rs

+13-10
Original file line numberDiff line numberDiff line change
@@ -339,18 +339,21 @@ pub(crate) fn rewrite_last_closure(
339339
if is_block_closure_forced(context, body) {
340340
return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
341341
|body_str| {
342-
// If the expression can fit in a single line, we need not force block closure.
343-
if body_str.lines().count() <= 7 {
344-
match rewrite_closure_expr(body, &prefix, context, shape) {
345-
Some(ref single_line_body_str)
346-
if !single_line_body_str.contains('\n') =>
347-
{
348-
Some(single_line_body_str.clone())
342+
match fn_decl.output {
343+
ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
344+
// If the expression can fit in a single line, we need not force block
345+
// closure. However, if the closure has a return type, then we must
346+
// keep the blocks.
347+
match rewrite_closure_expr(body, &prefix, context, shape) {
348+
Some(ref single_line_body_str)
349+
if !single_line_body_str.contains('\n') =>
350+
{
351+
Some(single_line_body_str.clone())
352+
}
353+
_ => Some(body_str),
349354
}
350-
_ => Some(body_str),
351355
}
352-
} else {
353-
Some(body_str)
356+
_ => Some(body_str),
354357
}
355358
},
356359
);

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

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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' {
7+
'0'
8+
} else {
9+
'1'
10+
}
11+
})
12+
.collect();
13+
14+
println!("{}", s);
15+
}

0 commit comments

Comments
 (0)