1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
6 use rustc::hir::{ExprAddrOf, Expr, MutImmutable, Pat, PatKind, BindingAnnotation};
8 use rustc::ty::adjustment::{Adjustment, Adjust};
9 use utils::{span_lint, in_macro};
11 /// **What it does:** Checks for address of operations (`&`) that are going to
12 /// be dereferenced immediately by the compiler.
14 /// **Why is this bad?** Suggests that the receiver of the expression borrows
17 /// **Known problems:** None.
21 /// let x: &i32 = &&&&&&5;
26 "taking a reference that is going to be automatically dereferenced"
29 #[derive(Copy, Clone)]
30 pub struct NeedlessBorrow;
32 impl LintPass for NeedlessBorrow {
33 fn get_lints(&self) -> LintArray {
34 lint_array!(NEEDLESS_BORROW)
38 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
39 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
43 if let ExprAddrOf(MutImmutable, ref inner) = e.node {
44 if let ty::TyRef(..) = cx.tables.expr_ty(inner).sty {
45 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
47 Adjustment { kind: Adjust::Deref(_), .. },
48 Adjustment { kind: Adjust::Deref(_), .. },
49 Adjustment { kind: Adjust::Borrow(_), .. }
54 "this expression borrows a reference that is immediately dereferenced by the \
61 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
62 if in_macro(pat.span) {
66 let PatKind::Binding(BindingAnnotation::Ref, _, _, _) = pat.node,
67 let ty::TyRef(_, ref tam) = cx.tables.pat_ty(pat).sty,
68 tam.mutbl == MutImmutable,
69 let ty::TyRef(_, ref tam) = tam.ty.sty,
70 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
71 tam.mutbl == MutImmutable,
73 span_lint(cx, NEEDLESS_BORROW, pat.span, "this pattern creates a reference to a reference")