summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs
blob: 22f5635a5bccb803ddad652db33ce738039449ac (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
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
use super::{contains_return, BIND_INSTEAD_OF_MAP};
use clippy_utils::diagnostics::{multispan_sugg_with_applicability, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::{snippet, snippet_with_macro_callsite};
use clippy_utils::{peel_blocks, visitors::find_all_ret_expressions};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
use rustc_hir::{LangItem, QPath};
use rustc_lint::LateContext;
use rustc_middle::ty::DefIdTree;
use rustc_span::Span;

pub(crate) struct OptionAndThenSome;

impl BindInsteadOfMap for OptionAndThenSome {
    const VARIANT_LANG_ITEM: LangItem = LangItem::OptionSome;
    const BAD_METHOD_NAME: &'static str = "and_then";
    const GOOD_METHOD_NAME: &'static str = "map";
}

pub(crate) struct ResultAndThenOk;

impl BindInsteadOfMap for ResultAndThenOk {
    const VARIANT_LANG_ITEM: LangItem = LangItem::ResultOk;
    const BAD_METHOD_NAME: &'static str = "and_then";
    const GOOD_METHOD_NAME: &'static str = "map";
}

pub(crate) struct ResultOrElseErrInfo;

impl BindInsteadOfMap for ResultOrElseErrInfo {
    const VARIANT_LANG_ITEM: LangItem = LangItem::ResultErr;
    const BAD_METHOD_NAME: &'static str = "or_else";
    const GOOD_METHOD_NAME: &'static str = "map_err";
}

pub(crate) trait BindInsteadOfMap {
    const VARIANT_LANG_ITEM: LangItem;
    const BAD_METHOD_NAME: &'static str;
    const GOOD_METHOD_NAME: &'static str;

    fn no_op_msg(cx: &LateContext<'_>) -> Option<String> {
        let variant_id = cx.tcx.lang_items().require(Self::VARIANT_LANG_ITEM).ok()?;
        let item_id = cx.tcx.parent(variant_id);
        Some(format!(
            "using `{}.{}({})`, which is a no-op",
            cx.tcx.item_name(item_id),
            Self::BAD_METHOD_NAME,
            cx.tcx.item_name(variant_id),
        ))
    }

    fn lint_msg(cx: &LateContext<'_>) -> Option<String> {
        let variant_id = cx.tcx.lang_items().require(Self::VARIANT_LANG_ITEM).ok()?;
        let item_id = cx.tcx.parent(variant_id);
        Some(format!(
            "using `{}.{}(|x| {}(y))`, which is more succinctly expressed as `{}(|x| y)`",
            cx.tcx.item_name(item_id),
            Self::BAD_METHOD_NAME,
            cx.tcx.item_name(variant_id),
            Self::GOOD_METHOD_NAME
        ))
    }

    fn lint_closure_autofixable(
        cx: &LateContext<'_>,
        expr: &hir::Expr<'_>,
        recv: &hir::Expr<'_>,
        closure_expr: &hir::Expr<'_>,
        closure_args_span: Span,
    ) -> bool {
        if_chain! {
            if let hir::ExprKind::Call(some_expr, [inner_expr]) = closure_expr.kind;
            if let hir::ExprKind::Path(QPath::Resolved(_, path)) = some_expr.kind;
            if Self::is_variant(cx, path.res);
            if !contains_return(inner_expr);
            if let Some(msg) = Self::lint_msg(cx);
            then {
                let some_inner_snip = if inner_expr.span.from_expansion() {
                    snippet_with_macro_callsite(cx, inner_expr.span, "_")
                } else {
                    snippet(cx, inner_expr.span, "_")
                };

                let closure_args_snip = snippet(cx, closure_args_span, "..");
                let option_snip = snippet(cx, recv.span, "..");
                let note = format!("{}.{}({} {})", option_snip, Self::GOOD_METHOD_NAME, closure_args_snip, some_inner_snip);
                span_lint_and_sugg(
                    cx,
                    BIND_INSTEAD_OF_MAP,
                    expr.span,
                    &msg,
                    "try this",
                    note,
                    Applicability::MachineApplicable,
                );
                true
            } else {
                false
            }
        }
    }

    fn lint_closure(cx: &LateContext<'_>, expr: &hir::Expr<'_>, closure_expr: &hir::Expr<'_>) -> bool {
        let mut suggs = Vec::new();
        let can_sugg: bool = find_all_ret_expressions(cx, closure_expr, |ret_expr| {
            if_chain! {
                if !ret_expr.span.from_expansion();
                if let hir::ExprKind::Call(func_path, [arg]) = ret_expr.kind;
                if let hir::ExprKind::Path(QPath::Resolved(_, path)) = func_path.kind;
                if Self::is_variant(cx, path.res);
                if !contains_return(arg);
                then {
                    suggs.push((ret_expr.span, arg.span.source_callsite()));
                    true
                } else {
                    false
                }
            }
        });
        let (span, msg) = if_chain! {
            if can_sugg;
            if let hir::ExprKind::MethodCall(segment, ..) = expr.kind;
            if let Some(msg) = Self::lint_msg(cx);
            then { (segment.ident.span, msg) } else { return false; }
        };
        span_lint_and_then(cx, BIND_INSTEAD_OF_MAP, expr.span, &msg, |diag| {
            multispan_sugg_with_applicability(
                diag,
                "try this",
                Applicability::MachineApplicable,
                std::iter::once((span, Self::GOOD_METHOD_NAME.into())).chain(
                    suggs
                        .into_iter()
                        .map(|(span1, span2)| (span1, snippet(cx, span2, "_").into())),
                ),
            );
        });
        true
    }

    /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
    fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, arg: &hir::Expr<'_>) -> bool {
        if_chain! {
            if let Some(adt) = cx.typeck_results().expr_ty(recv).ty_adt_def();
            if let Ok(vid) = cx.tcx.lang_items().require(Self::VARIANT_LANG_ITEM);
            if adt.did() == cx.tcx.parent(vid);
            then {} else { return false; }
        }

        match arg.kind {
            hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) => {
                let closure_body = cx.tcx.hir().body(body);
                let closure_expr = peel_blocks(closure_body.value);

                if Self::lint_closure_autofixable(cx, expr, recv, closure_expr, fn_decl_span) {
                    true
                } else {
                    Self::lint_closure(cx, expr, closure_expr)
                }
            },
            // `_.and_then(Some)` case, which is no-op.
            hir::ExprKind::Path(QPath::Resolved(_, path)) if Self::is_variant(cx, path.res) => {
                if let Some(msg) = Self::no_op_msg(cx) {
                    span_lint_and_sugg(
                        cx,
                        BIND_INSTEAD_OF_MAP,
                        expr.span,
                        &msg,
                        "use the expression directly",
                        snippet(cx, recv.span, "..").into(),
                        Applicability::MachineApplicable,
                    );
                }
                true
            },
            _ => false,
        }
    }

    fn is_variant(cx: &LateContext<'_>, res: Res) -> bool {
        if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), id) = res {
            if let Ok(variant_id) = cx.tcx.lang_items().require(Self::VARIANT_LANG_ITEM) {
                return cx.tcx.parent(id) == variant_id;
            }
        }
        false
    }
}