1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
6 use crate::utils::{in_macro_or_desugar, snippet_opt, span_lint_and_then};
7 use if_chain::if_chain;
8 use rustc::hir::{BindingAnnotation, Expr, ExprKind, HirId, Item, MutImmutable, Pat, PatKind};
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::ty::adjustment::{Adjust, Adjustment};
12 use rustc::{declare_tool_lint, impl_lint_pass};
13 use rustc_errors::Applicability;
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
24 /// let x: &i32 = &&&&&&5;
27 /// **Known problems:** None.
30 "taking a reference that is going to be automatically dereferenced"
34 pub struct NeedlessBorrow {
35 derived_item: Option<HirId>,
38 impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
42 if in_macro_or_desugar(e.span) || self.derived_item.is_some() {
45 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
46 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
47 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
49 kind: Adjust::Deref(_), ..
51 kind: Adjust::Deref(_), ..
53 kind: Adjust::Borrow(_),
61 "this expression borrows a reference that is immediately dereferenced \
64 if let Some(snippet) = snippet_opt(cx, inner.span) {
69 Applicability::MachineApplicable,
79 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
80 if in_macro_or_desugar(pat.span) || self.derived_item.is_some() {
84 if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.node;
85 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
86 if mutbl == MutImmutable;
87 if let ty::Ref(_, _, mutbl) = tam.sty;
88 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
89 if mutbl == MutImmutable;
95 "this pattern creates a reference to a reference",
97 if let Some(snippet) = snippet_opt(cx, name.span) {
102 Applicability::MachineApplicable,
111 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
112 if item.attrs.iter().any(|a| a.check_name(*sym::automatically_derived)) {
113 debug_assert!(self.derived_item.is_none());
114 self.derived_item = Some(item.hir_id);
118 fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
119 if let Some(id) = self.derived_item {
120 if item.hir_id == id {
121 self.derived_item = None;