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