]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrowed_ref.rs
Auto merge of #4879 - matthiaskrgr:rustup_23, r=flip1995
[rust.git] / clippy_lints / src / needless_borrowed_ref.rs
1 //! Checks for useless borrowed references.
2 //!
3 //! This lint is **warn** by default
4
5 use crate::utils::{snippet_with_applicability, span_lint_and_then};
6 use if_chain::if_chain;
7 use rustc::declare_lint_pass;
8 use rustc::hir::{BindingAnnotation, Mutability, Node, Pat, PatKind};
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc_errors::Applicability;
11 use rustc_session::declare_tool_lint;
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for useless borrowed references.
15     ///
16     /// **Why is this bad?** It is mostly useless and make the code look more
17     /// complex than it
18     /// actually is.
19     ///
20     /// **Known problems:** It seems that the `&ref` pattern is sometimes useful.
21     /// For instance in the following snippet:
22     /// ```rust,ignore
23     /// enum Animal {
24     ///     Cat(u64),
25     ///     Dog(u64),
26     /// }
27     ///
28     /// fn foo(a: &Animal, b: &Animal) {
29     ///     match (a, b) {
30     ///         (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime mismatch error
31     ///         (&Animal::Dog(ref c), &Animal::Dog(_)) => ()
32     ///     }
33     /// }
34     /// ```
35     /// There is a lifetime mismatch error for `k` (indeed a and b have distinct
36     /// lifetime).
37     /// This can be fixed by using the `&ref` pattern.
38     /// However, the code can also be fixed by much cleaner ways
39     ///
40     /// **Example:**
41     /// ```rust
42     /// let mut v = Vec::<String>::new();
43     /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
44     /// ```
45     /// This closure takes a reference on something that has been matched as a
46     /// reference and
47     /// de-referenced.
48     /// As such, it could just be |a| a.is_empty()
49     pub NEEDLESS_BORROWED_REFERENCE,
50     complexity,
51     "taking a needless borrowed reference"
52 }
53
54 declare_lint_pass!(NeedlessBorrowedRef => [NEEDLESS_BORROWED_REFERENCE]);
55
56 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
57     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
58         if pat.span.from_expansion() {
59             // OK, simple enough, lints doesn't check in macro.
60             return;
61         }
62
63         if_chain! {
64             // Only lint immutable refs, because `&mut ref T` may be useful.
65             if let PatKind::Ref(ref sub_pat, Mutability::Immutable) = pat.kind;
66
67             // Check sub_pat got a `ref` keyword (excluding `ref mut`).
68             if let PatKind::Binding(BindingAnnotation::Ref, .., spanned_name, _) = sub_pat.kind;
69             let parent_id = cx.tcx.hir().get_parent_node(pat.hir_id);
70             if let Some(parent_node) = cx.tcx.hir().find(parent_id);
71             then {
72                 // do not recurse within patterns, as they may have other references
73                 // XXXManishearth we can relax this constraint if we only check patterns
74                 // with a single ref pattern inside them
75                 if let Node::Pat(_) = parent_node {
76                     return;
77                 }
78                 let mut applicability = Applicability::MachineApplicable;
79                 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
80                                    "this pattern takes a reference on something that is being de-referenced",
81                                    |db| {
82                                        let hint = snippet_with_applicability(cx, spanned_name.span, "..", &mut applicability).into_owned();
83                                        db.span_suggestion(
84                                            pat.span,
85                                            "try removing the `&ref` part and just keep",
86                                            hint,
87                                            applicability,
88                                        );
89                                    });
90             }
91         }
92     }
93 }