]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs
Rollup merge of #80720 - steffahn:prettify_prelude_imports, r=camelid,jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / needless_borrowed_ref.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet_with_applicability;
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{BindingAnnotation, Mutability, Node, Pat, PatKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for bindings that destructure a reference and borrow the inner
11     /// value with `&ref`.
12     ///
13     /// **Why is this bad?** This pattern has no effect in almost all cases.
14     ///
15     /// **Known problems:** In some cases, `&ref` is needed to avoid a lifetime mismatch error.
16     /// Example:
17     /// ```rust
18     /// fn foo(a: &Option<String>, b: &Option<String>) {
19     ///     match (a, b) {
20     ///         (None, &ref c) | (&ref c, None) => (),
21     ///         (&Some(ref c), _) => (),
22     ///     };
23     /// }
24     /// ```
25     ///
26     /// **Example:**
27     /// Bad:
28     /// ```rust
29     /// let mut v = Vec::<String>::new();
30     /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
31     /// ```
32     ///
33     /// Good:
34     /// ```rust
35     /// let mut v = Vec::<String>::new();
36     /// let _ = v.iter_mut().filter(|a| a.is_empty());
37     /// ```
38     pub NEEDLESS_BORROWED_REFERENCE,
39     complexity,
40     "destructuring a reference and borrowing the inner value"
41 }
42
43 declare_lint_pass!(NeedlessBorrowedRef => [NEEDLESS_BORROWED_REFERENCE]);
44
45 impl<'tcx> LateLintPass<'tcx> for NeedlessBorrowedRef {
46     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
47         if pat.span.from_expansion() {
48             // OK, simple enough, lints doesn't check in macro.
49             return;
50         }
51
52         if_chain! {
53             // Only lint immutable refs, because `&mut ref T` may be useful.
54             if let PatKind::Ref(ref sub_pat, Mutability::Not) = pat.kind;
55
56             // Check sub_pat got a `ref` keyword (excluding `ref mut`).
57             if let PatKind::Binding(BindingAnnotation::Ref, .., spanned_name, _) = sub_pat.kind;
58             let parent_id = cx.tcx.hir().get_parent_node(pat.hir_id);
59             if let Some(parent_node) = cx.tcx.hir().find(parent_id);
60             then {
61                 // do not recurse within patterns, as they may have other references
62                 // XXXManishearth we can relax this constraint if we only check patterns
63                 // with a single ref pattern inside them
64                 if let Node::Pat(_) = parent_node {
65                     return;
66                 }
67                 let mut applicability = Applicability::MachineApplicable;
68                 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
69                                    "this pattern takes a reference on something that is being de-referenced",
70                                    |diag| {
71                                        let hint = snippet_with_applicability(cx, spanned_name.span, "..", &mut applicability).into_owned();
72                                        diag.span_suggestion(
73                                            pat.span,
74                                            "try removing the `&ref` part and just keep",
75                                            hint,
76                                            applicability,
77                                        );
78                                    });
79             }
80         }
81     }
82 }