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