1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
5 use clippy_utils::diagnostics::span_lint_and_then;
6 use clippy_utils::source::snippet_opt;
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::{BindingAnnotation, BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind};
10 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for address of operations (`&`) that are going to
17 /// be dereferenced immediately by the compiler.
19 /// **Why is this bad?** Suggests that the receiver of the expression borrows
22 /// **Known problems:** None.
27 /// let x: &i32 = &&&&&&5;
34 "taking a reference that is going to be automatically dereferenced"
38 pub struct NeedlessBorrow;
40 impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]);
42 impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow {
43 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
44 if e.span.from_expansion() {
47 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = e.kind {
48 if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(inner).kind() {
49 for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) {
51 kind: Adjust::Deref(_), ..
53 kind: Adjust::Deref(_), ..
55 kind: Adjust::Borrow(_),
64 "this expression borrows a reference (`&{}`) that is immediately dereferenced \
69 if let Some(snippet) = snippet_opt(cx, inner.span) {
74 Applicability::MachineApplicable,
84 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
85 if pat.span.from_expansion() {
89 if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind;
90 if let ty::Ref(_, tam, mutbl) = *cx.typeck_results().pat_ty(pat).kind();
91 if mutbl == Mutability::Not;
92 if let ty::Ref(_, _, mutbl) = *tam.kind();
93 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
94 if mutbl == Mutability::Not;
100 "this pattern creates a reference to a reference",
102 if let Some(snippet) = snippet_opt(cx, name.span) {
103 diag.span_suggestion(
107 Applicability::MachineApplicable,