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, 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;
13 use syntax::ast::NodeId;
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.
27 declare_clippy_lint! {
30 "taking a reference that is going to be automatically dereferenced"
34 pub struct NeedlessBorrow {
35 derived_item: Option<NodeId>,
38 impl LintPass for NeedlessBorrow {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(NEEDLESS_BORROW)
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
45 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
46 if in_macro(e.span) || self.derived_item.is_some() {
49 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
50 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
51 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
53 kind: Adjust::Deref(_), ..
55 kind: Adjust::Deref(_), ..
57 kind: Adjust::Borrow(_),
65 "this expression borrows a reference that is immediately dereferenced \
68 if let Some(snippet) = snippet_opt(cx, inner.span) {
69 db.span_suggestion_with_applicability(
73 Applicability::MachineApplicable,
83 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
84 if in_macro(pat.span) || self.derived_item.is_some() {
88 if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
89 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
90 if mutbl == MutImmutable;
91 if let ty::Ref(_, _, mutbl) = tam.sty;
92 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
93 if mutbl == MutImmutable;
99 "this pattern creates a reference to a reference",
101 if let Some(snippet) = snippet_opt(cx, name.span) {
102 db.span_suggestion_with_applicability(
106 Applicability::MachineApplicable,
115 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
116 if item.attrs.iter().any(|a| a.check_name("automatically_derived")) {
117 debug_assert!(self.derived_item.is_none());
118 self.derived_item = Some(item.id);
122 fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
123 if let Some(id) = self.derived_item {
125 self.derived_item = None;