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