summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/methods/obfuscated_if_else.rs
blob: 4d7427b26621398af65280b7147796ab1d4d1ac7 (plain)
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
// run-rustfix

use super::OBFUSCATED_IF_ELSE;
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_with_applicability};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;

pub(super) fn check<'tcx>(
    cx: &LateContext<'tcx>,
    expr: &'tcx hir::Expr<'_>,
    then_recv: &'tcx hir::Expr<'_>,
    then_arg: &'tcx hir::Expr<'_>,
    unwrap_arg: &'tcx hir::Expr<'_>,
) {
    // something.then_some(blah).unwrap_or(blah)
    // ^^^^^^^^^-then_recv ^^^^-then_arg   ^^^^- unwrap_arg
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr

    let recv_ty = cx.typeck_results().expr_ty(then_recv);

    if recv_ty.is_bool() {
        let mut applicability = Applicability::MachineApplicable;
        let sugg = format!(
            "if {} {{ {} }} else {{ {} }}",
            snippet_with_applicability(cx, then_recv.span, "..", &mut applicability),
            snippet_with_applicability(cx, then_arg.span, "..", &mut applicability),
            snippet_with_applicability(cx, unwrap_arg.span, "..", &mut applicability)
        );

        span_lint_and_sugg(
            cx,
            OBFUSCATED_IF_ELSE,
            expr.span,
            "use of `.then_some(..).unwrap_or(..)` can be written \
            more clearly with `if .. else ..`",
            "try",
            sugg,
            applicability,
        );
    }
}