1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
6 use rustc::hir::{ExprAddrOf, Expr, MutImmutable, Pat, PatKind, BindingMode};
8 use utils::{span_lint, in_macro};
10 /// **What it does:** Checks for address of operations (`&`) that are going to
11 /// be dereferenced immediately by the compiler.
13 /// **Why is this bad?** Suggests that the receiver of the expression borrows
16 /// **Known problems:** None.
20 /// let x: &i32 = &&&&&&5;
25 "taking a reference that is going to be automatically dereferenced"
29 pub struct NeedlessBorrow;
31 impl LintPass for NeedlessBorrow {
32 fn get_lints(&self) -> LintArray {
33 lint_array!(NEEDLESS_BORROW)
37 impl LateLintPass for NeedlessBorrow {
38 fn check_expr<'a, 'tcx: 'a>(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
39 if in_macro(cx, e.span) {
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, .. }) = cx.tcx.tables.borrow().adjustments.get(&e.id).map(|a| &a.kind) {
45 if autoderefs > 1 && autoref.is_some() {
49 "this expression borrows a reference that is immediately dereferenced by the \
56 fn check_pat<'a, 'tcx: 'a>(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
57 if in_macro(cx, pat.span) {
60 if let PatKind::Binding(BindingMode::BindByRef(MutImmutable), _, _, _) = pat.node {
61 if let ty::TyRef(_, ref tam) = cx.tcx.tables().pat_ty(pat).sty {
62 if tam.mutbl == MutImmutable {
63 if let ty::TyRef(..) = tam.ty.sty {
67 "this pattern creates a reference to a reference")