]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_map.rs
Rollup merge of #83343 - osa1:issue83340, r=jackh726
[rust.git] / src / tools / clippy / 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, is_else_clause_of_if_let_else, 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, MatchSource, 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(
55             scrutinee,
56             [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
57             match_kind,
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                 if matches!(match_kind, MatchSource::IfLetDesugar { .. }) && is_else_clause_of_if_let_else(cx.tcx, expr)
185                 {
186                     format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
187                 } else {
188                     format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
189                 },
190                 app,
191             );
192         }
193     }
194 }
195
196 // Checks if the expression can be moved into a closure as is.
197 fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
198     struct V<'cx, 'tcx> {
199         cx: &'cx LateContext<'tcx>,
200         make_closure: bool,
201     }
202     impl Visitor<'tcx> for V<'_, 'tcx> {
203         type Map = ErasedMap<'tcx>;
204         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
205             NestedVisitorMap::None
206         }
207
208         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
209             match e.kind {
210                 ExprKind::Break(..)
211                 | ExprKind::Continue(_)
212                 | ExprKind::Ret(_)
213                 | ExprKind::Yield(..)
214                 | ExprKind::InlineAsm(_)
215                 | ExprKind::LlvmInlineAsm(_) => {
216                     self.make_closure = false;
217                 },
218                 // Accessing a field of a local value can only be done if the type isn't
219                 // partially moved.
220                 ExprKind::Field(base_expr, _)
221                     if matches!(
222                         base_expr.kind,
223                         ExprKind::Path(QPath::Resolved(_, Path { res: Res::Local(_), .. }))
224                     ) && can_partially_move_ty(self.cx, self.cx.typeck_results().expr_ty(base_expr)) =>
225                 {
226                     // TODO: check if the local has been partially moved. Assume it has for now.
227                     self.make_closure = false;
228                     return;
229                 }
230                 _ => (),
231             };
232             walk_expr(self, e);
233         }
234     }
235
236     let mut v = V { cx, make_closure: true };
237     v.visit_expr(expr);
238     v.make_closure
239 }
240
241 // Checks whether the expression could be passed as a function, or whether a closure is needed.
242 // Returns the function to be passed to `map` if it exists.
243 fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
244     match expr.kind {
245         ExprKind::Call(func, [arg])
246             if match_var(arg, binding.name) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
247         {
248             Some(func)
249         },
250         _ => None,
251     }
252 }
253
254 enum OptionPat<'a> {
255     Wild,
256     None,
257     Some {
258         // The pattern contained in the `Some` tuple.
259         pattern: &'a Pat<'a>,
260         // The number of references before the `Some` tuple.
261         // e.g. `&&Some(_)` has a ref count of 2.
262         ref_count: usize,
263     },
264 }
265
266 // Try to parse into a recognized `Option` pattern.
267 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
268 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
269     fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
270         match pat.kind {
271             PatKind::Wild => Some(OptionPat::Wild),
272             PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
273             PatKind::Path(QPath::Resolved(None, path))
274                 if path
275                     .res
276                     .opt_def_id()
277                     .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)) =>
278             {
279                 Some(OptionPat::None)
280             },
281             PatKind::TupleStruct(QPath::Resolved(None, path), [pattern], _)
282                 if path
283                     .res
284                     .opt_def_id()
285                     .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME))
286                     && pat.span.ctxt() == ctxt =>
287             {
288                 Some(OptionPat::Some { pattern, ref_count })
289             },
290             _ => None,
291         }
292     }
293     f(cx, pat, 0, ctxt)
294 }
295
296 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
297 fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
298     // TODO: Allow more complex expressions.
299     match expr.kind {
300         ExprKind::Call(
301             Expr {
302                 kind: ExprKind::Path(QPath::Resolved(None, path)),
303                 ..
304             },
305             [arg],
306         ) if ctxt == expr.span.ctxt() => {
307             if match_def_path(cx, path.res.opt_def_id()?, &paths::OPTION_SOME) {
308                 Some(arg)
309             } else {
310                 None
311             }
312         },
313         ExprKind::Block(
314             Block {
315                 stmts: [],
316                 expr: Some(expr),
317                 ..
318             },
319             _,
320         ) => get_some_expr(cx, expr, ctxt),
321         _ => None,
322     }
323 }
324
325 // Checks for the `None` value.
326 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
327     match expr.kind {
328         ExprKind::Path(QPath::Resolved(None, path)) => path
329             .res
330             .opt_def_id()
331             .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)),
332         ExprKind::Block(
333             Block {
334                 stmts: [],
335                 expr: Some(expr),
336                 ..
337             },
338             _,
339         ) => is_none_expr(cx, expr),
340         _ => false,
341     }
342 }