]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrow.rs
Auto merge of #6462 - flip1995:roadmap, r=flip1995,llogiq,killercup,Manishearth,oli...
[rust.git] / clippy_lints / src / needless_borrow.rs
1 //! Checks for needless address of operations (`&`)
2 //!
3 //! This lint is **warn** by default
4
5 use crate::utils::{is_automatically_derived, snippet_opt, span_lint_and_then};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BindingAnnotation, BorrowKind, Expr, ExprKind, HirId, Item, Mutability, Pat, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty;
11 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for address of operations (`&`) that are going to
16     /// be dereferenced immediately by the compiler.
17     ///
18     /// **Why is this bad?** Suggests that the receiver of the expression borrows
19     /// the expression.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     /// ```rust
25     /// // Bad
26     /// let x: &i32 = &&&&&&5;
27     ///
28     /// // Good
29     /// let x: &i32 = &5;
30     /// ```
31     pub NEEDLESS_BORROW,
32     nursery,
33     "taking a reference that is going to be automatically dereferenced"
34 }
35
36 #[derive(Default)]
37 pub struct NeedlessBorrow {
38     derived_item: Option<HirId>,
39 }
40
41 impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]);
42
43 impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow {
44     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
45         if e.span.from_expansion() || self.derived_item.is_some() {
46             return;
47         }
48         if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = e.kind {
49             if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(inner).kind() {
50                 for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) {
51                     if let [Adjustment {
52                         kind: Adjust::Deref(_), ..
53                     }, Adjustment {
54                         kind: Adjust::Deref(_), ..
55                     }, Adjustment {
56                         kind: Adjust::Borrow(_),
57                         ..
58                     }] = *adj3
59                     {
60                         span_lint_and_then(
61                             cx,
62                             NEEDLESS_BORROW,
63                             e.span,
64                             &format!(
65                                 "this expression borrows a reference (`&{}`) that is immediately dereferenced \
66                              by the compiler",
67                                 ty
68                             ),
69                             |diag| {
70                                 if let Some(snippet) = snippet_opt(cx, inner.span) {
71                                     diag.span_suggestion(
72                                         e.span,
73                                         "change this to",
74                                         snippet,
75                                         Applicability::MachineApplicable,
76                                     );
77                                 }
78                             },
79                         );
80                     }
81                 }
82             }
83         }
84     }
85     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
86         if pat.span.from_expansion() || self.derived_item.is_some() {
87             return;
88         }
89         if_chain! {
90             if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind;
91             if let ty::Ref(_, tam, mutbl) = *cx.typeck_results().pat_ty(pat).kind();
92             if mutbl == Mutability::Not;
93             if let ty::Ref(_, _, mutbl) = *tam.kind();
94             // only lint immutable refs, because borrowed `&mut T` cannot be moved out
95             if mutbl == Mutability::Not;
96             then {
97                 span_lint_and_then(
98                     cx,
99                     NEEDLESS_BORROW,
100                     pat.span,
101                     "this pattern creates a reference to a reference",
102                     |diag| {
103                         if let Some(snippet) = snippet_opt(cx, name.span) {
104                             diag.span_suggestion(
105                                 pat.span,
106                                 "change this to",
107                                 snippet,
108                                 Applicability::MachineApplicable,
109                             );
110                         }
111                     }
112                 )
113             }
114         }
115     }
116
117     fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) {
118         if is_automatically_derived(item.attrs) {
119             debug_assert!(self.derived_item.is_none());
120             self.derived_item = Some(item.hir_id);
121         }
122     }
123
124     fn check_item_post(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) {
125         if let Some(id) = self.derived_item {
126             if item.hir_id == id {
127                 self.derived_item = None;
128             }
129         }
130     }
131 }