1 use std::iter::{self, successors};
4 use ide_db::{defs::NameClass, ty_filter::TryEnum, RootDatabase};
8 edit::{AstNodeEdit, IndentLevel},
15 utils::{does_pat_match_variant, unwrap_trivial_block},
16 AssistContext, AssistId, AssistKind, Assists,
19 // Assist: replace_if_let_with_match
21 // Replaces a `if let` expression with a `match` expression.
24 // enum Action { Move { distance: u32 }, Stop }
26 // fn handle(action: Action) {
27 // $0if let Action::Move { distance } = action {
36 // enum Action { Move { distance: u32 }, Stop }
38 // fn handle(action: Action) {
40 // Action::Move { distance } => foo(distance),
45 pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
46 let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
47 let mut else_block = None;
48 let if_exprs = successors(Some(if_expr.clone()), |expr| match expr.else_branch()? {
49 ast::ElseBranch::IfExpr(expr) => Some(expr),
50 ast::ElseBranch::Block(block) => {
51 else_block = Some(block);
55 let scrutinee_to_be_expr = if_expr.condition()?.expr()?;
57 let mut pat_seen = false;
58 let mut cond_bodies = Vec::new();
59 for if_expr in if_exprs {
60 let cond = if_expr.condition()?;
61 let expr = cond.expr()?;
62 let cond = match cond.pat() {
64 if scrutinee_to_be_expr.syntax().text() != expr.syntax().text() {
65 // Only if all condition expressions are equal we can merge them into a match
71 None => Either::Right(expr),
73 let body = if_expr.then_branch()?;
74 cond_bodies.push((cond, body));
78 // Don't offer turning an if (chain) without patterns into a match
82 let target = if_expr.syntax().text_range();
84 AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
85 "Replace if let with match",
89 let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
90 let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
91 let body = body.reset_indent().indent(IndentLevel(1));
93 Either::Left(pat) => {
94 make::match_arm(iter::once(pat), None, unwrap_trivial_block(body))
96 Either::Right(expr) => make::match_arm(
97 iter::once(make::wildcard_pat().into()),
99 unwrap_trivial_block(body),
103 let arms = cond_bodies.into_iter().map(make_match_arm).chain(iter::once(else_arm));
104 let match_expr = make::expr_match(scrutinee_to_be_expr, make::match_arm_list(arms));
105 match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
108 let has_preceding_if_expr =
109 if_expr.syntax().parent().map_or(false, |it| ast::IfExpr::can_cast(it.kind()));
110 let expr = if has_preceding_if_expr {
111 // make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
112 make::block_expr(None, Some(match_expr)).into()
116 edit.replace_ast::<ast::Expr>(if_expr.into(), expr);
123 else_block: Option<ast::BlockExpr>,
124 conditionals: &[(Either<ast::Pat, ast::Expr>, ast::BlockExpr)],
126 if let Some(else_block) = else_block {
127 let pattern = if let [(Either::Left(pat), _)] = conditionals {
130 .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
135 let pattern = match pattern {
137 if does_pat_match_variant(&pat, &it.sad_pattern()) {
143 None => make::wildcard_pat().into(),
145 make::match_arm(iter::once(pattern), None, unwrap_trivial_block(else_block))
147 make::match_arm(iter::once(make::wildcard_pat().into()), None, make::expr_unit().into())
151 // Assist: replace_match_with_if_let
153 // Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression.
156 // enum Action { Move { distance: u32 }, Stop }
158 // fn handle(action: Action) {
160 // Action::Move { distance } => foo(distance),
167 // enum Action { Move { distance: u32 }, Stop }
169 // fn handle(action: Action) {
170 // if let Action::Move { distance } = action {
177 pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
178 let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?;
180 let mut arms = match_expr.match_arm_list()?.arms();
181 let (first_arm, second_arm) = (arms.next()?, arms.next()?);
182 if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() {
186 let (if_let_pat, then_expr, else_expr) = pick_pattern_and_expr_order(
193 let scrutinee = match_expr.expr()?;
195 let target = match_expr.syntax().text_range();
197 AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
198 "Replace match with if let",
201 let condition = make::condition(scrutinee, Some(if_let_pat));
202 let then_block = match then_expr.reset_indent() {
203 ast::Expr::BlockExpr(block) => block,
204 expr => make::block_expr(iter::empty(), Some(expr)),
206 let else_expr = match else_expr {
207 ast::Expr::BlockExpr(block) if block.is_empty() => None,
208 ast::Expr::TupleExpr(tuple) if tuple.fields().next().is_none() => None,
211 let if_let_expr = make::expr_if(
215 .map(|expr| match expr {
216 ast::Expr::BlockExpr(block) => block,
217 expr => (make::block_expr(iter::empty(), Some(expr))),
219 .map(ast::ElseBranch::Block),
221 .indent(IndentLevel::from_node(match_expr.syntax()));
223 edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
228 /// Pick the pattern for the if let condition and return the expressions for the `then` body and `else` body in that order.
229 fn pick_pattern_and_expr_order(
230 sema: &hir::Semantics<RootDatabase>,
235 ) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
236 let res = match (pat, pat2) {
237 (ast::Pat::WildcardPat(_), _) => return None,
238 (pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
239 (_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
240 (pat, pat2) => match (binds_name(sema, &pat), binds_name(sema, &pat2)) {
241 (true, true) => return None,
242 (true, false) => (pat, expr, expr2),
243 (false, true) => (pat2, expr2, expr),
244 _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
245 (false, false) => (pat, expr, expr2),
251 fn is_empty_expr(expr: &ast::Expr) -> bool {
253 ast::Expr::BlockExpr(expr) => expr.is_empty(),
254 ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
259 fn binds_name(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
260 let binds_name_v = |pat| binds_name(&sema, &pat);
262 ast::Pat::IdentPat(pat) => !matches!(
263 pat.name().and_then(|name| NameClass::classify(sema, &name)),
264 Some(NameClass::ConstReference(_))
266 ast::Pat::MacroPat(_) => true,
267 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
268 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
269 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
270 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
271 ast::Pat::RecordPat(it) => it
272 .record_pat_field_list()
273 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
274 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
275 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
276 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
281 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
282 sema.type_of_pat(pat)
283 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
284 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
291 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
294 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
295 check_assist_not_applicable(
296 replace_if_let_with_match,
299 if $0true {} else if false {} else {}
306 fn test_if_let_with_match_no_else() {
308 replace_if_let_with_match,
312 if $0let VariantData::Struct(..) = *self {
322 VariantData::Struct(..) => {
334 fn test_if_let_with_match_basic() {
336 replace_if_let_with_match,
339 pub fn is_struct(&self) -> bool {
340 if $0let VariantData::Struct(..) = *self {
342 } else if let VariantData::Tuple(..) = *self {
356 pub fn is_struct(&self) -> bool {
358 VariantData::Struct(..) => true,
359 VariantData::Tuple(..) => false,
374 fn test_if_let_with_match_on_tail_if_let() {
376 replace_if_let_with_match,
379 pub fn is_struct(&self) -> bool {
380 if let VariantData::Struct(..) = *self {
382 } else if let$0 VariantData::Tuple(..) = *self {
392 pub fn is_struct(&self) -> bool {
393 if let VariantData::Struct(..) = *self {
397 VariantData::Tuple(..) => false,
408 fn special_case_option() {
410 replace_if_let_with_match,
413 fn foo(x: Option<i32>) {
414 $0if let Some(x) = x {
422 fn foo(x: Option<i32>) {
424 Some(x) => println!("{}", x),
425 None => println!("none"),
433 fn special_case_inverted_option() {
435 replace_if_let_with_match,
438 fn foo(x: Option<i32>) {
447 fn foo(x: Option<i32>) {
449 None => println!("none"),
450 Some(_) => println!("some"),
458 fn special_case_result() {
460 replace_if_let_with_match,
463 fn foo(x: Result<i32, ()>) {
472 fn foo(x: Result<i32, ()>) {
474 Ok(x) => println!("{}", x),
475 Err(_) => println!("none"),
483 fn special_case_inverted_result() {
485 replace_if_let_with_match,
488 fn foo(x: Result<i32, ()>) {
489 $0if let Err(x) = x {
497 fn foo(x: Result<i32, ()>) {
499 Err(x) => println!("{}", x),
500 Ok(_) => println!("ok"),
510 replace_if_let_with_match,
514 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
515 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
516 Some((*id, rel_path))
526 match path.strip_prefix(root_path) {
528 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
529 Some((*id, rel_path))
540 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
542 replace_match_with_if_let,
545 pub fn is_struct(&self) -> bool {
547 VariantData::Struct(..) => true,
554 pub fn is_struct(&self) -> bool {
555 if let VariantData::Struct(..) = *self {
566 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
568 replace_match_with_if_let,
572 VariantData::Struct(..) => {
582 if let VariantData::Struct(..) = a {
594 fn replace_match_with_if_let_target() {
596 replace_match_with_if_let,
599 pub fn is_struct(&self) -> bool {
601 VariantData::Struct(..) => true,
607 VariantData::Struct(..) => true,
614 fn special_case_option_match_to_if_let() {
616 replace_match_with_if_let,
619 fn foo(x: Option<i32>) {
621 Some(x) => println!("{}", x),
622 None => println!("none"),
627 fn foo(x: Option<i32>) {
639 fn special_case_result_match_to_if_let() {
641 replace_match_with_if_let,
644 fn foo(x: Result<i32, ()>) {
646 Ok(x) => println!("{}", x),
647 Err(_) => println!("none"),
652 fn foo(x: Result<i32, ()>) {
664 fn nested_indent_match_to_if_let() {
666 replace_match_with_if_let,
670 $0match path.strip_prefix(root_path) {
672 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
673 Some((*id, rel_path))
683 if let Ok(rel_path) = path.strip_prefix(root_path) {
684 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
685 Some((*id, rel_path))
696 fn replace_match_with_if_let_empty_wildcard_expr() {
698 replace_match_with_if_let,
701 $0match path.strip_prefix(root_path) {
702 Ok(rel_path) => println!("{}", rel_path),
709 if let Ok(rel_path) = path.strip_prefix(root_path) {
710 println!("{}", rel_path)
718 fn replace_match_with_if_let_number_body() {
720 replace_match_with_if_let,
731 if let Err(_) = Ok(()) {
740 fn replace_match_with_if_let_exhaustive() {
742 replace_match_with_if_let,
744 fn print_source(def_source: ModuleSource) {
746 ModuleSource::SourceFile(..) => { println!("source file"); }
747 ModuleSource::Module(..) => { println!("module"); }
752 fn print_source(def_source: ModuleSource) {
753 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
760 fn replace_match_with_if_let_prefer_name_bind() {
762 replace_match_with_if_let,
767 Bar(bar) => println!("bar {}", bar),
773 if let Bar(bar) = Foo(0) {
774 println!("bar {}", bar)
780 replace_match_with_if_let,
784 Bar(bar) => println!("bar {}", bar),
791 if let Bar(bar) = Foo(0) {
792 println!("bar {}", bar)
800 fn replace_match_with_if_let_prefer_nonempty_body() {
802 replace_match_with_if_let,
807 Err(err) => eprintln!("{}", err),
813 if let Err(err) = Ok(0) {
820 replace_match_with_if_let,
824 Err(err) => eprintln!("{}", err),
831 if let Err(err) = Ok(0) {
840 fn replace_match_with_if_let_rejects_double_name_bindings() {
841 check_assist_not_applicable(
842 replace_match_with_if_let,
846 Foo(foo) => println!("bar {}", foo),
847 Bar(bar) => println!("bar {}", bar),