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 available_range = TextRange::new(
48 if_expr.syntax().text_range().start(),
49 if_expr.then_branch()?.syntax().text_range().start(),
51 let cursor_in_range = available_range.contains_range(ctx.frange.range);
55 let mut else_block = None;
56 let if_exprs = successors(Some(if_expr.clone()), |expr| match expr.else_branch()? {
57 ast::ElseBranch::IfExpr(expr) => Some(expr),
58 ast::ElseBranch::Block(block) => {
59 else_block = Some(block);
63 let scrutinee_to_be_expr = if_expr.condition()?.expr()?;
65 let mut pat_seen = false;
66 let mut cond_bodies = Vec::new();
67 for if_expr in if_exprs {
68 let cond = if_expr.condition()?;
69 let expr = cond.expr()?;
70 let cond = match cond.pat() {
72 if scrutinee_to_be_expr.syntax().text() != expr.syntax().text() {
73 // Only if all condition expressions are equal we can merge them into a match
79 None => Either::Right(expr),
81 let body = if_expr.then_branch()?;
82 cond_bodies.push((cond, body));
86 // Don't offer turning an if (chain) without patterns into a match
91 AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
92 "Replace if let with match",
96 let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
97 let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
98 let body = body.reset_indent().indent(IndentLevel(1));
100 Either::Left(pat) => {
101 make::match_arm(iter::once(pat), None, unwrap_trivial_block(body))
103 Either::Right(expr) => make::match_arm(
104 iter::once(make::wildcard_pat().into()),
106 unwrap_trivial_block(body),
110 let arms = cond_bodies.into_iter().map(make_match_arm).chain(iter::once(else_arm));
111 let match_expr = make::expr_match(scrutinee_to_be_expr, make::match_arm_list(arms));
112 match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
115 let has_preceding_if_expr =
116 if_expr.syntax().parent().map_or(false, |it| ast::IfExpr::can_cast(it.kind()));
117 let expr = if has_preceding_if_expr {
118 // make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
119 make::block_expr(None, Some(match_expr)).into()
123 edit.replace_ast::<ast::Expr>(if_expr.into(), expr);
130 else_block: Option<ast::BlockExpr>,
131 conditionals: &[(Either<ast::Pat, ast::Expr>, ast::BlockExpr)],
133 if let Some(else_block) = else_block {
134 let pattern = if let [(Either::Left(pat), _)] = conditionals {
137 .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
142 let pattern = match pattern {
144 if does_pat_match_variant(pat, &it.sad_pattern()) {
150 None => make::wildcard_pat().into(),
152 make::match_arm(iter::once(pattern), None, unwrap_trivial_block(else_block))
154 make::match_arm(iter::once(make::wildcard_pat().into()), None, make::expr_unit())
158 // Assist: replace_match_with_if_let
160 // Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression.
163 // enum Action { Move { distance: u32 }, Stop }
165 // fn handle(action: Action) {
167 // Action::Move { distance } => foo(distance),
174 // enum Action { Move { distance: u32 }, Stop }
176 // fn handle(action: Action) {
177 // if let Action::Move { distance } = action {
184 pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
185 let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?;
187 let mut arms = match_expr.match_arm_list()?.arms();
188 let (first_arm, second_arm) = (arms.next()?, arms.next()?);
189 if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() {
193 let (if_let_pat, then_expr, else_expr) = pick_pattern_and_expr_order(
200 let scrutinee = match_expr.expr()?;
202 let target = match_expr.syntax().text_range();
204 AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
205 "Replace match with if let",
208 let condition = make::condition(scrutinee, Some(if_let_pat));
209 let then_block = match then_expr.reset_indent() {
210 ast::Expr::BlockExpr(block) => block,
211 expr => make::block_expr(iter::empty(), Some(expr)),
213 let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) };
214 let if_let_expr = make::expr_if(
218 .map(|expr| match expr {
219 ast::Expr::BlockExpr(block) => block,
220 expr => (make::block_expr(iter::empty(), Some(expr))),
222 .map(ast::ElseBranch::Block),
224 .indent(IndentLevel::from_node(match_expr.syntax()));
226 edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
231 /// Pick the pattern for the if let condition and return the expressions for the `then` body and `else` body in that order.
232 fn pick_pattern_and_expr_order(
233 sema: &hir::Semantics<RootDatabase>,
238 ) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
239 let res = match (pat, pat2) {
240 (ast::Pat::WildcardPat(_), _) => return None,
241 (pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
242 (_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
243 (pat, pat2) => match (binds_name(sema, &pat), binds_name(sema, &pat2)) {
244 (true, true) => return None,
245 (true, false) => (pat, expr, expr2),
246 (false, true) => (pat2, expr2, expr),
247 _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
248 (false, false) => (pat, expr, expr2),
254 fn is_empty_expr(expr: &ast::Expr) -> bool {
256 ast::Expr::BlockExpr(expr) => expr.is_empty(),
257 ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
262 fn binds_name(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
263 let binds_name_v = |pat| binds_name(sema, &pat);
265 ast::Pat::IdentPat(pat) => !matches!(
266 pat.name().and_then(|name| NameClass::classify(sema, &name)),
267 Some(NameClass::ConstReference(_))
269 ast::Pat::MacroPat(_) => true,
270 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
271 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
272 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
273 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
274 ast::Pat::RecordPat(it) => it
275 .record_pat_field_list()
276 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
277 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
278 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
279 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
284 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
285 sema.type_of_pat(pat)
286 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
287 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
294 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
297 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
298 check_assist_not_applicable(
299 replace_if_let_with_match,
302 if $0true {} else if false {} else {}
309 fn test_if_let_with_match_no_else() {
311 replace_if_let_with_match,
315 if $0let VariantData::Struct(..) = *self {
325 VariantData::Struct(..) => {
337 fn test_if_let_with_match_available_range_left() {
338 check_assist_not_applicable(
339 replace_if_let_with_match,
343 $0 if let VariantData::Struct(..) = *self {
353 fn test_if_let_with_match_available_range_right() {
354 check_assist_not_applicable(
355 replace_if_let_with_match,
359 if let VariantData::Struct(..) = *self {$0
369 fn test_if_let_with_match_basic() {
371 replace_if_let_with_match,
374 pub fn is_struct(&self) -> bool {
375 if $0let VariantData::Struct(..) = *self {
377 } else if let VariantData::Tuple(..) = *self {
391 pub fn is_struct(&self) -> bool {
393 VariantData::Struct(..) => true,
394 VariantData::Tuple(..) => false,
409 fn test_if_let_with_match_on_tail_if_let() {
411 replace_if_let_with_match,
414 pub fn is_struct(&self) -> bool {
415 if let VariantData::Struct(..) = *self {
417 } else if let$0 VariantData::Tuple(..) = *self {
427 pub fn is_struct(&self) -> bool {
428 if let VariantData::Struct(..) = *self {
432 VariantData::Tuple(..) => false,
443 fn special_case_option() {
445 replace_if_let_with_match,
448 fn foo(x: Option<i32>) {
449 $0if let Some(x) = x {
457 fn foo(x: Option<i32>) {
459 Some(x) => println!("{}", x),
460 None => println!("none"),
468 fn special_case_inverted_option() {
470 replace_if_let_with_match,
473 fn foo(x: Option<i32>) {
482 fn foo(x: Option<i32>) {
484 None => println!("none"),
485 Some(_) => println!("some"),
493 fn special_case_result() {
495 replace_if_let_with_match,
498 fn foo(x: Result<i32, ()>) {
507 fn foo(x: Result<i32, ()>) {
509 Ok(x) => println!("{}", x),
510 Err(_) => println!("none"),
518 fn special_case_inverted_result() {
520 replace_if_let_with_match,
523 fn foo(x: Result<i32, ()>) {
524 $0if let Err(x) = x {
532 fn foo(x: Result<i32, ()>) {
534 Err(x) => println!("{}", x),
535 Ok(_) => println!("ok"),
545 replace_if_let_with_match,
549 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
550 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
551 Some((*id, rel_path))
561 match path.strip_prefix(root_path) {
563 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
564 Some((*id, rel_path))
575 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
577 replace_match_with_if_let,
580 pub fn is_struct(&self) -> bool {
582 VariantData::Struct(..) => true,
589 pub fn is_struct(&self) -> bool {
590 if let VariantData::Struct(..) = *self {
601 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
603 replace_match_with_if_let,
607 VariantData::Struct(..) => {
617 if let VariantData::Struct(..) = a {
629 fn replace_match_with_if_let_target() {
631 replace_match_with_if_let,
634 pub fn is_struct(&self) -> bool {
636 VariantData::Struct(..) => true,
642 VariantData::Struct(..) => true,
649 fn special_case_option_match_to_if_let() {
651 replace_match_with_if_let,
654 fn foo(x: Option<i32>) {
656 Some(x) => println!("{}", x),
657 None => println!("none"),
662 fn foo(x: Option<i32>) {
674 fn special_case_result_match_to_if_let() {
676 replace_match_with_if_let,
679 fn foo(x: Result<i32, ()>) {
681 Ok(x) => println!("{}", x),
682 Err(_) => println!("none"),
687 fn foo(x: Result<i32, ()>) {
699 fn nested_indent_match_to_if_let() {
701 replace_match_with_if_let,
705 $0match path.strip_prefix(root_path) {
707 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
708 Some((*id, rel_path))
718 if let Ok(rel_path) = path.strip_prefix(root_path) {
719 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
720 Some((*id, rel_path))
731 fn replace_match_with_if_let_empty_wildcard_expr() {
733 replace_match_with_if_let,
736 $0match path.strip_prefix(root_path) {
737 Ok(rel_path) => println!("{}", rel_path),
744 if let Ok(rel_path) = path.strip_prefix(root_path) {
745 println!("{}", rel_path)
753 fn replace_match_with_if_let_number_body() {
755 replace_match_with_if_let,
766 if let Err(_) = Ok(()) {
775 fn replace_match_with_if_let_exhaustive() {
777 replace_match_with_if_let,
779 fn print_source(def_source: ModuleSource) {
781 ModuleSource::SourceFile(..) => { println!("source file"); }
782 ModuleSource::Module(..) => { println!("module"); }
787 fn print_source(def_source: ModuleSource) {
788 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
795 fn replace_match_with_if_let_prefer_name_bind() {
797 replace_match_with_if_let,
802 Bar(bar) => println!("bar {}", bar),
808 if let Bar(bar) = Foo(0) {
809 println!("bar {}", bar)
815 replace_match_with_if_let,
819 Bar(bar) => println!("bar {}", bar),
826 if let Bar(bar) = Foo(0) {
827 println!("bar {}", bar)
835 fn replace_match_with_if_let_prefer_nonempty_body() {
837 replace_match_with_if_let,
842 Err(err) => eprintln!("{}", err),
848 if let Err(err) = Ok(0) {
855 replace_match_with_if_let,
859 Err(err) => eprintln!("{}", err),
866 if let Err(err) = Ok(0) {
875 fn replace_match_with_if_let_rejects_double_name_bindings() {
876 check_assist_not_applicable(
877 replace_match_with_if_let,
881 Foo(foo) => println!("bar {}", foo),
882 Bar(bar) => println!("bar {}", bar),