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::is_automatically_derived;
7 use clippy_utils::source::snippet_opt;
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::{BindingAnnotation, BorrowKind, Expr, ExprKind, Item, Mutability, Pat, PatKind};
11 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::def_id::LocalDefId;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for address of operations (`&`) that are going to
19 /// be dereferenced immediately by the compiler.
21 /// **Why is this bad?** Suggests that the receiver of the expression borrows
24 /// **Known problems:** None.
29 /// let x: &i32 = &&&&&&5;
36 "taking a reference that is going to be automatically dereferenced"
40 pub struct NeedlessBorrow {
41 derived_item: Option<LocalDefId>,
44 impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]);
46 impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow {
47 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
48 if e.span.from_expansion() || self.derived_item.is_some() {
51 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = e.kind {
52 if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(inner).kind() {
53 for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) {
55 kind: Adjust::Deref(_), ..
57 kind: Adjust::Deref(_), ..
59 kind: Adjust::Borrow(_),
68 "this expression borrows a reference (`&{}`) that is immediately dereferenced \
73 if let Some(snippet) = snippet_opt(cx, inner.span) {
78 Applicability::MachineApplicable,
88 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
89 if pat.span.from_expansion() || self.derived_item.is_some() {
93 if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind;
94 if let ty::Ref(_, tam, mutbl) = *cx.typeck_results().pat_ty(pat).kind();
95 if mutbl == Mutability::Not;
96 if let ty::Ref(_, _, mutbl) = *tam.kind();
97 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
98 if mutbl == Mutability::Not;
104 "this pattern creates a reference to a reference",
106 if let Some(snippet) = snippet_opt(cx, name.span) {
107 diag.span_suggestion(
111 Applicability::MachineApplicable,
120 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
121 let attrs = cx.tcx.hir().attrs(item.hir_id());
122 if is_automatically_derived(attrs) {
123 debug_assert!(self.derived_item.is_none());
124 self.derived_item = Some(item.def_id);
128 fn check_item_post(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) {
129 if let Some(id) = self.derived_item {
130 if item.def_id == id {
131 self.derived_item = None;