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