aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs')
-rw-r--r--crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs81
1 files changed, 0 insertions, 81 deletions
diff --git a/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs b/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
deleted file mode 100644
index 71880b919..000000000
--- a/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
+++ /dev/null
@@ -1,81 +0,0 @@
1use ra_syntax::{AstNode, ast};
2
3use crate::{
4 assists::{AssistCtx, Assist},
5 formatting::extract_trivial_expression,
6};
7
8pub fn replace_if_let_with_match(ctx: AssistCtx) -> Option<Assist> {
9 let if_expr: &ast::IfExpr = ctx.node_at_offset()?;
10 let cond = if_expr.condition()?;
11 let pat = cond.pat()?;
12 let expr = cond.expr()?;
13 let then_block = if_expr.then_branch()?;
14 let else_block = match if_expr.else_branch()? {
15 ast::ElseBranchFlavor::Block(it) => it,
16 ast::ElseBranchFlavor::IfExpr(_) => return None,
17 };
18
19 ctx.build("replace with match", |edit| {
20 let match_expr = build_match_expr(expr, pat, then_block, else_block);
21 edit.replace_node_and_indent(if_expr.syntax(), match_expr);
22 edit.set_cursor(if_expr.syntax().range().start())
23 })
24}
25
26fn build_match_expr(
27 expr: &ast::Expr,
28 pat1: &ast::Pat,
29 arm1: &ast::Block,
30 arm2: &ast::Block,
31) -> String {
32 let mut buf = String::new();
33 buf.push_str(&format!("match {} {{\n", expr.syntax().text()));
34 buf.push_str(&format!(
35 " {} => {}\n",
36 pat1.syntax().text(),
37 format_arm(arm1)
38 ));
39 buf.push_str(&format!(" _ => {}\n", format_arm(arm2)));
40 buf.push_str("}");
41 buf
42}
43
44fn format_arm(block: &ast::Block) -> String {
45 match extract_trivial_expression(block) {
46 None => block.syntax().text().to_string(),
47 Some(e) => format!("{},", e.syntax().text()),
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54 use crate::assists::check_assist;
55
56 #[test]
57 fn test_replace_if_let_with_match_unwraps_simple_expressions() {
58 check_assist(
59 replace_if_let_with_match,
60 "
61impl VariantData {
62 pub fn is_struct(&self) -> bool {
63 if <|>let VariantData::Struct(..) = *self {
64 true
65 } else {
66 false
67 }
68 }
69} ",
70 "
71impl VariantData {
72 pub fn is_struct(&self) -> bool {
73 <|>match *self {
74 VariantData::Struct(..) => true,
75 _ => false,
76 }
77 }
78} ",
79 )
80 }
81}