]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrowed_ref.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[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
11 //! Checks for useless borrowed references.
12 //!
13 //! This lint is **warn** by default
14
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::{declare_tool_lint, lint_array};
17 use if_chain::if_chain;
18 use crate::rustc::hir::{BindingAnnotation, MutImmutable, Pat, PatKind};
19 use crate::utils::{in_macro, snippet, span_lint_and_then};
20 use crate::rustc_errors::Applicability;
21
22 /// **What it does:** Checks for useless borrowed references.
23 ///
24 /// **Why is this bad?** It is mostly useless and make the code look more
25 /// complex than it
26 /// actually is.
27 ///
28 /// **Known problems:** It seems that the `&ref` pattern is sometimes useful.
29 /// For instance in the following snippet:
30 /// ```rust
31 /// enum Animal {
32 ///     Cat(u64),
33 ///     Dog(u64),
34 /// }
35 ///
36 /// fn foo(a: &Animal, b: &Animal) {
37 ///     match (a, b) {
38 /// (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime
39 /// mismatch error
40 ///         (&Animal::Dog(ref c), &Animal::Dog(_)) => ()
41 ///     }
42 /// }
43 /// ```
44 /// There is a lifetime mismatch error for `k` (indeed a and b have distinct
45 /// lifetime).
46 /// This can be fixed by using the `&ref` pattern.
47 /// However, the code can also be fixed by much cleaner ways
48 ///
49 /// **Example:**
50 /// ```rust
51 ///     let mut v = Vec::<String>::new();
52 ///     let _ = v.iter_mut().filter(|&ref a| a.is_empty());
53 /// ```
54 /// This closure takes a reference on something that has been matched as a
55 /// reference and
56 /// de-referenced.
57 /// As such, it could just be |a| a.is_empty()
58 declare_clippy_lint! {
59     pub NEEDLESS_BORROWED_REFERENCE,
60     complexity,
61     "taking a needless borrowed reference"
62 }
63
64 #[derive(Copy, Clone)]
65 pub struct NeedlessBorrowedRef;
66
67 impl LintPass for NeedlessBorrowedRef {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(NEEDLESS_BORROWED_REFERENCE)
70     }
71 }
72
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
74     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
75         if in_macro(pat.span) {
76             // OK, simple enough, lints doesn't check in macro.
77             return;
78         }
79
80         if_chain! {
81             // Only lint immutable refs, because `&mut ref T` may be useful.
82             if let PatKind::Ref(ref sub_pat, MutImmutable) = pat.node;
83
84             // Check sub_pat got a `ref` keyword (excluding `ref mut`).
85             if let PatKind::Binding(BindingAnnotation::Ref, _, spanned_name, ..) = sub_pat.node;
86             then {
87                 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
88                                    "this pattern takes a reference on something that is being de-referenced",
89                                    |db| {
90                                        let hint = snippet(cx, spanned_name.span, "..").into_owned();
91                                        db.span_suggestion_with_applicability(
92                                            pat.span, 
93                                            "try removing the `&ref` part and just keep",
94                                            hint,
95                                            Applicability::MachineApplicable, // snippet
96                                        );
97                                    });
98             }
99         }
100     }
101 }