]> git.lizzy.rs Git - rust.git/blob - src/needless_borrow.rs
Support either rustup or multirust environment variables
[rust.git] / 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::*;
7 use rustc::ty::TyRef;
8 use utils::{span_lint, in_macro};
9
10 /// **What it does:** This lint checks for address of operations (`&`) that are going to be dereferenced immediately by the compiler
11 ///
12 /// **Why is this bad?** Suggests that the receiver of the expression borrows the expression
13 ///
14 /// **Known problems:**
15 ///
16 /// **Example:** `let x: &i32 = &&&&&&5;`
17 declare_lint! {
18     pub NEEDLESS_BORROW,
19     Warn,
20     "taking a reference that is going to be automatically dereferenced"
21 }
22
23 #[derive(Copy,Clone)]
24 pub struct NeedlessBorrow;
25
26 impl LintPass for NeedlessBorrow {
27     fn get_lints(&self) -> LintArray {
28         lint_array!(NEEDLESS_BORROW)
29     }
30 }
31
32 impl LateLintPass for NeedlessBorrow {
33     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
34         if in_macro(cx, e.span) {
35             return;
36         }
37         if let ExprAddrOf(MutImmutable, ref inner) = e.node {
38             if let TyRef(..) = cx.tcx.expr_ty(inner).sty {
39                 let ty = cx.tcx.expr_ty(e);
40                 let adj_ty = cx.tcx.expr_ty_adjusted(e);
41                 if ty != adj_ty {
42                     span_lint(cx,
43                               NEEDLESS_BORROW,
44                               e.span,
45                               "this expression borrows a reference that is immediately dereferenced by the compiler");
46                 }
47             }
48         }
49     }
50 }