1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
5 use crate::utils::{snippet_opt, span_lint_and_then};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BindingAnnotation, BorrowKind, Expr, ExprKind, HirId, Item, Mutability, Pat, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for address of operations (`&`) that are going to
16 /// be dereferenced immediately by the compiler.
18 /// **Why is this bad?** Suggests that the receiver of the expression borrows
21 /// **Known problems:** None.
26 /// let x: &i32 = &&&&&&5;
33 "taking a reference that is going to be automatically dereferenced"
37 pub struct NeedlessBorrow {
38 derived_item: Option<HirId>,
41 impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]);
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
44 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
45 if e.span.from_expansion() || self.derived_item.is_some() {
48 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = e.kind {
49 if let ty::Ref(..) = cx.tables.expr_ty(inner).kind {
50 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
52 kind: Adjust::Deref(_), ..
54 kind: Adjust::Deref(_), ..
56 kind: Adjust::Borrow(_),
64 "this expression borrows a reference that is immediately dereferenced \
67 if let Some(snippet) = snippet_opt(cx, inner.span) {
72 Applicability::MachineApplicable,
82 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) {
83 if pat.span.from_expansion() || self.derived_item.is_some() {
87 if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind;
88 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).kind;
89 if mutbl == Mutability::Not;
90 if let ty::Ref(_, _, mutbl) = tam.kind;
91 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
92 if mutbl == Mutability::Not;
98 "this pattern creates a reference to a reference",
100 if let Some(snippet) = snippet_opt(cx, name.span) {
101 diag.span_suggestion(
105 Applicability::MachineApplicable,
114 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
115 if item.attrs.iter().any(|a| a.check_name(sym!(automatically_derived))) {
116 debug_assert!(self.derived_item.is_none());
117 self.derived_item = Some(item.hir_id);
121 fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
122 if let Some(id) = self.derived_item {
123 if item.hir_id == id {
124 self.derived_item = None;