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