]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_map.rs
Auto merge of #7097 - yawara:fix/7069, r=llogiq
[rust.git] / clippy_lints / src / manual_map.rs
1 use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
4 use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
5 use clippy_utils::{
6     can_move_expr_to_closure, in_constant, is_allowed, is_else_clause, is_lang_ctor, match_var, peel_hir_expr_refs,
7 };
8 use rustc_ast::util::parser::PREC_POSTFIX;
9 use rustc_errors::Applicability;
10 use rustc_hir::LangItem::{OptionNone, OptionSome};
11 use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, MatchSource, Mutability, Pat, PatKind};
12 use rustc_lint::{LateContext, LateLintPass, LintContext};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::{
16     symbol::{sym, Ident},
17     SyntaxContext,
18 };
19
20 declare_clippy_lint! {
21     /// **What it does:** Checks for usages of `match` which could be implemented using `map`
22     ///
23     /// **Why is this bad?** Using the `map` method is clearer and more concise.
24     ///
25     /// **Known problems:** None.
26     ///
27     /// **Example:**
28     ///
29     /// ```rust
30     /// match Some(0) {
31     ///     Some(x) => Some(x + 1),
32     ///     None => None,
33     /// };
34     /// ```
35     /// Use instead:
36     /// ```rust
37     /// Some(0).map(|x| x + 1);
38     /// ```
39     pub MANUAL_MAP,
40     style,
41     "reimplementation of `map`"
42 }
43
44 declare_lint_pass!(ManualMap => [MANUAL_MAP]);
45
46 impl LateLintPass<'_> for ManualMap {
47     #[allow(clippy::too_many_lines)]
48     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
49         if let ExprKind::Match(
50             scrutinee,
51             [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
52             match_kind,
53         ) = expr.kind
54         {
55             if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
56                 return;
57             }
58
59             let (scrutinee_ty, ty_ref_count, ty_mutability) =
60                 peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
61             if !(is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type)
62                 && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type))
63             {
64                 return;
65             }
66
67             let expr_ctxt = expr.span.ctxt();
68             let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
69                 try_parse_pattern(cx, arm1.pat, expr_ctxt),
70                 try_parse_pattern(cx, arm2.pat, expr_ctxt),
71             ) {
72                 (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
73                     if is_none_expr(cx, arm1.body) =>
74                 {
75                     (arm2.body, pattern, ref_count, true)
76                 },
77                 (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
78                     if is_none_expr(cx, arm1.body) =>
79                 {
80                     (arm2.body, pattern, ref_count, false)
81                 },
82                 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
83                     if is_none_expr(cx, arm2.body) =>
84                 {
85                     (arm1.body, pattern, ref_count, true)
86                 },
87                 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
88                     if is_none_expr(cx, arm2.body) =>
89                 {
90                     (arm1.body, pattern, ref_count, false)
91                 },
92                 _ => return,
93             };
94
95             // Top level or patterns aren't allowed in closures.
96             if matches!(some_pat.kind, PatKind::Or(_)) {
97                 return;
98             }
99
100             let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
101                 Some(expr) => expr,
102                 None => return,
103             };
104
105             // These two lints will go back and forth with each other.
106             if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
107                 && !is_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
108             {
109                 return;
110             }
111
112             // `map` won't perform any adjustments.
113             if !cx.typeck_results().expr_adjustments(some_expr).is_empty() {
114                 return;
115             }
116
117             if !can_move_expr_to_closure(cx, some_expr) {
118                 return;
119             }
120
121             // Determine which binding mode to use.
122             let explicit_ref = some_pat.contains_explicit_ref_binding();
123             let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
124
125             let as_ref_str = match binding_ref {
126                 Some(Mutability::Mut) => ".as_mut()",
127                 Some(Mutability::Not) => ".as_ref()",
128                 None => "",
129             };
130
131             let mut app = Applicability::MachineApplicable;
132
133             // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
134             // it's being passed by value.
135             let scrutinee = peel_hir_expr_refs(scrutinee).0;
136             let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
137             let scrutinee_str =
138                 if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
139                     format!("({})", scrutinee_str)
140                 } else {
141                     scrutinee_str.into()
142                 };
143
144             let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind {
145                 match can_pass_as_func(cx, some_binding, some_expr) {
146                     Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
147                         snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
148                     },
149                     _ => {
150                         if match_var(some_expr, some_binding.name)
151                             && !is_allowed(cx, MATCH_AS_REF, expr.hir_id)
152                             && binding_ref.is_some()
153                         {
154                             return;
155                         }
156
157                         // `ref` and `ref mut` annotations were handled earlier.
158                         let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
159                             "mut "
160                         } else {
161                             ""
162                         };
163                         format!(
164                             "|{}{}| {}",
165                             annotation,
166                             some_binding,
167                             snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
168                         )
169                     },
170                 }
171             } else if !is_wild_none && explicit_ref.is_none() {
172                 // TODO: handle explicit reference annotations.
173                 format!(
174                     "|{}| {}",
175                     snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
176                     snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
177                 )
178             } else {
179                 // Refutable bindings and mixed reference annotations can't be handled by `map`.
180                 return;
181             };
182
183             span_lint_and_sugg(
184                 cx,
185                 MANUAL_MAP,
186                 expr.span,
187                 "manual implementation of `Option::map`",
188                 "try this",
189                 if matches!(match_kind, MatchSource::IfLetDesugar { .. }) && is_else_clause(cx.tcx, expr) {
190                     format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
191                 } else {
192                     format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
193                 },
194                 app,
195             );
196         }
197     }
198 }
199
200 // Checks whether the expression could be passed as a function, or whether a closure is needed.
201 // Returns the function to be passed to `map` if it exists.
202 fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
203     match expr.kind {
204         ExprKind::Call(func, [arg])
205             if match_var(arg, binding.name) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
206         {
207             Some(func)
208         },
209         _ => None,
210     }
211 }
212
213 enum OptionPat<'a> {
214     Wild,
215     None,
216     Some {
217         // The pattern contained in the `Some` tuple.
218         pattern: &'a Pat<'a>,
219         // The number of references before the `Some` tuple.
220         // e.g. `&&Some(_)` has a ref count of 2.
221         ref_count: usize,
222     },
223 }
224
225 // Try to parse into a recognized `Option` pattern.
226 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
227 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
228     fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
229         match pat.kind {
230             PatKind::Wild => Some(OptionPat::Wild),
231             PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
232             PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
233             PatKind::TupleStruct(ref qpath, [pattern], _)
234                 if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
235             {
236                 Some(OptionPat::Some { pattern, ref_count })
237             },
238             _ => None,
239         }
240     }
241     f(cx, pat, 0, ctxt)
242 }
243
244 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
245 fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
246     // TODO: Allow more complex expressions.
247     match expr.kind {
248         ExprKind::Call(
249             Expr {
250                 kind: ExprKind::Path(ref qpath),
251                 ..
252             },
253             [arg],
254         ) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
255         ExprKind::Block(
256             Block {
257                 stmts: [],
258                 expr: Some(expr),
259                 ..
260             },
261             _,
262         ) => get_some_expr(cx, expr, ctxt),
263         _ => None,
264     }
265 }
266
267 // Checks for the `None` value.
268 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
269     match expr.kind {
270         ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
271         ExprKind::Block(
272             Block {
273                 stmts: [],
274                 expr: Some(expr),
275                 ..
276             },
277             _,
278         ) => is_none_expr(cx, expr),
279         _ => false,
280     }
281 }