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