]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_map.rs
Fix `manual_map` suggestion when used with unsafe functions and unsafe blocks.
[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, type_is_unsafe_function};
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, BlockCheckMode, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path,
15     QPath, UnsafeSource,
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::{sym, SyntaxContext};
21
22 declare_clippy_lint! {
23     /// ### What it does
24     /// Checks for usages of `match` which could be implemented using `map`
25     ///
26     /// ### Why is this bad?
27     /// Using the `map` method is clearer and more concise.
28     ///
29     /// ### Example
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     #[clippy::version = "1.52.0"]
41     pub MANUAL_MAP,
42     style,
43     "reimplementation of `map`"
44 }
45
46 declare_lint_pass!(ManualMap => [MANUAL_MAP]);
47
48 impl LateLintPass<'_> for ManualMap {
49     #[allow(clippy::too_many_lines)]
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51         let (scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) {
52             Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else),
53             Some(IfLetOrMatch::Match(
54                 scrutinee,
55                 [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
56                 _,
57             )) => (scrutinee, arm1.pat, arm1.body, Some(arm2.pat), arm2.body),
58             _ => return,
59         };
60         if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
61             return;
62         }
63
64         let (scrutinee_ty, ty_ref_count, ty_mutability) =
65             peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
66         if !(is_type_diagnostic_item(cx, scrutinee_ty, sym::Option)
67             && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Option))
68         {
69             return;
70         }
71
72         let expr_ctxt = expr.span.ctxt();
73         let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
74             try_parse_pattern(cx, then_pat, expr_ctxt),
75             else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),
76         ) {
77             (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
78                 (else_body, pattern, ref_count, true)
79             },
80             (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
81                 (else_body, pattern, ref_count, false)
82             },
83             (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_expr(cx, else_body) => {
84                 (then_body, pattern, ref_count, true)
85             },
86             (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_expr(cx, else_body) => {
87                 (then_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, false, 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.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.expr).is_empty() {
111             return;
112         }
113
114         // Determine which binding mode to use.
115         let explicit_ref = some_pat.contains_explicit_ref_binding();
116         let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
117
118         let as_ref_str = match binding_ref {
119             Some(Mutability::Mut) => ".as_mut()",
120             Some(Mutability::Not) => ".as_ref()",
121             None => "",
122         };
123
124         match can_move_expr_to_closure(cx, some_expr.expr) {
125             Some(captures) => {
126                 // Check if captures the closure will need conflict with borrows made in the scrutinee.
127                 // TODO: check all the references made in the scrutinee expression. This will require interacting
128                 // with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
129                 if let Some(binding_ref_mutability) = binding_ref {
130                     let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
131                         ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
132                         _ => None,
133                     });
134                     if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l), .. })) = e.kind {
135                         match captures.get(l) {
136                             Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
137                             Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {
138                                 return;
139                             },
140                             Some(CaptureKind::Ref(Mutability::Not)) | None => (),
141                         }
142                     }
143                 }
144             },
145             None => return,
146         };
147
148         let mut app = Applicability::MachineApplicable;
149
150         // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
151         // it's being passed by value.
152         let scrutinee = peel_hir_expr_refs(scrutinee).0;
153         let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
154         let scrutinee_str =
155             if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
156                 format!("({})", scrutinee_str)
157             } else {
158                 scrutinee_str.into()
159             };
160
161         let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
162             if_chain! {
163                 if !some_expr.needs_unsafe_block;
164                 if let Some(func) = can_pass_as_func(cx, id, some_expr.expr);
165                 if func.span.ctxt() == some_expr.expr.span.ctxt();
166                 then {
167                     snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
168                 } else {
169                     if path_to_local_id(some_expr.expr, id)
170                         && !is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
171                         && binding_ref.is_some()
172                     {
173                         return;
174                     }
175
176                     // `ref` and `ref mut` annotations were handled earlier.
177                     let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
178                         "mut "
179                     } else {
180                         ""
181                     };
182                     if some_expr.needs_unsafe_block {
183                         format!(
184                             "|{}{}| unsafe {{ {} }}",
185                             annotation,
186                             some_binding,
187                             snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0
188                         )
189                     } else {
190                         format!(
191                             "|{}{}| {}",
192                             annotation,
193                             some_binding,
194                             snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0
195                         )
196                     }
197                 }
198             }
199         } else if !is_wild_none && explicit_ref.is_none() {
200             // TODO: handle explicit reference annotations.
201             if some_expr.needs_unsafe_block {
202                 format!(
203                     "|{}| unsafe {{ {} }}",
204                     snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
205                     snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0
206                 )
207             } else {
208                 format!(
209                     "|{}| {}",
210                     snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
211                     snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0
212                 )
213             }
214         } else {
215             // Refutable bindings and mixed reference annotations can't be handled by `map`.
216             return;
217         };
218
219         span_lint_and_sugg(
220             cx,
221             MANUAL_MAP,
222             expr.span,
223             "manual implementation of `Option::map`",
224             "try this",
225             if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
226                 format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
227             } else {
228                 format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
229             },
230             app,
231         );
232     }
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: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
238     match expr.kind {
239         ExprKind::Call(func, [arg])
240             if path_to_local_id(arg, binding)
241                 && cx.typeck_results().expr_adjustments(arg).is_empty()
242                 && !type_is_unsafe_function(cx, cx.typeck_results().expr_ty(func).peel_refs()) =>
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 struct SomeExpr<'tcx> {
263     expr: &'tcx Expr<'tcx>,
264     needs_unsafe_block: bool,
265 }
266
267 // Try to parse into a recognized `Option` pattern.
268 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
269 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
270     fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
271         match pat.kind {
272             PatKind::Wild => Some(OptionPat::Wild),
273             PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
274             PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
275             PatKind::TupleStruct(ref qpath, [pattern], _)
276                 if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
277             {
278                 Some(OptionPat::Some { pattern, ref_count })
279             },
280             _ => None,
281         }
282     }
283     f(cx, pat, 0, ctxt)
284 }
285
286 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
287 fn get_some_expr(
288     cx: &LateContext<'tcx>,
289     expr: &'tcx Expr<'_>,
290     needs_unsafe_block: bool,
291     ctxt: SyntaxContext,
292 ) -> Option<SomeExpr<'tcx>> {
293     // TODO: Allow more complex expressions.
294     match expr.kind {
295         ExprKind::Call(
296             Expr {
297                 kind: ExprKind::Path(ref qpath),
298                 ..
299             },
300             [arg],
301         ) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(SomeExpr {
302             expr: arg,
303             needs_unsafe_block,
304         }),
305         ExprKind::Block(
306             Block {
307                 stmts: [],
308                 expr: Some(expr),
309                 rules,
310                 ..
311             },
312             _,
313         ) => get_some_expr(
314             cx,
315             expr,
316             needs_unsafe_block || *rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided),
317             ctxt,
318         ),
319         _ => None,
320     }
321 }
322
323 // Checks for the `None` value.
324 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
325     match expr.kind {
326         ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
327         ExprKind::Block(
328             Block {
329                 stmts: [],
330                 expr: Some(expr),
331                 ..
332             },
333             _,
334         ) => is_none_expr(cx, expr),
335         _ => false,
336     }
337 }