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