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