aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src')
-rw-r--r--crates/ra_assists/src/assists/replace_if_let_with_match.rs49
1 files changed, 22 insertions, 27 deletions
diff --git a/crates/ra_assists/src/assists/replace_if_let_with_match.rs b/crates/ra_assists/src/assists/replace_if_let_with_match.rs
index c9b62e5ff..c8b13b7b3 100644
--- a/crates/ra_assists/src/assists/replace_if_let_with_match.rs
+++ b/crates/ra_assists/src/assists/replace_if_let_with_match.rs
@@ -1,9 +1,12 @@
1use format_buf::format;
2use hir::db::HirDatabase; 1use hir::db::HirDatabase;
3use ra_fmt::extract_trivial_expression; 2use ra_fmt::unwrap_trivial_block;
4use ra_syntax::{ast, AstNode}; 3use ra_syntax::{
4 ast::{self, make},
5 AstNode,
6};
5 7
6use crate::{Assist, AssistCtx, AssistId}; 8use crate::{Assist, AssistCtx, AssistId};
9use ast::edit::IndentLevel;
7 10
8// Assist: replace_if_let_with_match 11// Assist: replace_if_let_with_match
9// 12//
@@ -43,32 +46,24 @@ pub(crate) fn replace_if_let_with_match(ctx: AssistCtx<impl HirDatabase>) -> Opt
43 }; 46 };
44 47
45 ctx.add_assist(AssistId("replace_if_let_with_match"), "Replace with match", |edit| { 48 ctx.add_assist(AssistId("replace_if_let_with_match"), "Replace with match", |edit| {
46 let match_expr = build_match_expr(expr, pat, then_block, else_block); 49 let match_expr = {
47 edit.target(if_expr.syntax().text_range()); 50 let then_arm = {
48 edit.replace_node_and_indent(if_expr.syntax(), match_expr); 51 let then_expr = unwrap_trivial_block(then_block);
49 edit.set_cursor(if_expr.syntax().text_range().start()) 52 make::match_arm(vec![pat], then_expr)
50 }) 53 };
51} 54 let else_arm = {
55 let else_expr = unwrap_trivial_block(else_block);
56 make::match_arm(vec![make::placeholder_pat().into()], else_expr)
57 };
58 make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm]))
59 };
52 60
53fn build_match_expr( 61 let match_expr = IndentLevel::from_node(if_expr.syntax()).increase_indent(match_expr);
54 expr: ast::Expr,
55 pat1: ast::Pat,
56 arm1: ast::BlockExpr,
57 arm2: ast::BlockExpr,
58) -> String {
59 let mut buf = String::new();
60 format!(buf, "match {} {{\n", expr.syntax().text());
61 format!(buf, " {} => {}\n", pat1.syntax().text(), format_arm(&arm1));
62 format!(buf, " _ => {}\n", format_arm(&arm2));
63 buf.push_str("}");
64 buf
65}
66 62
67fn format_arm(block: &ast::BlockExpr) -> String { 63 edit.target(if_expr.syntax().text_range());
68 match extract_trivial_expression(block) { 64 edit.set_cursor(if_expr.syntax().text_range().start());
69 Some(e) if !e.syntax().text().contains_char('\n') => format!("{},", e.syntax().text()), 65 edit.replace_ast::<ast::Expr>(if_expr.into(), match_expr.into());
70 _ => block.syntax().text().to_string(), 66 })
71 }
72} 67}
73 68
74#[cfg(test)] 69#[cfg(test)]