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()) {
145 it.happy_pattern_wildcard()
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) => match expr.stmt_list() {
257 Some(it) => it.statements().next().is_none() && it.tail_expr().is_none(),
260 ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
265 fn binds_name(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
266 let binds_name_v = |pat| binds_name(sema, &pat);
268 ast::Pat::IdentPat(pat) => !matches!(
269 pat.name().and_then(|name| NameClass::classify(sema, &name)),
270 Some(NameClass::ConstReference(_))
272 ast::Pat::MacroPat(_) => true,
273 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
274 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
275 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
276 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
277 ast::Pat::RecordPat(it) => it
278 .record_pat_field_list()
279 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
280 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
281 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
282 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
287 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
288 sema.type_of_pat(pat)
289 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
290 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
297 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
300 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
301 check_assist_not_applicable(
302 replace_if_let_with_match,
305 if $0true {} else if false {} else {}
312 fn test_if_let_with_match_no_else() {
314 replace_if_let_with_match,
318 if $0let VariantData::Struct(..) = *self {
328 VariantData::Struct(..) => {
340 fn test_if_let_with_match_available_range_left() {
341 check_assist_not_applicable(
342 replace_if_let_with_match,
346 $0 if let VariantData::Struct(..) = *self {
356 fn test_if_let_with_match_available_range_right() {
357 check_assist_not_applicable(
358 replace_if_let_with_match,
362 if let VariantData::Struct(..) = *self {$0
372 fn test_if_let_with_match_basic() {
374 replace_if_let_with_match,
377 pub fn is_struct(&self) -> bool {
378 if $0let VariantData::Struct(..) = *self {
380 } else if let VariantData::Tuple(..) = *self {
394 pub fn is_struct(&self) -> bool {
396 VariantData::Struct(..) => true,
397 VariantData::Tuple(..) => false,
412 fn test_if_let_with_match_on_tail_if_let() {
414 replace_if_let_with_match,
417 pub fn is_struct(&self) -> bool {
418 if let VariantData::Struct(..) = *self {
420 } else if let$0 VariantData::Tuple(..) = *self {
430 pub fn is_struct(&self) -> bool {
431 if let VariantData::Struct(..) = *self {
435 VariantData::Tuple(..) => false,
446 fn special_case_option() {
448 replace_if_let_with_match,
451 fn foo(x: Option<i32>) {
452 $0if let Some(x) = x {
460 fn foo(x: Option<i32>) {
462 Some(x) => println!("{}", x),
463 None => println!("none"),
471 fn special_case_inverted_option() {
473 replace_if_let_with_match,
476 fn foo(x: Option<i32>) {
485 fn foo(x: Option<i32>) {
487 None => println!("none"),
488 Some(_) => println!("some"),
496 fn special_case_result() {
498 replace_if_let_with_match,
501 fn foo(x: Result<i32, ()>) {
510 fn foo(x: Result<i32, ()>) {
512 Ok(x) => println!("{}", x),
513 Err(_) => println!("none"),
521 fn special_case_inverted_result() {
523 replace_if_let_with_match,
526 fn foo(x: Result<i32, ()>) {
527 $0if let Err(x) = x {
535 fn foo(x: Result<i32, ()>) {
537 Err(x) => println!("{}", x),
538 Ok(_) => println!("ok"),
548 replace_if_let_with_match,
552 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
553 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
554 Some((*id, rel_path))
564 match path.strip_prefix(root_path) {
566 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
567 Some((*id, rel_path))
578 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
580 replace_match_with_if_let,
583 pub fn is_struct(&self) -> bool {
585 VariantData::Struct(..) => true,
592 pub fn is_struct(&self) -> bool {
593 if let VariantData::Struct(..) = *self {
604 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
606 replace_match_with_if_let,
610 VariantData::Struct(..) => {
620 if let VariantData::Struct(..) = a {
632 fn replace_match_with_if_let_target() {
634 replace_match_with_if_let,
637 pub fn is_struct(&self) -> bool {
639 VariantData::Struct(..) => true,
645 VariantData::Struct(..) => true,
652 fn special_case_option_match_to_if_let() {
654 replace_match_with_if_let,
657 fn foo(x: Option<i32>) {
659 Some(x) => println!("{}", x),
660 None => println!("none"),
665 fn foo(x: Option<i32>) {
677 fn special_case_result_match_to_if_let() {
679 replace_match_with_if_let,
682 fn foo(x: Result<i32, ()>) {
684 Ok(x) => println!("{}", x),
685 Err(_) => println!("none"),
690 fn foo(x: Result<i32, ()>) {
702 fn nested_indent_match_to_if_let() {
704 replace_match_with_if_let,
708 $0match path.strip_prefix(root_path) {
710 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
711 Some((*id, rel_path))
721 if let Ok(rel_path) = path.strip_prefix(root_path) {
722 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
723 Some((*id, rel_path))
734 fn replace_match_with_if_let_empty_wildcard_expr() {
736 replace_match_with_if_let,
739 $0match path.strip_prefix(root_path) {
740 Ok(rel_path) => println!("{}", rel_path),
747 if let Ok(rel_path) = path.strip_prefix(root_path) {
748 println!("{}", rel_path)
756 fn replace_match_with_if_let_number_body() {
758 replace_match_with_if_let,
769 if let Err(_) = Ok(()) {
778 fn replace_match_with_if_let_exhaustive() {
780 replace_match_with_if_let,
782 fn print_source(def_source: ModuleSource) {
784 ModuleSource::SourceFile(..) => { println!("source file"); }
785 ModuleSource::Module(..) => { println!("module"); }
790 fn print_source(def_source: ModuleSource) {
791 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
798 fn replace_match_with_if_let_prefer_name_bind() {
800 replace_match_with_if_let,
805 Bar(bar) => println!("bar {}", bar),
811 if let Bar(bar) = Foo(0) {
812 println!("bar {}", bar)
818 replace_match_with_if_let,
822 Bar(bar) => println!("bar {}", bar),
829 if let Bar(bar) = Foo(0) {
830 println!("bar {}", bar)
838 fn replace_match_with_if_let_prefer_nonempty_body() {
840 replace_match_with_if_let,
845 Err(err) => eprintln!("{}", err),
851 if let Err(err) = Ok(0) {
858 replace_match_with_if_let,
862 Err(err) => eprintln!("{}", err),
869 if let Err(err) = Ok(0) {
878 fn replace_match_with_if_let_rejects_double_name_bindings() {
879 check_assist_not_applicable(
880 replace_match_with_if_let,
884 Foo(foo) => println!("bar {}", foo),
885 Bar(bar) => println!("bar {}", bar),
895 replace_if_let_with_match,
898 fn foo(x: Result<i32, ()>) {
899 let bar: Result<_, ()> = Ok(Some(1));
900 $0if let Ok(Some(_)) = bar {
908 fn foo(x: Result<i32, ()>) {
909 let bar: Result<_, ()> = Ok(Some(1));