1 use std::iter::{self, successors};
6 helpers::node_ext::{is_pattern_cond, single_let},
13 edit::{AstNodeEdit, IndentLevel},
20 utils::{does_nested_pattern, does_pat_match_variant, unwrap_trivial_block},
21 AssistContext, AssistId, AssistKind, Assists,
24 // Assist: replace_if_let_with_match
26 // Replaces a `if let` expression with a `match` expression.
29 // enum Action { Move { distance: u32 }, Stop }
31 // fn handle(action: Action) {
32 // $0if let Action::Move { distance } = action {
41 // enum Action { Move { distance: u32 }, Stop }
43 // fn handle(action: Action) {
45 // Action::Move { distance } => foo(distance),
50 pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
51 let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
52 let available_range = TextRange::new(
53 if_expr.syntax().text_range().start(),
54 if_expr.then_branch()?.syntax().text_range().start(),
56 let cursor_in_range = available_range.contains_range(ctx.selection_trimmed());
60 let mut else_block = None;
61 let if_exprs = successors(Some(if_expr.clone()), |expr| match expr.else_branch()? {
62 ast::ElseBranch::IfExpr(expr) => Some(expr),
63 ast::ElseBranch::Block(block) => {
64 else_block = Some(block);
68 let scrutinee_to_be_expr = if_expr.condition()?;
69 let scrutinee_to_be_expr = match single_let(scrutinee_to_be_expr.clone()) {
70 Some(cond) => cond.expr()?,
71 None => scrutinee_to_be_expr,
74 let mut pat_seen = false;
75 let mut cond_bodies = Vec::new();
76 for if_expr in if_exprs {
77 let cond = if_expr.condition()?;
78 let cond = match single_let(cond.clone()) {
80 let pat = let_.pat()?;
81 let expr = let_.expr()?;
82 // FIXME: If one `let` is wrapped in parentheses and the second is not,
84 if scrutinee_to_be_expr.syntax().text() != expr.syntax().text() {
85 // Only if all condition expressions are equal we can merge them into a match
91 // Multiple `let`, unsupported.
92 None if is_pattern_cond(cond.clone()) => return None,
93 None => Either::Right(cond),
95 let body = if_expr.then_branch()?;
96 cond_bodies.push((cond, body));
100 // Don't offer turning an if (chain) without patterns into a match
105 AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
106 "Replace if let with match",
110 let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
111 let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
112 let body = body.reset_indent().indent(IndentLevel(1));
114 Either::Left(pat) => {
115 make::match_arm(iter::once(pat), None, unwrap_trivial_block(body))
117 Either::Right(expr) => make::match_arm(
118 iter::once(make::wildcard_pat().into()),
120 unwrap_trivial_block(body),
124 let arms = cond_bodies.into_iter().map(make_match_arm).chain(iter::once(else_arm));
125 let match_expr = make::expr_match(scrutinee_to_be_expr, make::match_arm_list(arms));
126 match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
129 let has_preceding_if_expr =
130 if_expr.syntax().parent().map_or(false, |it| ast::IfExpr::can_cast(it.kind()));
131 let expr = if has_preceding_if_expr {
132 // make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
133 make::block_expr(None, Some(match_expr)).into()
137 edit.replace_ast::<ast::Expr>(if_expr.into(), expr);
144 else_block: Option<ast::BlockExpr>,
145 conditionals: &[(Either<ast::Pat, ast::Expr>, ast::BlockExpr)],
147 if let Some(else_block) = else_block {
148 let pattern = if let [(Either::Left(pat), _)] = conditionals {
151 .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
156 let pattern = match pattern {
158 if does_pat_match_variant(pat, &it.sad_pattern()) {
159 it.happy_pattern_wildcard()
160 } else if does_nested_pattern(pat) {
161 make::wildcard_pat().into()
166 None => make::wildcard_pat().into(),
168 make::match_arm(iter::once(pattern), None, unwrap_trivial_block(else_block))
170 make::match_arm(iter::once(make::wildcard_pat().into()), None, make::expr_unit())
174 // Assist: replace_match_with_if_let
176 // Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression.
179 // enum Action { Move { distance: u32 }, Stop }
181 // fn handle(action: Action) {
183 // Action::Move { distance } => foo(distance),
190 // enum Action { Move { distance: u32 }, Stop }
192 // fn handle(action: Action) {
193 // if let Action::Move { distance } = action {
200 pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
201 let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?;
203 let mut arms = match_expr.match_arm_list()?.arms();
204 let (first_arm, second_arm) = (arms.next()?, arms.next()?);
205 if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() {
209 let (if_let_pat, then_expr, else_expr) = pick_pattern_and_expr_order(
216 let scrutinee = match_expr.expr()?;
218 let target = match_expr.syntax().text_range();
220 AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
221 "Replace match with if let",
224 fn make_block_expr(expr: ast::Expr) -> ast::BlockExpr {
225 // Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are
226 // formatted without enclosing braces. If we encounter such block exprs,
227 // wrap them in another BlockExpr.
229 ast::Expr::BlockExpr(block) if block.modifier().is_none() => block,
230 expr => make::block_expr(iter::empty(), Some(expr)),
234 let condition = make::expr_let(if_let_pat, scrutinee);
235 let then_block = make_block_expr(then_expr.reset_indent());
236 let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) };
237 let if_let_expr = make::expr_if(
240 else_expr.map(make_block_expr).map(ast::ElseBranch::Block),
242 .indent(IndentLevel::from_node(match_expr.syntax()));
244 edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
249 /// Pick the pattern for the if let condition and return the expressions for the `then` body and `else` body in that order.
250 fn pick_pattern_and_expr_order(
251 sema: &hir::Semantics<RootDatabase>,
256 ) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
257 let res = match (pat, pat2) {
258 (ast::Pat::WildcardPat(_), _) => return None,
259 (pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
260 (_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
261 (pat, pat2) => match (binds_name(sema, &pat), binds_name(sema, &pat2)) {
262 (true, true) => return None,
263 (true, false) => (pat, expr, expr2),
264 (false, true) => (pat2, expr2, expr),
265 _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
266 (false, false) => (pat, expr, expr2),
272 fn is_empty_expr(expr: &ast::Expr) -> bool {
274 ast::Expr::BlockExpr(expr) => match expr.stmt_list() {
275 Some(it) => it.statements().next().is_none() && it.tail_expr().is_none(),
278 ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
283 fn binds_name(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
284 let binds_name_v = |pat| binds_name(sema, &pat);
286 ast::Pat::IdentPat(pat) => !matches!(
287 pat.name().and_then(|name| NameClass::classify(sema, &name)),
288 Some(NameClass::ConstReference(_))
290 ast::Pat::MacroPat(_) => true,
291 ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
292 ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
293 ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
294 ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
295 ast::Pat::RecordPat(it) => it
296 .record_pat_field_list()
297 .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
298 ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
299 ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
300 ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
305 fn is_sad_pat(sema: &hir::Semantics<RootDatabase>, pat: &ast::Pat) -> bool {
306 sema.type_of_pat(pat)
307 .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
308 .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
315 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
318 fn test_if_let_with_match_unapplicable_for_simple_ifs() {
319 check_assist_not_applicable(
320 replace_if_let_with_match,
323 if $0true {} else if false {} else {}
330 fn test_if_let_with_match_no_else() {
332 replace_if_let_with_match,
336 if $0let VariantData::Struct(..) = *self {
346 VariantData::Struct(..) => {
358 fn test_if_let_with_match_available_range_left() {
359 check_assist_not_applicable(
360 replace_if_let_with_match,
364 $0 if let VariantData::Struct(..) = *self {
374 fn test_if_let_with_match_available_range_right() {
375 check_assist_not_applicable(
376 replace_if_let_with_match,
380 if let VariantData::Struct(..) = *self {$0
390 fn test_if_let_with_match_let_chain() {
391 check_assist_not_applicable(
392 replace_if_let_with_match,
395 if $0let true = true && let Some(1) = None {}
402 fn test_if_let_with_match_basic() {
404 replace_if_let_with_match,
407 pub fn is_struct(&self) -> bool {
408 if $0let VariantData::Struct(..) = *self {
410 } else if let VariantData::Tuple(..) = *self {
424 pub fn is_struct(&self) -> bool {
426 VariantData::Struct(..) => true,
427 VariantData::Tuple(..) => false,
442 fn test_if_let_with_match_on_tail_if_let() {
444 replace_if_let_with_match,
447 pub fn is_struct(&self) -> bool {
448 if let VariantData::Struct(..) = *self {
450 } else if let$0 VariantData::Tuple(..) = *self {
460 pub fn is_struct(&self) -> bool {
461 if let VariantData::Struct(..) = *self {
465 VariantData::Tuple(..) => false,
476 fn special_case_option() {
478 replace_if_let_with_match,
481 fn foo(x: Option<i32>) {
482 $0if let Some(x) = x {
490 fn foo(x: Option<i32>) {
492 Some(x) => println!("{}", x),
493 None => println!("none"),
501 fn special_case_inverted_option() {
503 replace_if_let_with_match,
506 fn foo(x: Option<i32>) {
515 fn foo(x: Option<i32>) {
517 None => println!("none"),
518 Some(_) => println!("some"),
526 fn special_case_result() {
528 replace_if_let_with_match,
531 fn foo(x: Result<i32, ()>) {
540 fn foo(x: Result<i32, ()>) {
542 Ok(x) => println!("{}", x),
543 Err(_) => println!("none"),
551 fn special_case_inverted_result() {
553 replace_if_let_with_match,
556 fn foo(x: Result<i32, ()>) {
557 $0if let Err(x) = x {
565 fn foo(x: Result<i32, ()>) {
567 Err(x) => println!("{}", x),
568 Ok(_) => println!("ok"),
578 replace_if_let_with_match,
582 $0if let Ok(rel_path) = path.strip_prefix(root_path) {
583 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
584 Some((*id, rel_path))
594 match path.strip_prefix(root_path) {
596 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
597 Some((*id, rel_path))
610 replace_if_let_with_match,
613 fn foo(x: Result<i32, ()>) {
614 let bar: Result<_, ()> = Ok(Some(1));
615 $0if let Ok(Some(_)) = bar {
623 fn foo(x: Result<i32, ()>) {
624 let bar: Result<_, ()> = Ok(Some(1));
635 fn test_replace_match_with_if_let_unwraps_simple_expressions() {
637 replace_match_with_if_let,
640 pub fn is_struct(&self) -> bool {
642 VariantData::Struct(..) => true,
649 pub fn is_struct(&self) -> bool {
650 if let VariantData::Struct(..) = *self {
661 fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
663 replace_match_with_if_let,
667 VariantData::Struct(..) => {
677 if let VariantData::Struct(..) = a {
689 fn replace_match_with_if_let_target() {
691 replace_match_with_if_let,
694 pub fn is_struct(&self) -> bool {
696 VariantData::Struct(..) => true,
702 VariantData::Struct(..) => true,
709 fn special_case_option_match_to_if_let() {
711 replace_match_with_if_let,
714 fn foo(x: Option<i32>) {
716 Some(x) => println!("{}", x),
717 None => println!("none"),
722 fn foo(x: Option<i32>) {
734 fn special_case_result_match_to_if_let() {
736 replace_match_with_if_let,
739 fn foo(x: Result<i32, ()>) {
741 Ok(x) => println!("{}", x),
742 Err(_) => println!("none"),
747 fn foo(x: Result<i32, ()>) {
759 fn nested_indent_match_to_if_let() {
761 replace_match_with_if_let,
765 $0match path.strip_prefix(root_path) {
767 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
768 Some((*id, rel_path))
778 if let Ok(rel_path) = path.strip_prefix(root_path) {
779 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
780 Some((*id, rel_path))
791 fn replace_match_with_if_let_empty_wildcard_expr() {
793 replace_match_with_if_let,
796 $0match path.strip_prefix(root_path) {
797 Ok(rel_path) => println!("{}", rel_path),
804 if let Ok(rel_path) = path.strip_prefix(root_path) {
805 println!("{}", rel_path)
813 fn replace_match_with_if_let_number_body() {
815 replace_match_with_if_let,
826 if let Err(_) = Ok(()) {
835 fn replace_match_with_if_let_exhaustive() {
837 replace_match_with_if_let,
839 fn print_source(def_source: ModuleSource) {
841 ModuleSource::SourceFile(..) => { println!("source file"); }
842 ModuleSource::Module(..) => { println!("module"); }
847 fn print_source(def_source: ModuleSource) {
848 if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
855 fn replace_match_with_if_let_prefer_name_bind() {
857 replace_match_with_if_let,
862 Bar(bar) => println!("bar {}", bar),
868 if let Bar(bar) = Foo(0) {
869 println!("bar {}", bar)
875 replace_match_with_if_let,
879 Bar(bar) => println!("bar {}", bar),
886 if let Bar(bar) = Foo(0) {
887 println!("bar {}", bar)
895 fn replace_match_with_if_let_prefer_nonempty_body() {
897 replace_match_with_if_let,
902 Err(err) => eprintln!("{}", err),
908 if let Err(err) = Ok(0) {
915 replace_match_with_if_let,
919 Err(err) => eprintln!("{}", err),
926 if let Err(err) = Ok(0) {
935 fn replace_match_with_if_let_rejects_double_name_bindings() {
936 check_assist_not_applicable(
937 replace_match_with_if_let,
941 Foo(foo) => println!("bar {}", foo),
942 Bar(bar) => println!("bar {}", bar),
950 fn test_replace_match_with_if_let_keeps_unsafe_block() {
952 replace_match_with_if_let,
955 pub fn is_struct(&self) -> bool {
957 VariantData::Struct(..) => true,
958 _ => unsafe { unreachable_unchecked() },
964 pub fn is_struct(&self) -> bool {
965 if let VariantData::Struct(..) = *self {
968 unsafe { unreachable_unchecked() }