1 use std::iter::{self, successors};
4 use ide_db::{defs::NameClass, ty_filter::TryEnum, RootDatabase};
8 edit::{AstNodeEdit, IndentLevel},
15 utils::{does_nested_pattern, 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.selection_trimmed());
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()) {
145 it.happy_pattern_wildcard()
146 } else if does_nested_pattern(pat) {
147 make::wildcard_pat().into()
152 None => make::wildcard_pat().into(),
154 make::match_arm(iter::once(pattern), None, unwrap_trivial_block(else_block))
156 make::match_arm(iter::once(make::wildcard_pat().into()), None, make::expr_unit())
160 // Assist: replace_match_with_if_let
162 // Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression.
165 // enum Action { Move { distance: u32 }, Stop }
167 // fn handle(action: Action) {
169 // Action::Move { distance } => foo(distance),
176 // enum Action { Move { distance: u32 }, Stop }
178 // fn handle(action: Action) {
179 // if let Action::Move { distance } = action {
186 pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
187 let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?;
189 let mut arms = match_expr.match_arm_list()?.arms();
190 let (first_arm, second_arm) = (arms.next()?, arms.next()?);
191 if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() {
195 let (if_let_pat, then_expr, else_expr) = pick_pattern_and_expr_order(
202 let scrutinee = match_expr.expr()?;
204 let target = match_expr.syntax().text_range();
206 AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
207 "Replace match with if let",
210 fn make_block_expr(expr: ast::Expr) -> ast::BlockExpr {
211 // Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are
212 // formatted without enclosing braces. If we encounter such block exprs,
213 // wrap them in another BlockExpr.
215 ast::Expr::BlockExpr(block) if block.modifier().is_none() => block,
216 expr => make::block_expr(iter::empty(), Some(expr)),
220 let condition = make::condition(scrutinee, Some(if_let_pat));
221 let then_block = make_block_expr(then_expr.reset_indent());
222 let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) };
223 let if_let_expr = make::expr_if(
226 else_expr.map(make_block_expr).map(ast::ElseBranch::Block),
228 .indent(IndentLevel::from_node(match_expr.syntax()));
230 edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
235 /// Pick the pattern for the if let condition and return the expressions for the `then` body and `else` body in that order.
236 fn pick_pattern_and_expr_order(
237 sema: &hir::Semantics<RootDatabase>,
242 ) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
243 let res = match (pat, pat2) {
244 (ast::Pat::WildcardPat(_), _) => return None,
245 (pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
246 (_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
247 (pat, pat2) => match (binds_name(sema, &pat), binds_name(sema, &pat2)) {
248 (true, true) => return None,
249 (true, false) => (pat, expr, expr2),
250 (false, true) => (pat2, expr2, expr),
251 _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
252 (false, false) => (pat, expr, expr2),
258 fn is_empty_expr(expr: &ast::Expr) -> bool {
260 ast::Expr::BlockExpr(expr) => match expr.stmt_list() {
261 Some(it) => it.statements().next().is_none() && it.tail_expr().is_none(),
264 ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
269 fn binds_name(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
270 let binds_name_v = |pat| binds_name(sema, &pat);
272 ast::Pat::IdentPat(pat) => !matches!(
273 pat.name().and_then(|name| NameClass::classify(sema, &name)),
274 Some(NameClass::ConstReference(_))
276 ast::Pat::MacroPat(_) => true,
277 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
278 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
279 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
280 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
281 ast::Pat::RecordPat(it) => it
282 .record_pat_field_list()
283 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
284 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
285 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
286 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
291 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
292 sema.type_of_pat(pat)
293 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
294 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
301 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
304 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
305 check_assist_not_applicable(
306 replace_if_let_with_match,
309 if $0true {} else if false {} else {}
316 fn test_if_let_with_match_no_else() {
318 replace_if_let_with_match,
322 if $0let VariantData::Struct(..) = *self {
332 VariantData::Struct(..) => {
344 fn test_if_let_with_match_available_range_left() {
345 check_assist_not_applicable(
346 replace_if_let_with_match,
350 $0 if let VariantData::Struct(..) = *self {
360 fn test_if_let_with_match_available_range_right() {
361 check_assist_not_applicable(
362 replace_if_let_with_match,
366 if let VariantData::Struct(..) = *self {$0
376 fn test_if_let_with_match_basic() {
378 replace_if_let_with_match,
381 pub fn is_struct(&self) -> bool {
382 if $0let VariantData::Struct(..) = *self {
384 } else if let VariantData::Tuple(..) = *self {
398 pub fn is_struct(&self) -> bool {
400 VariantData::Struct(..) => true,
401 VariantData::Tuple(..) => false,
416 fn test_if_let_with_match_on_tail_if_let() {
418 replace_if_let_with_match,
421 pub fn is_struct(&self) -> bool {
422 if let VariantData::Struct(..) = *self {
424 } else if let$0 VariantData::Tuple(..) = *self {
434 pub fn is_struct(&self) -> bool {
435 if let VariantData::Struct(..) = *self {
439 VariantData::Tuple(..) => false,
450 fn special_case_option() {
452 replace_if_let_with_match,
455 fn foo(x: Option<i32>) {
456 $0if let Some(x) = x {
464 fn foo(x: Option<i32>) {
466 Some(x) => println!("{}", x),
467 None => println!("none"),
475 fn special_case_inverted_option() {
477 replace_if_let_with_match,
480 fn foo(x: Option<i32>) {
489 fn foo(x: Option<i32>) {
491 None => println!("none"),
492 Some(_) => println!("some"),
500 fn special_case_result() {
502 replace_if_let_with_match,
505 fn foo(x: Result<i32, ()>) {
514 fn foo(x: Result<i32, ()>) {
516 Ok(x) => println!("{}", x),
517 Err(_) => println!("none"),
525 fn special_case_inverted_result() {
527 replace_if_let_with_match,
530 fn foo(x: Result<i32, ()>) {
531 $0if let Err(x) = x {
539 fn foo(x: Result<i32, ()>) {
541 Err(x) => println!("{}", x),
542 Ok(_) => println!("ok"),
552 replace_if_let_with_match,
556 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
557 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
558 Some((*id, rel_path))
568 match path.strip_prefix(root_path) {
570 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
571 Some((*id, rel_path))
584 replace_if_let_with_match,
587 fn foo(x: Result<i32, ()>) {
588 let bar: Result<_, ()> = Ok(Some(1));
589 $0if let Ok(Some(_)) = bar {
597 fn foo(x: Result<i32, ()>) {
598 let bar: Result<_, ()> = Ok(Some(1));
609 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
611 replace_match_with_if_let,
614 pub fn is_struct(&self) -> bool {
616 VariantData::Struct(..) => true,
623 pub fn is_struct(&self) -> bool {
624 if let VariantData::Struct(..) = *self {
635 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
637 replace_match_with_if_let,
641 VariantData::Struct(..) => {
651 if let VariantData::Struct(..) = a {
663 fn replace_match_with_if_let_target() {
665 replace_match_with_if_let,
668 pub fn is_struct(&self) -> bool {
670 VariantData::Struct(..) => true,
676 VariantData::Struct(..) => true,
683 fn special_case_option_match_to_if_let() {
685 replace_match_with_if_let,
688 fn foo(x: Option<i32>) {
690 Some(x) => println!("{}", x),
691 None => println!("none"),
696 fn foo(x: Option<i32>) {
708 fn special_case_result_match_to_if_let() {
710 replace_match_with_if_let,
713 fn foo(x: Result<i32, ()>) {
715 Ok(x) => println!("{}", x),
716 Err(_) => println!("none"),
721 fn foo(x: Result<i32, ()>) {
733 fn nested_indent_match_to_if_let() {
735 replace_match_with_if_let,
739 $0match path.strip_prefix(root_path) {
741 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
742 Some((*id, rel_path))
752 if let Ok(rel_path) = path.strip_prefix(root_path) {
753 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
754 Some((*id, rel_path))
765 fn replace_match_with_if_let_empty_wildcard_expr() {
767 replace_match_with_if_let,
770 $0match path.strip_prefix(root_path) {
771 Ok(rel_path) => println!("{}", rel_path),
778 if let Ok(rel_path) = path.strip_prefix(root_path) {
779 println!("{}", rel_path)
787 fn replace_match_with_if_let_number_body() {
789 replace_match_with_if_let,
800 if let Err(_) = Ok(()) {
809 fn replace_match_with_if_let_exhaustive() {
811 replace_match_with_if_let,
813 fn print_source(def_source: ModuleSource) {
815 ModuleSource::SourceFile(..) => { println!("source file"); }
816 ModuleSource::Module(..) => { println!("module"); }
821 fn print_source(def_source: ModuleSource) {
822 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
829 fn replace_match_with_if_let_prefer_name_bind() {
831 replace_match_with_if_let,
836 Bar(bar) => println!("bar {}", bar),
842 if let Bar(bar) = Foo(0) {
843 println!("bar {}", bar)
849 replace_match_with_if_let,
853 Bar(bar) => println!("bar {}", bar),
860 if let Bar(bar) = Foo(0) {
861 println!("bar {}", bar)
869 fn replace_match_with_if_let_prefer_nonempty_body() {
871 replace_match_with_if_let,
876 Err(err) => eprintln!("{}", err),
882 if let Err(err) = Ok(0) {
889 replace_match_with_if_let,
893 Err(err) => eprintln!("{}", err),
900 if let Err(err) = Ok(0) {
909 fn replace_match_with_if_let_rejects_double_name_bindings() {
910 check_assist_not_applicable(
911 replace_match_with_if_let,
915 Foo(foo) => println!("bar {}", foo),
916 Bar(bar) => println!("bar {}", bar),
924 fn test_replace_match_with_if_let_keeps_unsafe_block() {
926 replace_match_with_if_let,
929 pub fn is_struct(&self) -> bool {
931 VariantData::Struct(..) => true,
932 _ => unsafe { unreachable_unchecked() },
938 pub fn is_struct(&self) -> bool {
939 if let VariantData::Struct(..) = *self {
942 unsafe { unreachable_unchecked() }