1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
8 use rustc::hir::{BindingAnnotation, Expr, ExprKind, MutImmutable, Pat, PatKind};
10 use rustc::ty::adjustment::{Adjust, Adjustment};
11 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
13 /// **What it does:** Checks for address of operations (`&`) that are going to
14 /// be dereferenced immediately by the compiler.
16 /// **Why is this bad?** Suggests that the receiver of the expression borrows
19 /// **Known problems:** None.
23 /// let x: &i32 = &&&&&&5;
25 declare_clippy_lint! {
28 "taking a reference that is going to be automatically dereferenced"
31 #[derive(Copy, Clone)]
32 pub struct NeedlessBorrow;
34 impl LintPass for NeedlessBorrow {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(NEEDLESS_BORROW)
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
45 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
46 if let ty::TyRef(..) = cx.tables.expr_ty(inner).sty {
47 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
49 kind: Adjust::Deref(_),
52 kind: Adjust::Deref(_),
55 kind: Adjust::Borrow(_),
63 "this expression borrows a reference that is immediately dereferenced \
66 if let Some(snippet) = snippet_opt(cx, inner.span) {
67 db.span_suggestion(e.span, "change this to", snippet);
76 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
77 if in_macro(pat.span) {
81 if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
82 if let ty::TyRef(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
83 if mutbl == MutImmutable;
84 if let ty::TyRef(_, _, mutbl) = tam.sty;
85 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
86 if mutbl == MutImmutable;
92 "this pattern creates a reference to a reference",
94 if let Some(snippet) = snippet_opt(cx, name.span) {
95 db.span_suggestion(pat.span, "change this to", snippet);