Unnamed repository; edit this file 'description' to name the repository.
Merge pull request #21485 from A4-Tacks/move-guard-clean-block
Improve move_guard redundanted block
Shoyu Vanilla (Flint) 3 months ago
parent 66463ea · parent 4db75a1 · commit b5eb57a
-rw-r--r--crates/ide-assists/src/handlers/move_guard.rs35
-rw-r--r--crates/ide-assists/src/utils.rs11
2 files changed, 42 insertions, 4 deletions
diff --git a/crates/ide-assists/src/handlers/move_guard.rs b/crates/ide-assists/src/handlers/move_guard.rs
index 31baa63372..84f02bdfdb 100644
--- a/crates/ide-assists/src/handlers/move_guard.rs
+++ b/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();
@@ -345,6 +345,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(
move_guard_to_arm_body,
@@ -395,9 +424,7 @@ fn main() {
&& true
&& true {
{
- {
- false
- }
+ false
}
},
_ => true
diff --git a/crates/ide-assists/src/utils.rs b/crates/ide-assists/src/utils.rs
index 9a96374c00..4b8c193057 100644
--- a/crates/ide-assists/src/utils.rs
+++ b/crates/ide-assists/src/utils.rs
@@ -86,6 +86,17 @@ pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Ex
None
}
+pub(crate) fn wrap_block(expr: &ast::Expr) -> 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.