From c31698b6958b5c818e4f4c86d3e4d12e128152f9 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Sat, 17 Jan 2026 19:24:19 +0800 Subject: [PATCH] Improve move_guard redundanted block Example --- ```rust fn main() { match 92 { x $0if x > 10 => { let _ = true; false }, _ => true } } ``` **Before this PR** ```rust fn main() { match 92 { x => if x > 10 { { let _ = true; false } }, _ => true } } ``` **After this PR** ```rust fn main() { match 92 { x => if x > 10 { let _ = true; false }, _ => true } } ``` --- .../ide-assists/src/handlers/move_guard.rs | 35 ++++++++++++++++--- .../crates/ide-assists/src/utils.rs | 11 ++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_guard.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_guard.rs index 31baa63372ff..84f02bdfdba6 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_guard.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_guard.rs @@ -49,7 +49,7 @@ pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext<'_>) let guard_condition = guard.condition()?.reset_indent(); let arm_expr = match_arm.expr()?; - let then_branch = make::block_expr(None, Some(arm_expr.reset_indent().indent(1.into()))); + let then_branch = crate::utils::wrap_block(&arm_expr); let if_expr = make::expr_if(guard_condition, then_branch, None).indent(arm_expr.indent_level()); let target = guard.syntax().text_range(); @@ -344,6 +344,35 @@ fn main() { ); } + #[test] + fn move_guard_to_block_arm_body_works() { + check_assist( + move_guard_to_arm_body, + r#" +fn main() { + match 92 { + x $0if x > 10 => { + let _ = true; + false + }, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x => if x > 10 { + let _ = true; + false + }, + _ => true + } +} +"#, + ); + } + #[test] fn move_let_guard_to_arm_body_works() { check_assist( @@ -395,9 +424,7 @@ fn main() { && true && true { { - { - false - } + false } }, _ => true diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs index 9a96374c00af..4b8c19305793 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs @@ -86,6 +86,17 @@ pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option ast::BlockExpr { + if let ast::Expr::BlockExpr(block) = expr + && let Some(first) = block.syntax().first_token() + && first.kind() == T!['{'] + { + block.reset_indent() + } else { + make::block_expr(None, Some(expr.reset_indent().indent(1.into()))) + } +} + /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as /// `#[test_case(...)]`, `#[tokio::test]` and similar. /// Also a regular `#[test]` annotation is supported.