]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_map.rs
Rollup merge of #87759 - m-ou-se:linux-process-sealed, r=jyn514
[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::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
5 use clippy_utils::{
6     can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
7     peel_hir_expr_refs,
8 };
9 use rustc_ast::util::parser::PREC_POSTFIX;
10 use rustc_errors::Applicability;
11 use rustc_hir::LangItem::{OptionNone, OptionSome};
12 use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, MatchSource, Mutability, Pat, PatKind};
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::{sym, SyntaxContext};
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Checks for usages of `match` which could be implemented using `map`
21     ///
22     /// ### Why is this bad?
23     /// Using the `map` method is clearer and more concise.
24     ///
25     /// ### Example
26     /// ```rust
27     /// match Some(0) {
28     ///     Some(x) => Some(x + 1),
29     ///     None => None,
30     /// };
31     /// ```
32     /// Use instead:
33     /// ```rust
34     /// Some(0).map(|x| x + 1);
35     /// ```
36     pub MANUAL_MAP,
37     style,
38     "reimplementation of `map`"
39 }
40
41 declare_lint_pass!(ManualMap => [MANUAL_MAP]);
42
43 impl LateLintPass<'_> for ManualMap {
44     #[allow(clippy::too_many_lines)]
45     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
46         if let ExprKind::Match(
47             scrutinee,
48             [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
49             match_kind,
50         ) = expr.kind
51         {
52             if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
53                 return;
54             }
55
56             let (scrutinee_ty, ty_ref_count, ty_mutability) =
57                 peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
58             if !(is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type)
59                 && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type))
60             {
61                 return;
62             }
63
64             let expr_ctxt = expr.span.ctxt();
65             let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
66                 try_parse_pattern(cx, arm1.pat, expr_ctxt),
67                 try_parse_pattern(cx, arm2.pat, expr_ctxt),
68             ) {
69                 (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
70                     if is_none_expr(cx, arm1.body) =>
71                 {
72                     (arm2.body, pattern, ref_count, true)
73                 },
74                 (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
75                     if is_none_expr(cx, arm1.body) =>
76                 {
77                     (arm2.body, pattern, ref_count, false)
78                 },
79                 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
80                     if is_none_expr(cx, arm2.body) =>
81                 {
82                     (arm1.body, pattern, ref_count, true)
83                 },
84                 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
85                     if is_none_expr(cx, arm2.body) =>
86                 {
87                     (arm1.body, pattern, ref_count, false)
88                 },
89                 _ => return,
90             };
91
92             // Top level or patterns aren't allowed in closures.
93             if matches!(some_pat.kind, PatKind::Or(_)) {
94                 return;
95             }
96
97             let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
98                 Some(expr) => expr,
99                 None => return,
100             };
101
102             // These two lints will go back and forth with each other.
103             if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
104                 && !is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
105             {
106                 return;
107             }
108
109             // `map` won't perform any adjustments.
110             if !cx.typeck_results().expr_adjustments(some_expr).is_empty() {
111                 return;
112             }
113
114             if !can_move_expr_to_closure(cx, some_expr) {
115                 return;
116             }
117
118             // Determine which binding mode to use.
119             let explicit_ref = some_pat.contains_explicit_ref_binding();
120             let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
121
122             let as_ref_str = match binding_ref {
123                 Some(Mutability::Mut) => ".as_mut()",
124                 Some(Mutability::Not) => ".as_ref()",
125                 None => "",
126             };
127
128             let mut app = Applicability::MachineApplicable;
129
130             // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
131             // it's being passed by value.
132             let scrutinee = peel_hir_expr_refs(scrutinee).0;
133             let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
134             let scrutinee_str =
135                 if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
136                     format!("({})", scrutinee_str)
137                 } else {
138                     scrutinee_str.into()
139                 };
140
141             let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
142                 match can_pass_as_func(cx, id, some_expr) {
143                     Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
144                         snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
145                     },
146                     _ => {
147                         if path_to_local_id(some_expr, id)
148                             && !is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
149                             && binding_ref.is_some()
150                         {
151                             return;
152                         }
153
154                         // `ref` and `ref mut` annotations were handled earlier.
155                         let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
156                             "mut "
157                         } else {
158                             ""
159                         };
160                         format!(
161                             "|{}{}| {}",
162                             annotation,
163                             some_binding,
164                             snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
165                         )
166                     },
167                 }
168             } else if !is_wild_none && explicit_ref.is_none() {
169                 // TODO: handle explicit reference annotations.
170                 format!(
171                     "|{}| {}",
172                     snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
173                     snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
174                 )
175             } else {
176                 // Refutable bindings and mixed reference annotations can't be handled by `map`.
177                 return;
178             };
179
180             span_lint_and_sugg(
181                 cx,
182                 MANUAL_MAP,
183                 expr.span,
184                 "manual implementation of `Option::map`",
185                 "try this",
186                 if matches!(match_kind, MatchSource::IfLetDesugar { .. }) && is_else_clause(cx.tcx, expr) {
187                     format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
188                 } else {
189                     format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
190                 },
191                 app,
192             );
193         }
194     }
195 }
196
197 // Checks whether the expression could be passed as a function, or whether a closure is needed.
198 // Returns the function to be passed to `map` if it exists.
199 fn can_pass_as_func(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
200     match expr.kind {
201         ExprKind::Call(func, [arg])
202             if path_to_local_id(arg, binding) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
203         {
204             Some(func)
205         },
206         _ => None,
207     }
208 }
209
210 enum OptionPat<'a> {
211     Wild,
212     None,
213     Some {
214         // The pattern contained in the `Some` tuple.
215         pattern: &'a Pat<'a>,
216         // The number of references before the `Some` tuple.
217         // e.g. `&&Some(_)` has a ref count of 2.
218         ref_count: usize,
219     },
220 }
221
222 // Try to parse into a recognized `Option` pattern.
223 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
224 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
225     fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
226         match pat.kind {
227             PatKind::Wild => Some(OptionPat::Wild),
228             PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
229             PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
230             PatKind::TupleStruct(ref qpath, [pattern], _)
231                 if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
232             {
233                 Some(OptionPat::Some { pattern, ref_count })
234             },
235             _ => None,
236         }
237     }
238     f(cx, pat, 0, ctxt)
239 }
240
241 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
242 fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
243     // TODO: Allow more complex expressions.
244     match expr.kind {
245         ExprKind::Call(
246             Expr {
247                 kind: ExprKind::Path(ref qpath),
248                 ..
249             },
250             [arg],
251         ) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
252         ExprKind::Block(
253             Block {
254                 stmts: [],
255                 expr: Some(expr),
256                 ..
257             },
258             _,
259         ) => get_some_expr(cx, expr, ctxt),
260         _ => None,
261     }
262 }
263
264 // Checks for the `None` value.
265 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
266     match expr.kind {
267         ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
268         ExprKind::Block(
269             Block {
270                 stmts: [],
271                 expr: Some(expr),
272                 ..
273             },
274             _,
275         ) => is_none_expr(cx, expr),
276         _ => false,
277     }
278 }