1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
5 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use crate::rustc::{declare_tool_lint, lint_array};
7 use if_chain::if_chain;
8 use crate::rustc::hir::{BindingAnnotation, Expr, ExprKind, MutImmutable, Pat, PatKind};
10 use crate::rustc::ty::adjustment::{Adjust, Adjustment};
11 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
12 use crate::rustc_errors::Applicability;
14 /// **What it does:** Checks for address of operations (`&`) that are going to
15 /// be dereferenced immediately by the compiler.
17 /// **Why is this bad?** Suggests that the receiver of the expression borrows
22 /// let x: &i32 = &&&&&&5;
25 /// **Known problems:** This will cause false positives in code generated by `derive`.
26 /// For instance in the following snippet:
35 /// A warning will be emitted that `&'static str` should be replaced with `&'static str`,
36 /// however there is nothing that can or should be done to fix this.
37 declare_clippy_lint! {
40 "taking a reference that is going to be automatically dereferenced"
43 #[derive(Copy, Clone)]
44 pub struct NeedlessBorrow;
46 impl LintPass for NeedlessBorrow {
47 fn get_lints(&self) -> LintArray {
48 lint_array!(NEEDLESS_BORROW)
52 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
53 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
57 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
58 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
59 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
61 kind: Adjust::Deref(_),
64 kind: Adjust::Deref(_),
67 kind: Adjust::Borrow(_),
75 "this expression borrows a reference that is immediately dereferenced \
78 if let Some(snippet) = snippet_opt(cx, inner.span) {
79 db.span_suggestion_with_applicability(
83 Applicability::MachineApplicable,
93 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
94 if in_macro(pat.span) {
98 if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
99 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
100 if mutbl == MutImmutable;
101 if let ty::Ref(_, _, mutbl) = tam.sty;
102 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
103 if mutbl == MutImmutable;
109 "this pattern creates a reference to a reference",
111 if let Some(snippet) = snippet_opt(cx, name.span) {
112 db.span_suggestion_with_applicability(
116 Applicability::MachineApplicable,