]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrow.rs
Merge #3353
[rust.git] / clippy_lints / src / needless_borrow.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //! Checks for needless address of operations (`&`)
12 //!
13 //! This lint is **warn** by default
14
15 use crate::rustc::hir::{BindingAnnotation, Expr, ExprKind, Item, MutImmutable, Pat, PatKind};
16 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use crate::rustc::ty;
18 use crate::rustc::ty::adjustment::{Adjust, Adjustment};
19 use crate::rustc::{declare_tool_lint, lint_array};
20 use crate::rustc_errors::Applicability;
21 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
22 use crate::syntax::ast::NodeId;
23 use if_chain::if_chain;
24
25 /// **What it does:** Checks for address of operations (`&`) that are going to
26 /// be dereferenced immediately by the compiler.
27 ///
28 /// **Why is this bad?** Suggests that the receiver of the expression borrows
29 /// the expression.
30 ///
31 /// **Example:**
32 /// ```rust
33 /// let x: &i32 = &&&&&&5;
34 /// ```
35 ///
36 /// **Known problems:** None.
37 declare_clippy_lint! {
38     pub NEEDLESS_BORROW,
39     nursery,
40     "taking a reference that is going to be automatically dereferenced"
41 }
42
43 #[derive(Default)]
44 pub struct NeedlessBorrow {
45     derived_item: Option<NodeId>,
46 }
47
48 impl LintPass for NeedlessBorrow {
49     fn get_lints(&self) -> LintArray {
50         lint_array!(NEEDLESS_BORROW)
51     }
52 }
53
54 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
55     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
56         if in_macro(e.span) || self.derived_item.is_some() {
57             return;
58         }
59         if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
60             if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
61                 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
62                     if let [Adjustment {
63                         kind: Adjust::Deref(_),
64                         ..
65                     }, Adjustment {
66                         kind: Adjust::Deref(_),
67                         ..
68                     }, Adjustment {
69                         kind: Adjust::Borrow(_),
70                         ..
71                     }] = *adj3
72                     {
73                         span_lint_and_then(
74                             cx,
75                             NEEDLESS_BORROW,
76                             e.span,
77                             "this expression borrows a reference that is immediately dereferenced \
78                              by the compiler",
79                             |db| {
80                                 if let Some(snippet) = snippet_opt(cx, inner.span) {
81                                     db.span_suggestion_with_applicability(
82                                         e.span,
83                                         "change this to",
84                                         snippet,
85                                         Applicability::MachineApplicable,
86                                     );
87                                 }
88                             },
89                         );
90                     }
91                 }
92             }
93         }
94     }
95     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
96         if in_macro(pat.span) || self.derived_item.is_some() {
97             return;
98         }
99         if_chain! {
100             if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
101             if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
102             if mutbl == MutImmutable;
103             if let ty::Ref(_, _, mutbl) = tam.sty;
104             // only lint immutable refs, because borrowed `&mut T` cannot be moved out
105             if mutbl == MutImmutable;
106             then {
107                 span_lint_and_then(
108                     cx,
109                     NEEDLESS_BORROW,
110                     pat.span,
111                     "this pattern creates a reference to a reference",
112                     |db| {
113                         if let Some(snippet) = snippet_opt(cx, name.span) {
114                             db.span_suggestion_with_applicability(
115                                 pat.span,
116                                 "change this to",
117                                 snippet,
118                                 Applicability::MachineApplicable,
119                             );
120                         }
121                     }
122                 )
123             }
124         }
125     }
126
127     fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
128         if item.attrs.iter().any(|a| a.check_name("automatically_derived")) {
129             debug_assert!(self.derived_item.is_none());
130             self.derived_item = Some(item.id);
131         }
132     }
133
134     fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
135         if let Some(id) = self.derived_item {
136             if item.id == id {
137                 self.derived_item = None;
138             }
139         }
140     }
141 }