From b21c80cb2598bf477e61aba14085e4a7f14d53b9 Mon Sep 17 00:00:00 2001 From: Alexander Glusker Date: Fri, 29 Mar 2024 10:29:39 +0300 Subject: [PATCH] Ignoring empty statements in closures. Resolve #6116 --- src/closures.rs | 16 ++++++++++++++-- tests/source/issue-6116/main.rs | 7 +++++++ tests/target/issue-6116/main.rs | 3 +++ 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 tests/source/issue-6116/main.rs create mode 100644 tests/target/issue-6116/main.rs diff --git a/src/closures.rs b/src/closures.rs index 1f59fbc2960..4aa0930e9d0 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -108,7 +108,10 @@ fn get_inner_expr<'a>( if !needs_block(block, prefix, context) { // block.stmts.len() == 1 except with `|| {{}}`; // https://github.com/rust-lang/rustfmt/issues/3844 - if let Some(expr) = block.stmts.first().and_then(stmt_expr) { + if let Some(expr) = iter_stmts_without_empty(&block.stmts) + .next() + .and_then(stmt_expr) + { return get_inner_expr(expr, prefix, context); } } @@ -117,6 +120,15 @@ fn get_inner_expr<'a>( expr } +fn iter_stmts_without_empty( + stmts: &thin_vec::ThinVec, +) -> impl Iterator { + stmts.iter().filter(|x| match x.kind { + crate::ast::StmtKind::Empty => false, + _ => true, + }) +} + // Figure out if a block is necessary. fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool { let has_attributes = block.stmts.first().map_or(false, |first_stmt| { @@ -124,7 +136,7 @@ fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) - }); is_unsafe_block(block) - || block.stmts.len() > 1 + || iter_stmts_without_empty(&block.stmts).count() > 1 || has_attributes || block_contains_comment(context, block) || prefix.contains('\n') diff --git a/tests/source/issue-6116/main.rs b/tests/source/issue-6116/main.rs new file mode 100644 index 00000000000..910131a4761 --- /dev/null +++ b/tests/source/issue-6116/main.rs @@ -0,0 +1,7 @@ +fn foo() -> fn(i32) -> i32 { + |a| { + ; + a + } +} + diff --git a/tests/target/issue-6116/main.rs b/tests/target/issue-6116/main.rs new file mode 100644 index 00000000000..dc0e48f1bfe --- /dev/null +++ b/tests/target/issue-6116/main.rs @@ -0,0 +1,3 @@ +fn foo() -> fn(i32) -> i32 { + |a| a +}