]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrow.rs
clippy: support `QPath::LangItem`
[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
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(..) = 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                             "this expression borrows a reference that is immediately dereferenced \
65                              by the compiler",
66                             |diag| {
67                                 if let Some(snippet) = snippet_opt(cx, inner.span) {
68                                     diag.span_suggestion(
69                                         e.span,
70                                         "change this to",
71                                         snippet,
72                                         Applicability::MachineApplicable,
73                                     );
74                                 }
75                             },
76                         );
77                     }
78                 }
79             }
80         }
81     }
82     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
83         if pat.span.from_expansion() || self.derived_item.is_some() {
84             return;
85         }
86         if_chain! {
87             if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind;
88             if let ty::Ref(_, tam, mutbl) = cx.typeck_results().pat_ty(pat).kind;
89             if mutbl == Mutability::Not;
90             if let ty::Ref(_, _, mutbl) = tam.kind;
91             // only lint immutable refs, because borrowed `&mut T` cannot be moved out
92             if mutbl == Mutability::Not;
93             then {
94                 span_lint_and_then(
95                     cx,
96                     NEEDLESS_BORROW,
97                     pat.span,
98                     "this pattern creates a reference to a reference",
99                     |diag| {
100                         if let Some(snippet) = snippet_opt(cx, name.span) {
101                             diag.span_suggestion(
102                                 pat.span,
103                                 "change this to",
104                                 snippet,
105                                 Applicability::MachineApplicable,
106                             );
107                         }
108                     }
109                 )
110             }
111         }
112     }
113
114     fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) {
115         if item.attrs.iter().any(|a| a.has_name(sym!(automatically_derived))) {
116             debug_assert!(self.derived_item.is_none());
117             self.derived_item = Some(item.hir_id);
118         }
119     }
120
121     fn check_item_post(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) {
122         if let Some(id) = self.derived_item {
123             if item.hir_id == id {
124                 self.derived_item = None;
125             }
126         }
127     }
128 }