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