]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_borrow.rs
Merge pull request #1146 from birkenfeld/housekeeping
[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 rustc::lint::*;
6 use rustc::hir::{ExprAddrOf, Expr, MutImmutable, Pat, PatKind, BindingMode};
7 use rustc::ty::TyRef;
8 use utils::{span_lint, in_macro};
9 use rustc::ty::adjustment::AutoAdjustment::AdjustDerefRef;
10
11 /// **What it does:** Checks for address of operations (`&`) that are going to
12 /// be dereferenced immediately by the compiler.
13 ///
14 /// **Why is this bad?** Suggests that the receiver of the expression borrows
15 /// the expression.
16 ///
17 /// **Known problems:** None.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// let x: &i32 = &&&&&&5;
22 /// ```
23 declare_lint! {
24     pub NEEDLESS_BORROW,
25     Warn,
26     "taking a reference that is going to be automatically dereferenced"
27 }
28
29 #[derive(Copy,Clone)]
30 pub struct NeedlessBorrow;
31
32 impl LintPass for NeedlessBorrow {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(NEEDLESS_BORROW)
35     }
36 }
37
38 impl LateLintPass for NeedlessBorrow {
39     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
40         if in_macro(cx, e.span) {
41             return;
42         }
43         if let ExprAddrOf(MutImmutable, ref inner) = e.node {
44             if let TyRef(..) = cx.tcx.expr_ty(inner).sty {
45                 if let Some(&AdjustDerefRef(ref deref)) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
46                     if deref.autoderefs > 1 && deref.autoref.is_some() {
47                         span_lint(cx,
48                                   NEEDLESS_BORROW,
49                                   e.span,
50                                   "this expression borrows a reference that is immediately dereferenced by the \
51                                    compiler");
52                     }
53                 }
54             }
55         }
56     }
57     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
58         if in_macro(cx, pat.span) {
59             return;
60         }
61         if let PatKind::Binding(BindingMode::BindByRef(MutImmutable), _, _) = pat.node {
62             if let TyRef(_, ref tam) = cx.tcx.pat_ty(pat).sty {
63                 if tam.mutbl == MutImmutable {
64                     if let TyRef(..) = tam.ty.sty {
65                         span_lint(cx,
66                                   NEEDLESS_BORROW,
67                                   pat.span,
68                                   "this pattern creates a reference to a reference")
69                     }
70                 }
71             }
72         }
73     }
74 }