1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
5 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
6 use if_chain::if_chain;
7 use rustc::hir::{BindingAnnotation, Expr, ExprKind, HirId, Item, MutImmutable, Pat, PatKind};
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::ty::adjustment::{Adjust, Adjustment};
11 use rustc::{declare_tool_lint, lint_array};
12 use rustc_errors::Applicability;
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
23 /// let x: &i32 = &&&&&&5;
26 /// **Known problems:** None.
29 "taking a reference that is going to be automatically dereferenced"
33 pub struct NeedlessBorrow {
34 derived_item: Option<HirId>,
37 impl LintPass for NeedlessBorrow {
38 fn get_lints(&self) -> LintArray {
39 lint_array!(NEEDLESS_BORROW)
42 fn name(&self) -> &'static str {
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
48 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
49 if in_macro(e.span) || self.derived_item.is_some() {
52 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
53 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
54 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
56 kind: Adjust::Deref(_), ..
58 kind: Adjust::Deref(_), ..
60 kind: Adjust::Borrow(_),
68 "this expression borrows a reference that is immediately dereferenced \
71 if let Some(snippet) = snippet_opt(cx, inner.span) {
76 Applicability::MachineApplicable,
86 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
87 if in_macro(pat.span) || self.derived_item.is_some() {
91 if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.node;
92 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
93 if mutbl == MutImmutable;
94 if let ty::Ref(_, _, mutbl) = tam.sty;
95 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
96 if mutbl == MutImmutable;
102 "this pattern creates a reference to a reference",
104 if let Some(snippet) = snippet_opt(cx, name.span) {
109 Applicability::MachineApplicable,
118 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
119 if item.attrs.iter().any(|a| a.check_name("automatically_derived")) {
120 debug_assert!(self.derived_item.is_none());
121 self.derived_item = Some(item.hir_id);
125 fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
126 if let Some(id) = self.derived_item {
127 if item.hir_id == id {
128 self.derived_item = None;