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, &pat2) => (pat, expr, expr2),
245 _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
246 (false, false) => (pat, expr, expr2),
252 fn is_empty_expr(expr: &ast::Expr) -> bool {
254 ast::Expr::BlockExpr(expr) => {
255 expr.statements().next().is_none() && expr.tail_expr().is_none()
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) => {
266 match pat.name().and_then(|name| NameClass::classify(sema, &name)) {
267 Some(NameClass::ConstReference(_)) => false,
271 ast::Pat::MacroPat(_) => true,
272 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
273 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
274 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
275 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
276 ast::Pat::RecordPat(it) => it
277 .record_pat_field_list()
278 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
279 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
280 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
281 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
286 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
287 sema.type_of_pat(pat)
288 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
289 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
296 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
299 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
300 check_assist_not_applicable(
301 replace_if_let_with_match,
304 if $0true {} else if false {} else {}
311 fn test_if_let_with_match_no_else() {
313 replace_if_let_with_match,
317 if $0let VariantData::Struct(..) = *self {
327 VariantData::Struct(..) => {
339 fn test_if_let_with_match_basic() {
341 replace_if_let_with_match,
344 pub fn is_struct(&self) -> bool {
345 if $0let VariantData::Struct(..) = *self {
347 } else if let VariantData::Tuple(..) = *self {
361 pub fn is_struct(&self) -> bool {
363 VariantData::Struct(..) => true,
364 VariantData::Tuple(..) => false,
379 fn test_if_let_with_match_on_tail_if_let() {
381 replace_if_let_with_match,
384 pub fn is_struct(&self) -> bool {
385 if let VariantData::Struct(..) = *self {
387 } else if let$0 VariantData::Tuple(..) = *self {
397 pub fn is_struct(&self) -> bool {
398 if let VariantData::Struct(..) = *self {
402 VariantData::Tuple(..) => false,
413 fn special_case_option() {
415 replace_if_let_with_match,
418 fn foo(x: Option<i32>) {
419 $0if let Some(x) = x {
427 fn foo(x: Option<i32>) {
429 Some(x) => println!("{}", x),
430 None => println!("none"),
438 fn special_case_inverted_option() {
440 replace_if_let_with_match,
443 fn foo(x: Option<i32>) {
452 fn foo(x: Option<i32>) {
454 None => println!("none"),
455 Some(_) => println!("some"),
463 fn special_case_result() {
465 replace_if_let_with_match,
468 fn foo(x: Result<i32, ()>) {
477 fn foo(x: Result<i32, ()>) {
479 Ok(x) => println!("{}", x),
480 Err(_) => println!("none"),
488 fn special_case_inverted_result() {
490 replace_if_let_with_match,
493 fn foo(x: Result<i32, ()>) {
494 $0if let Err(x) = x {
502 fn foo(x: Result<i32, ()>) {
504 Err(x) => println!("{}", x),
505 Ok(_) => println!("ok"),
515 replace_if_let_with_match,
519 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
520 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
521 Some((*id, rel_path))
531 match path.strip_prefix(root_path) {
533 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
534 Some((*id, rel_path))
545 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
547 replace_match_with_if_let,
550 pub fn is_struct(&self) -> bool {
552 VariantData::Struct(..) => true,
559 pub fn is_struct(&self) -> bool {
560 if let VariantData::Struct(..) = *self {
571 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
573 replace_match_with_if_let,
577 VariantData::Struct(..) => {
587 if let VariantData::Struct(..) = a {
599 fn replace_match_with_if_let_target() {
601 replace_match_with_if_let,
604 pub fn is_struct(&self) -> bool {
606 VariantData::Struct(..) => true,
612 VariantData::Struct(..) => true,
619 fn special_case_option_match_to_if_let() {
621 replace_match_with_if_let,
624 fn foo(x: Option<i32>) {
626 Some(x) => println!("{}", x),
627 None => println!("none"),
632 fn foo(x: Option<i32>) {
644 fn special_case_result_match_to_if_let() {
646 replace_match_with_if_let,
649 fn foo(x: Result<i32, ()>) {
651 Ok(x) => println!("{}", x),
652 Err(_) => println!("none"),
657 fn foo(x: Result<i32, ()>) {
669 fn nested_indent_match_to_if_let() {
671 replace_match_with_if_let,
675 $0match path.strip_prefix(root_path) {
677 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
678 Some((*id, rel_path))
688 if let Ok(rel_path) = path.strip_prefix(root_path) {
689 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
690 Some((*id, rel_path))
701 fn replace_match_with_if_let_empty_wildcard_expr() {
703 replace_match_with_if_let,
706 $0match path.strip_prefix(root_path) {
707 Ok(rel_path) => println!("{}", rel_path),
714 if let Ok(rel_path) = path.strip_prefix(root_path) {
715 println!("{}", rel_path)
723 fn replace_match_with_if_let_number_body() {
725 replace_match_with_if_let,
736 if let Err(_) = Ok(()) {
745 fn replace_match_with_if_let_exhaustive() {
747 replace_match_with_if_let,
749 fn print_source(def_source: ModuleSource) {
751 ModuleSource::SourceFile(..) => { println!("source file"); }
752 ModuleSource::Module(..) => { println!("module"); }
757 fn print_source(def_source: ModuleSource) {
758 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
765 fn replace_match_with_if_let_prefer_name_bind() {
767 replace_match_with_if_let,
772 Bar(bar) => println!("bar {}", bar),
778 if let Bar(bar) = Foo(0) {
779 println!("bar {}", bar)
785 replace_match_with_if_let,
789 Bar(bar) => println!("bar {}", bar),
796 if let Bar(bar) = Foo(0) {
797 println!("bar {}", bar)
805 fn replace_match_with_if_let_prefer_nonempty_body() {
807 replace_match_with_if_let,
812 Err(err) => eprintln!("{}", err),
818 if let Err(err) = Ok(0) {
825 replace_match_with_if_let,
829 Err(err) => eprintln!("{}", err),
836 if let Err(err) = Ok(0) {
845 fn replace_match_with_if_let_rejects_double_name_bindings() {
846 check_assist_not_applicable(
847 replace_match_with_if_let,
851 Foo(foo) => println!("bar {}", foo),
852 Bar(bar) => println!("bar {}", bar),