]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrowed_ref.rs
Auto merge of #3598 - xfix:apply-cargo-fix-edition-idioms, r=phansch
[rust.git] / clippy_lints / src / needless_borrowed_ref.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! Checks for useless borrowed references.
11 //!
12 //! This lint is **warn** by default
13
14 use crate::utils::{in_macro, snippet, span_lint_and_then};
15 use if_chain::if_chain;
16 use rustc::hir::{BindingAnnotation, MutImmutable, Pat, PatKind};
17 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
18 use rustc::{declare_tool_lint, lint_array};
19 use rustc_errors::Applicability;
20
21 /// **What it does:** Checks for useless borrowed references.
22 ///
23 /// **Why is this bad?** It is mostly useless and make the code look more
24 /// complex than it
25 /// actually is.
26 ///
27 /// **Known problems:** It seems that the `&ref` pattern is sometimes useful.
28 /// For instance in the following snippet:
29 /// ```rust
30 /// enum Animal {
31 ///     Cat(u64),
32 ///     Dog(u64),
33 /// }
34 ///
35 /// fn foo(a: &Animal, b: &Animal) {
36 ///     match (a, b) {
37 /// (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime
38 /// mismatch error
39 ///         (&Animal::Dog(ref c), &Animal::Dog(_)) => ()
40 ///     }
41 /// }
42 /// ```
43 /// There is a lifetime mismatch error for `k` (indeed a and b have distinct
44 /// lifetime).
45 /// This can be fixed by using the `&ref` pattern.
46 /// However, the code can also be fixed by much cleaner ways
47 ///
48 /// **Example:**
49 /// ```rust
50 /// let mut v = Vec::<String>::new();
51 /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
52 /// ```
53 /// This closure takes a reference on something that has been matched as a
54 /// reference and
55 /// de-referenced.
56 /// As such, it could just be |a| a.is_empty()
57 declare_clippy_lint! {
58     pub NEEDLESS_BORROWED_REFERENCE,
59     complexity,
60     "taking a needless borrowed reference"
61 }
62
63 #[derive(Copy, Clone)]
64 pub struct NeedlessBorrowedRef;
65
66 impl LintPass for NeedlessBorrowedRef {
67     fn get_lints(&self) -> LintArray {
68         lint_array!(NEEDLESS_BORROWED_REFERENCE)
69     }
70 }
71
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
73     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
74         if in_macro(pat.span) {
75             // OK, simple enough, lints doesn't check in macro.
76             return;
77         }
78
79         if_chain! {
80             // Only lint immutable refs, because `&mut ref T` may be useful.
81             if let PatKind::Ref(ref sub_pat, MutImmutable) = pat.node;
82
83             // Check sub_pat got a `ref` keyword (excluding `ref mut`).
84             if let PatKind::Binding(BindingAnnotation::Ref, _, spanned_name, ..) = sub_pat.node;
85             then {
86                 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
87                                    "this pattern takes a reference on something that is being de-referenced",
88                                    |db| {
89                                        let hint = snippet(cx, spanned_name.span, "..").into_owned();
90                                        db.span_suggestion_with_applicability(
91                                            pat.span,
92                                            "try removing the `&ref` part and just keep",
93                                            hint,
94                                            Applicability::MachineApplicable, // snippet
95                                        );
96                                    });
97             }
98         }
99     }
100 }