1 use ra_syntax::{AstNode, ast};
2 use ra_fmt::extract_trivial_expression;
3 use hir::db::HirDatabase;
5 use crate::{AssistCtx, Assist};
7 pub(crate) fn replace_if_let_with_match(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
8 let if_expr: &ast::IfExpr = ctx.node_at_offset()?;
9 let cond = if_expr.condition()?;
10 let pat = cond.pat()?;
11 let expr = cond.expr()?;
12 let then_block = if_expr.then_branch()?;
13 let else_block = match if_expr.else_branch()? {
14 ast::ElseBranchFlavor::Block(it) => it,
15 ast::ElseBranchFlavor::IfExpr(_) => return None,
18 ctx.build("replace with match", |edit| {
19 let match_expr = build_match_expr(expr, pat, then_block, else_block);
20 edit.target(if_expr.syntax().range());
21 edit.replace_node_and_indent(if_expr.syntax(), match_expr);
22 edit.set_cursor(if_expr.syntax().range().start())
32 let mut buf = String::new();
33 buf.push_str(&format!("match {} {{\n", expr.syntax().text()));
34 buf.push_str(&format!(" {} => {}\n", pat1.syntax().text(), format_arm(arm1)));
35 buf.push_str(&format!(" _ => {}\n", format_arm(arm2)));
40 fn format_arm(block: &ast::Block) -> String {
41 match extract_trivial_expression(block) {
42 None => block.syntax().text().to_string(),
43 Some(e) => format!("{},", e.syntax().text()),
50 use crate::helpers::{check_assist, check_assist_target};
53 fn test_replace_if_let_with_match_unwraps_simple_expressions() {
55 replace_if_let_with_match,
58 pub fn is_struct(&self) -> bool {
59 if <|>let VariantData::Struct(..) = *self {
68 pub fn is_struct(&self) -> bool {
70 VariantData::Struct(..) => true,
79 fn replace_if_let_with_match_target() {
81 replace_if_let_with_match,
84 pub fn is_struct(&self) -> bool {
85 if <|>let VariantData::Struct(..) = *self {
92 "if let VariantData::Struct(..) = *self {