Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use itertools::Itertools;
use syntax::{
    ast::{self, make, AstNode, AstToken},
    match_ast, ted, NodeOrToken, SyntaxElement, TextRange, TextSize, T,
};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: remove_dbg
//
// Removes `dbg!()` macro call.
//
// ```
// fn main() {
//     let x = $0dbg!(42 * dbg!(4 + 2));$0
// }
// ```
// ->
// ```
// fn main() {
//     let x = 42 * (4 + 2);
// }
// ```
pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let macro_calls = if ctx.has_empty_selection() {
        vec![ctx.find_node_at_offset::<ast::MacroExpr>()?]
    } else {
        ctx.covering_element()
            .as_node()?
            .descendants()
            .filter(|node| ctx.selection_trimmed().contains_range(node.text_range()))
            // When the selection exactly covers the macro call to be removed, `covering_element()`
            // returns `ast::MacroCall` instead of its parent `ast::MacroExpr` that we want. So
            // first try finding `ast::MacroCall`s and then retrieve their parent.
            .filter_map(ast::MacroCall::cast)
            .filter_map(|it| it.syntax().parent().and_then(ast::MacroExpr::cast))
            .collect()
    };

    let replacements =
        macro_calls.into_iter().filter_map(compute_dbg_replacement).collect::<Vec<_>>();
    if replacements.is_empty() {
        return None;
    }

    acc.add(
        AssistId("remove_dbg", AssistKind::Refactor),
        "Remove dbg!()",
        replacements.iter().map(|&(range, _)| range).reduce(|acc, range| acc.cover(range)).unwrap(),
        |builder| {
            for (range, expr) in replacements {
                if let Some(expr) = expr {
                    builder.replace(range, expr.to_string());
                } else {
                    builder.delete(range);
                }
            }
        },
    )
}

/// Returns `None` when either
/// - macro call is not `dbg!()`
/// - any node inside `dbg!()` could not be parsed as an expression
/// - (`macro_expr` has no parent - is that possible?)
///
/// Returns `Some(_, None)` when the macro call should just be removed.
fn compute_dbg_replacement(macro_expr: ast::MacroExpr) -> Option<(TextRange, Option<ast::Expr>)> {
    let macro_call = macro_expr.macro_call()?;
    let tt = macro_call.token_tree()?;
    let r_delim = NodeOrToken::Token(tt.right_delimiter_token()?);
    if macro_call.path()?.segment()?.name_ref()?.text() != "dbg"
        || macro_call.excl_token().is_none()
    {
        return None;
    }

    let mac_input = tt.syntax().children_with_tokens().skip(1).take_while(|it| *it != r_delim);
    let input_expressions = mac_input.group_by(|tok| tok.kind() == T![,]);
    let input_expressions = input_expressions
        .into_iter()
        .filter_map(|(is_sep, group)| (!is_sep).then_some(group))
        .map(|mut tokens| syntax::hacks::parse_expr_from_str(&tokens.join("")))
        .collect::<Option<Vec<ast::Expr>>>()?;

    let parent = macro_expr.syntax().parent()?;
    Some(match &*input_expressions {
        // dbg!()
        [] => {
            match_ast! {
                match parent {
                    ast::StmtList(_) => {
                        let range = macro_expr.syntax().text_range();
                        let range = match whitespace_start(macro_expr.syntax().prev_sibling_or_token()) {
                            Some(start) => range.cover_offset(start),
                            None => range,
                        };
                        (range, None)
                    },
                    ast::ExprStmt(it) => {
                        let range = it.syntax().text_range();
                        let range = match whitespace_start(it.syntax().prev_sibling_or_token()) {
                            Some(start) => range.cover_offset(start),
                            None => range,
                        };
                        (range, None)
                    },
                    _ => (macro_call.syntax().text_range(), Some(make::expr_unit())),
                }
            }
        }
        // dbg!(expr0)
        [expr] => {
            // dbg!(expr, &parent);
            let wrap = match ast::Expr::cast(parent) {
                Some(parent) => match (expr, parent) {
                    (ast::Expr::CastExpr(_), ast::Expr::CastExpr(_)) => false,
                    (
                        ast::Expr::BoxExpr(_)
                        | ast::Expr::PrefixExpr(_)
                        | ast::Expr::RefExpr(_)
                        | ast::Expr::MacroExpr(_),
                        ast::Expr::AwaitExpr(_)
                        | ast::Expr::CallExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::FieldExpr(_)
                        | ast::Expr::IndexExpr(_)
                        | ast::Expr::MethodCallExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::TryExpr(_),
                    ) => true,
                    (
                        ast::Expr::BinExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::MacroExpr(_),
                        ast::Expr::AwaitExpr(_)
                        | ast::Expr::BinExpr(_)
                        | ast::Expr::CallExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::FieldExpr(_)
                        | ast::Expr::IndexExpr(_)
                        | ast::Expr::MethodCallExpr(_)
                        | ast::Expr::PrefixExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::RefExpr(_)
                        | ast::Expr::TryExpr(_),
                    ) => true,
                    _ => false,
                },
                None => false,
            };
            let expr = replace_nested_dbgs(expr.clone());
            let expr = if wrap { make::expr_paren(expr) } else { expr.clone_subtree() };
            (macro_call.syntax().text_range(), Some(expr))
        }
        // dbg!(expr0, expr1, ...)
        exprs => {
            let exprs = exprs.iter().cloned().map(replace_nested_dbgs);
            let expr = make::expr_tuple(exprs);
            (macro_call.syntax().text_range(), Some(expr))
        }
    })
}

fn replace_nested_dbgs(expanded: ast::Expr) -> ast::Expr {
    if let ast::Expr::MacroExpr(mac) = &expanded {
        // Special-case when `expanded` itself is `dbg!()` since we cannot replace the whole tree
        // with `ted`. It should be fairly rare as it means the user wrote `dbg!(dbg!(..))` but you
        // never know how code ends up being!
        let replaced = if let Some((_, expr_opt)) = compute_dbg_replacement(mac.clone()) {
            match expr_opt {
                Some(expr) => expr,
                None => {
                    stdx::never!("dbg! inside dbg! should not be just removed");
                    expanded
                }
            }
        } else {
            expanded
        };

        return replaced;
    }

    let expanded = expanded.clone_for_update();

    // We need to collect to avoid mutation during traversal.
    let macro_exprs: Vec<_> =
        expanded.syntax().descendants().filter_map(ast::MacroExpr::cast).collect();

    for mac in macro_exprs {
        let expr_opt = match compute_dbg_replacement(mac.clone()) {
            Some((_, expr)) => expr,
            None => continue,
        };

        if let Some(expr) = expr_opt {
            ted::replace(mac.syntax(), expr.syntax().clone_for_update());
        } else {
            ted::remove(mac.syntax());
        }
    }

    expanded
}

fn whitespace_start(it: Option<SyntaxElement>) -> Option<TextSize> {
    Some(it?.into_token().and_then(ast::Whitespace::cast)?.syntax().text_range().start())
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    fn check(ra_fixture_before: &str, ra_fixture_after: &str) {
        check_assist(
            remove_dbg,
            &format!("fn main() {{\n{ra_fixture_before}\n}}"),
            &format!("fn main() {{\n{ra_fixture_after}\n}}"),
        );
    }

    #[test]
    fn test_remove_dbg() {
        check("$0dbg!(1 + 1)", "1 + 1");
        check("dbg!$0(1 + 1)", "1 + 1");
        check("dbg!(1 $0+ 1)", "1 + 1");
        check("dbg![$01 + 1]", "1 + 1");
        check("dbg!{$01 + 1}", "1 + 1");
    }

    #[test]
    fn test_remove_dbg_not_applicable() {
        check_assist_not_applicable(remove_dbg, "fn main() {$0vec![1, 2, 3]}");
        check_assist_not_applicable(remove_dbg, "fn main() {$0dbg(5, 6, 7)}");
        check_assist_not_applicable(remove_dbg, "fn main() {$0dbg!(5, 6, 7}");
    }

    #[test]
    fn test_remove_dbg_keep_semicolon_in_let() {
        // https://github.com/rust-lang/rust-analyzer/issues/5129#issuecomment-651399779
        check(
            r#"let res = $0dbg!(1 * 20); // needless comment"#,
            r#"let res = 1 * 20; // needless comment"#,
        );
        check(r#"let res = $0dbg!(); // needless comment"#, r#"let res = (); // needless comment"#);
        check(
            r#"let res = $0dbg!(1, 2); // needless comment"#,
            r#"let res = (1, 2); // needless comment"#,
        );
    }

    #[test]
    fn test_remove_dbg_cast_cast() {
        check(r#"let res = $0dbg!(x as u32) as u32;"#, r#"let res = x as u32 as u32;"#);
    }

    #[test]
    fn test_remove_dbg_prefix() {
        check(r#"let res = $0dbg!(&result).foo();"#, r#"let res = (&result).foo();"#);
        check(r#"let res = &$0dbg!(&result);"#, r#"let res = &&result;"#);
        check(r#"let res = $0dbg!(!result) && true;"#, r#"let res = !result && true;"#);
    }

    #[test]
    fn test_remove_dbg_post_expr() {
        check(r#"let res = $0dbg!(fut.await).foo();"#, r#"let res = fut.await.foo();"#);
        check(r#"let res = $0dbg!(result?).foo();"#, r#"let res = result?.foo();"#);
        check(r#"let res = $0dbg!(foo as u32).foo();"#, r#"let res = (foo as u32).foo();"#);
        check(r#"let res = $0dbg!(array[3]).foo();"#, r#"let res = array[3].foo();"#);
        check(r#"let res = $0dbg!(tuple.3).foo();"#, r#"let res = tuple.3.foo();"#);
    }

    #[test]
    fn test_remove_dbg_range_expr() {
        check(r#"let res = $0dbg!(foo..bar).foo();"#, r#"let res = (foo..bar).foo();"#);
        check(r#"let res = $0dbg!(foo..=bar).foo();"#, r#"let res = (foo..=bar).foo();"#);
    }

    #[test]
    fn test_remove_empty_dbg() {
        check_assist(remove_dbg, r#"fn foo() { $0dbg!(); }"#, r#"fn foo() { }"#);
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    $0dbg!();
}
"#,
            r#"
fn foo() {
}
"#,
        );
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    let test = $0dbg!();
}"#,
            r#"
fn foo() {
    let test = ();
}"#,
        );
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    let t = {
        println!("Hello, world");
        $0dbg!()
    };
}"#,
            r#"
fn foo() {
    let t = {
        println!("Hello, world");
    };
}"#,
        );
    }

    #[test]
    fn test_remove_multi_dbg() {
        check(r#"$0dbg!(0, 1)"#, r#"(0, 1)"#);
        check(r#"$0dbg!(0, (1, 2))"#, r#"(0, (1, 2))"#);
    }

    #[test]
    fn test_range() {
        check(
            r#"
fn f() {
    dbg!(0) + $0dbg!(1);
    dbg!(())$0
}
"#,
            r#"
fn f() {
    dbg!(0) + 1;
    ()
}
"#,
        );
    }

    #[test]
    fn test_range_partial() {
        check_assist_not_applicable(remove_dbg, r#"$0dbg$0!(0)"#);
        check_assist_not_applicable(remove_dbg, r#"$0dbg!(0$0)"#);
    }

    #[test]
    fn test_nested_dbg() {
        check(
            r#"$0let x = dbg!(dbg!(dbg!(dbg!(0 + 1)) * 2) + dbg!(3));$0"#,
            r#"let x = ((0 + 1) * 2) + 3;"#,
        );
        check(r#"$0dbg!(10, dbg!(), dbg!(20, 30))$0"#, r#"(10, (), (20, 30))"#);
    }

    #[test]
    fn test_multiple_nested_dbg() {
        check(
            r#"
fn f() {
    $0dbg!();
    let x = dbg!(dbg!(dbg!(0 + 1)) + 2) + dbg!(3);
    dbg!(10, dbg!(), dbg!(20, 30));$0
}
"#,
            r#"
fn f() {
    let x = ((0 + 1) + 2) + 3;
    (10, (), (20, 30));
}
"#,
        );
    }
}
3'>813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
use std::iter::{self, successors};

use either::Either;
use ide_db::{
    defs::NameClass,
    syntax_helpers::node_ext::{is_pattern_cond, single_let},
    ty_filter::TryEnum,
    RootDatabase,
};
use syntax::{
    ast::{
        self,
        edit::{AstNodeEdit, IndentLevel},
        make, HasName,
    },
    AstNode, TextRange,
};

use crate::{
    utils::{does_nested_pattern, does_pat_match_variant, unwrap_trivial_block},
    AssistContext, AssistId, AssistKind, Assists,
};

// Assist: replace_if_let_with_match
//
// Replaces a `if let` expression with a `match` expression.
//
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Action) {
//     $0if let Action::Move { distance } = action {
//         foo(distance)
//     } else {
//         bar()
//     }
// }
// ```
// ->
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Action) {
//     match action {
//         Action::Move { distance } => foo(distance),
//         _ => bar(),
//     }
// }
// ```
pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
    let available_range = TextRange::new(
        if_expr.syntax().text_range().start(),
        if_expr.then_branch()?.syntax().text_range().start(),
    );
    let cursor_in_range = available_range.contains_range(ctx.selection_trimmed());
    if !cursor_in_range {
        return None;
    }
    let mut else_block = None;
    let if_exprs = successors(Some(if_expr.clone()), |expr| match expr.else_branch()? {
        ast::ElseBranch::IfExpr(expr) => Some(expr),
        ast::ElseBranch::Block(block) => {
            else_block = Some(block);
            None
        }
    });
    let scrutinee_to_be_expr = if_expr.condition()?;
    let scrutinee_to_be_expr = match single_let(scrutinee_to_be_expr.clone()) {
        Some(cond) => cond.expr()?,
        None => scrutinee_to_be_expr,
    };

    let mut pat_seen = false;
    let mut cond_bodies = Vec::new();
    for if_expr in if_exprs {
        let cond = if_expr.condition()?;
        let cond = match single_let(cond.clone()) {
            Some(let_) => {
                let pat = let_.pat()?;
                let expr = let_.expr()?;
                // FIXME: If one `let` is wrapped in parentheses and the second is not,
                // we'll exit here.
                if scrutinee_to_be_expr.syntax().text() != expr.syntax().text() {
                    // Only if all condition expressions are equal we can merge them into a match
                    return None;
                }
                pat_seen = true;
                Either::Left(pat)
            }
            // Multiple `let`, unsupported.
            None if is_pattern_cond(cond.clone()) => return None,
            None => Either::Right(cond),
        };
        let body = if_expr.then_branch()?;
        cond_bodies.push((cond, body));
    }

    if !pat_seen {
        // Don't offer turning an if (chain) without patterns into a match
        return None;
    }

    acc.add(
        AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
        "Replace if let with match",
        available_range,
        move |edit| {
            let match_expr = {
                let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
                let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
                    let body = body.reset_indent().indent(IndentLevel(1));
                    match pat {
                        Either::Left(pat) => {
                            make::match_arm(iter::once(pat), None, unwrap_trivial_block(body))
                        }
                        Either::Right(expr) => make::match_arm(
                            iter::once(make::wildcard_pat().into()),
                            Some(expr),
                            unwrap_trivial_block(body),
                        ),
                    }
                };
                let arms = cond_bodies.into_iter().map(make_match_arm).chain(iter::once(else_arm));
                let match_expr = make::expr_match(scrutinee_to_be_expr, make::match_arm_list(arms));
                match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
            };

            let has_preceding_if_expr =
                if_expr.syntax().parent().map_or(false, |it| ast::IfExpr::can_cast(it.kind()));
            let expr = if has_preceding_if_expr {
                // make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
                make::block_expr(None, Some(match_expr)).into()
            } else {
                match_expr
            };
            edit.replace_ast::<ast::Expr>(if_expr.into(), expr);
        },
    )
}

fn make_else_arm(
    ctx: &AssistContext<'_>,
    else_block: Option<ast::BlockExpr>,
    conditionals: &[(Either<ast::Pat, ast::Expr>, ast::BlockExpr)],
) -> ast::MatchArm {
    if let Some(else_block) = else_block {
        let pattern = if let [(Either::Left(pat), _)] = conditionals {
            ctx.sema
                .type_of_pat(pat)
                .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
                .zip(Some(pat))
        } else {
            None
        };
        let pattern = match pattern {
            Some((it, pat)) => {
                if does_pat_match_variant(pat, &it.sad_pattern()) {
                    it.happy_pattern_wildcard()
                } else if does_nested_pattern(pat) {
                    make::wildcard_pat().into()
                } else {
                    it.sad_pattern()
                }
            }
            None => make::wildcard_pat().into(),
        };
        make::match_arm(iter::once(pattern), None, unwrap_trivial_block(else_block))
    } else {
        make::match_arm(iter::once(make::wildcard_pat().into()), None, make::expr_unit())
    }
}

// Assist: replace_match_with_if_let
//
// Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression.
//
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Action) {
//     $0match action {
//         Action::Move { distance } => foo(distance),
//         _ => bar(),
//     }
// }
// ```
// ->
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Action) {
//     if let Action::Move { distance } = action {
//         foo(distance)
//     } else {
//         bar()
//     }
// }
// ```
pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?;

    let mut arms = match_expr.match_arm_list()?.arms();
    let (first_arm, second_arm) = (arms.next()?, arms.next()?);
    if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() {
        return None;
    }

    let (if_let_pat, then_expr, else_expr) = pick_pattern_and_expr_order(
        &ctx.sema,
        first_arm.pat()?,
        second_arm.pat()?,
        first_arm.expr()?,
        second_arm.expr()?,
    )?;
    let scrutinee = match_expr.expr()?;

    let target = match_expr.syntax().text_range();
    acc.add(
        AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
        "Replace match with if let",
        target,
        move |edit| {
            fn make_block_expr(expr: ast::Expr) -> ast::BlockExpr {
                // Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are
                // formatted without enclosing braces. If we encounter such block exprs,
                // wrap them in another BlockExpr.
                match expr {
                    ast::Expr::BlockExpr(block) if block.modifier().is_none() => block,
                    expr => make::block_expr(iter::empty(), Some(expr)),
                }
            }

            let condition = make::expr_let(if_let_pat, scrutinee);
            let then_block = make_block_expr(then_expr.reset_indent());
            let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) };
            let if_let_expr = make::expr_if(
                condition.into(),
                then_block,
                else_expr.map(make_block_expr).map(ast::ElseBranch::Block),
            )
            .indent(IndentLevel::from_node(match_expr.syntax()));

            edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
        },
    )
}

/// Pick the pattern for the if let condition and return the expressions for the `then` body and `else` body in that order.
fn pick_pattern_and_expr_order(
    sema: &hir::Semantics<'_, RootDatabase>,
    pat: ast::Pat,
    pat2: ast::Pat,
    expr: ast::Expr,
    expr2: ast::Expr,
) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
    let res = match (pat, pat2) {
        (ast::Pat::WildcardPat(_), _) => return None,
        (pat, ast::Pat::WildcardPat(_)) => (pat, expr, expr2),
        (pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
        (_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
        (pat, pat2) => match (binds_name(sema, &pat), binds_name(sema, &pat2)) {
            (true, true) => return None,
            (true, false) => (pat, expr, expr2),
            (false, true) => (pat2, expr2, expr),
            _ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
            (false, false) => (pat, expr, expr2),
        },
    };
    Some(res)
}

fn is_empty_expr(expr: &ast::Expr) -> bool {
    match expr {
        ast::Expr::BlockExpr(expr) => match expr.stmt_list() {
            Some(it) => it.statements().next().is_none() && it.tail_expr().is_none(),
            None => true,
        },
        ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
        _ => false,
    }
}

fn binds_name(sema: &hir::Semantics<'_, RootDatabase>, pat: &ast::Pat) -> bool {
    let binds_name_v = |pat| binds_name(sema, &pat);
    match pat {
        ast::Pat::IdentPat(pat) => !matches!(
            pat.name().and_then(|name| NameClass::classify(sema, &name)),
            Some(NameClass::ConstReference(_))
        ),
        ast::Pat::MacroPat(_) => true,
        ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
        ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
        ast::Pat::TuplePat(it) => it.fields().any(binds_name_v),
        ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
        ast::Pat::RecordPat(it) => it
            .record_pat_field_list()
            .map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
        ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
        ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
        ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
        _ => false,
    }
}

fn is_sad_pat(sema: &hir::Semantics<'_, RootDatabase>, pat: &ast::Pat) -> bool {
    sema.type_of_pat(pat)
        .and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
        .map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};

    #[test]
    fn test_if_let_with_match_unapplicable_for_simple_ifs() {
        check_assist_not_applicable(
            replace_if_let_with_match,
            r#"
fn main() {
    if $0true {} else if false {} else {}
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_no_else() {
        check_assist(
            replace_if_let_with_match,
            r#"
impl VariantData {
    pub fn foo(&self) {
        if $0let VariantData::Struct(..) = *self {
            self.foo();
        }
    }
}
"#,
            r#"
impl VariantData {
    pub fn foo(&self) {
        match *self {
            VariantData::Struct(..) => {
                self.foo();
            }
            _ => (),
        }
    }
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_available_range_left() {
        check_assist_not_applicable(
            replace_if_let_with_match,
            r#"
impl VariantData {
    pub fn foo(&self) {
        $0 if let VariantData::Struct(..) = *self {
            self.foo();
        }
    }
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_available_range_right() {
        check_assist_not_applicable(
            replace_if_let_with_match,
            r#"
impl VariantData {
    pub fn foo(&self) {
        if let VariantData::Struct(..) = *self {$0
            self.foo();
        }
    }
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_let_chain() {
        check_assist_not_applicable(
            replace_if_let_with_match,
            r#"
fn main() {
    if $0let true = true && let Some(1) = None {}
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_basic() {
        check_assist(
            replace_if_let_with_match,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        if $0let VariantData::Struct(..) = *self {
            true
        } else if let VariantData::Tuple(..) = *self {
            false
        } else if cond() {
            true
        } else {
            bar(
                123
            )
        }
    }
}
"#,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        match *self {
            VariantData::Struct(..) => true,
            VariantData::Tuple(..) => false,
            _ if cond() => true,
            _ => {
                    bar(
                        123
                    )
                }
        }
    }
}
"#,
        )
    }

    #[test]
    fn test_if_let_with_match_on_tail_if_let() {
        check_assist(
            replace_if_let_with_match,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        if let VariantData::Struct(..) = *self {
            true
        } else if let$0 VariantData::Tuple(..) = *self {
            false
        } else {
            false
        }
    }
}
"#,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        if let VariantData::Struct(..) = *self {
            true
        } else {
    match *self {
            VariantData::Tuple(..) => false,
            _ => false,
        }
}
    }
}
"#,
        )
    }

    #[test]
    fn special_case_option() {
        check_assist(
            replace_if_let_with_match,
            r#"
//- minicore: option
fn foo(x: Option<i32>) {
    $0if let Some(x) = x {
        println!("{}", x)
    } else {
        println!("none")
    }
}
"#,
            r#"
fn foo(x: Option<i32>) {
    match x {
        Some(x) => println!("{}", x),
        None => println!("none"),
    }
}
"#,
        );
    }

    #[test]
    fn special_case_inverted_option() {
        check_assist(
            replace_if_let_with_match,
            r#"
//- minicore: option
fn foo(x: Option<i32>) {
    $0if let None = x {
        println!("none")
    } else {
        println!("some")
    }
}
"#,
            r#"
fn foo(x: Option<i32>) {
    match x {
        None => println!("none"),
        Some(_) => println!("some"),
    }
}
"#,
        );
    }

    #[test]
    fn special_case_result() {
        check_assist(
            replace_if_let_with_match,
            r#"
//- minicore: result
fn foo(x: Result<i32, ()>) {
    $0if let Ok(x) = x {
        println!("{}", x)
    } else {
        println!("none")
    }
}
"#,
            r#"
fn foo(x: Result<i32, ()>) {
    match x {
        Ok(x) => println!("{}", x),
        Err(_) => println!("none"),
    }
}
"#,
        );
    }

    #[test]
    fn special_case_inverted_result() {
        check_assist(
            replace_if_let_with_match,
            r#"
//- minicore: result
fn foo(x: Result<i32, ()>) {
    $0if let Err(x) = x {
        println!("{}", x)
    } else {
        println!("ok")
    }
}
"#,
            r#"
fn foo(x: Result<i32, ()>) {
    match x {
        Err(x) => println!("{}", x),
        Ok(_) => println!("ok"),
    }
}
"#,
        );
    }

    #[test]
    fn nested_indent() {
        check_assist(
            replace_if_let_with_match,
            r#"
fn main() {
    if true {
        $0if let Ok(rel_path) = path.strip_prefix(root_path) {
            let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
            Some((*id, rel_path))
        } else {
            None
        }
    }
}
"#,
            r#"
fn main() {
    if true {
        match path.strip_prefix(root_path) {
            Ok(rel_path) => {
                let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
                Some((*id, rel_path))
            }
            _ => None,
        }
    }
}
"#,
        )
    }

    #[test]
    fn nested_type() {
        check_assist(
            replace_if_let_with_match,
            r#"
//- minicore: result
fn foo(x: Result<i32, ()>) {
    let bar: Result<_, ()> = Ok(Some(1));
    $0if let Ok(Some(_)) = bar {
        ()
    } else {
        ()
    }
}
"#,
            r#"
fn foo(x: Result<i32, ()>) {
    let bar: Result<_, ()> = Ok(Some(1));
    match bar {
        Ok(Some(_)) => (),
        _ => (),
    }
}
"#,
        );
    }

    #[test]
    fn test_replace_match_with_if_let_unwraps_simple_expressions() {
        check_assist(
            replace_match_with_if_let,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        $0match *self {
            VariantData::Struct(..) => true,
            _ => false,
        }
    }
}           "#,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        if let VariantData::Struct(..) = *self {
            true
        } else {
            false
        }
    }
}           "#,
        )
    }

    #[test]
    fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn foo() {
    $0match a {
        VariantData::Struct(..) => {
            bar(
                123
            )
        }
        _ => false,
    }
}           "#,
            r#"
fn foo() {
    if let VariantData::Struct(..) = a {
        bar(
            123
        )
    } else {
        false
    }
}           "#,
        )
    }

    #[test]
    fn replace_match_with_if_let_target() {
        check_assist_target(
            replace_match_with_if_let,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        $0match *self {
            VariantData::Struct(..) => true,
            _ => false,
        }
    }
}           "#,
            r#"match *self {
            VariantData::Struct(..) => true,
            _ => false,
        }"#,
        );
    }

    #[test]
    fn special_case_option_match_to_if_let() {
        check_assist(
            replace_match_with_if_let,
            r#"
//- minicore: option
fn foo(x: Option<i32>) {
    $0match x {
        Some(x) => println!("{}", x),
        None => println!("none"),
    }
}
"#,
            r#"
fn foo(x: Option<i32>) {
    if let Some(x) = x {
        println!("{}", x)
    } else {
        println!("none")
    }
}
"#,
        );
    }

    #[test]
    fn special_case_result_match_to_if_let() {
        check_assist(
            replace_match_with_if_let,
            r#"
//- minicore: result
fn foo(x: Result<i32, ()>) {
    $0match x {
        Ok(x) => println!("{}", x),
        Err(_) => println!("none"),
    }
}
"#,
            r#"
fn foo(x: Result<i32, ()>) {
    if let Ok(x) = x {
        println!("{}", x)
    } else {
        println!("none")
    }
}
"#,
        );
    }

    #[test]
    fn nested_indent_match_to_if_let() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn main() {
    if true {
        $0match path.strip_prefix(root_path) {
            Ok(rel_path) => {
                let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
                Some((*id, rel_path))
            }
            _ => None,
        }
    }
}
"#,
            r#"
fn main() {
    if true {
        if let Ok(rel_path) = path.strip_prefix(root_path) {
            let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
            Some((*id, rel_path))
        } else {
            None
        }
    }
}
"#,
        )
    }

    #[test]
    fn replace_match_with_if_let_empty_wildcard_expr() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn main() {
    $0match path.strip_prefix(root_path) {
        Ok(rel_path) => println!("{}", rel_path),
        _ => (),
    }
}
"#,
            r#"
fn main() {
    if let Ok(rel_path) = path.strip_prefix(root_path) {
        println!("{}", rel_path)
    }
}
"#,
        )
    }

    #[test]
    fn replace_match_with_if_let_number_body() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn main() {
    $0match Ok(()) {
        Ok(()) => {},
        Err(_) => 0,
    }
}
"#,
            r#"
fn main() {
    if let Err(_) = Ok(()) {
        0
    }
}
"#,
        )
    }

    #[test]
    fn replace_match_with_if_let_exhaustive() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn print_source(def_source: ModuleSource) {
    match def_so$0urce {
        ModuleSource::SourceFile(..) => { println!("source file"); }
        ModuleSource::Module(..) => { println!("module"); }
    }
}
"#,
            r#"
fn print_source(def_source: ModuleSource) {
    if let ModuleSource::SourceFile(..) = def_source { println!("source file"); } else { println!("module"); }
}
"#,
        )
    }

    #[test]
    fn replace_match_with_if_let_prefer_name_bind() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn foo() {
    match $0Foo(0) {
        Foo(_) => (),
        Bar(bar) => println!("bar {}", bar),
    }
}
"#,
            r#"
fn foo() {
    if let Bar(bar) = Foo(0) {
        println!("bar {}", bar)
    }
}
"#,
        );
        check_assist(
            replace_match_with_if_let,
            r#"
fn foo() {
    match $0Foo(0) {
        Bar(bar) => println!("bar {}", bar),
        Foo(_) => (),
    }
}
"#,
            r#"
fn foo() {
    if let Bar(bar) = Foo(0) {
        println!("bar {}", bar)
    }
}
"#,
        );
    }

    #[test]
    fn replace_match_with_if_let_prefer_nonempty_body() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn foo() {
    match $0Ok(0) {
        Ok(value) => {},
        Err(err) => eprintln!("{}", err),
    }
}
"#,
            r#"
fn foo() {
    if let Err(err) = Ok(0) {
        eprintln!("{}", err)
    }
}
"#,
        );
        check_assist(
            replace_match_with_if_let,
            r#"
fn foo() {
    match $0Ok(0) {
        Err(err) => eprintln!("{}", err),
        Ok(value) => {},
    }
}
"#,
            r#"
fn foo() {
    if let Err(err) = Ok(0) {
        eprintln!("{}", err)
    }
}
"#,
        );
    }

    #[test]
    fn replace_match_with_if_let_rejects_double_name_bindings() {
        check_assist_not_applicable(
            replace_match_with_if_let,
            r#"
fn foo() {
    match $0Foo(0) {
        Foo(foo) => println!("bar {}", foo),
        Bar(bar) => println!("bar {}", bar),
    }
}
"#,
        );
    }

    #[test]
    fn test_replace_match_with_if_let_keeps_unsafe_block() {
        check_assist(
            replace_match_with_if_let,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        $0match *self {
            VariantData::Struct(..) => true,
            _ => unsafe { unreachable_unchecked() },
        }
    }
}           "#,
            r#"
impl VariantData {
    pub fn is_struct(&self) -> bool {
        if let VariantData::Struct(..) = *self {
            true
        } else {
            unsafe { unreachable_unchecked() }
        }
    }
}           "#,
        )
    }

    #[test]
    fn test_replace_match_with_if_let_forces_else() {
        check_assist(
            replace_match_with_if_let,
            r#"
fn main() {
    match$0 0 {
        0 => (),
        _ => code(),
    }
}
"#,
            r#"
fn main() {
    if let 0 = 0 {
        ()
    } else {
        code()
    }
}
"#,
        )
    }
}