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