1 //! Checks for needless address of operations (`&`)
3 //! This lint is **warn** by default
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
8 use rustc::hir::{BindingAnnotation, Expr, ExprKind, MutImmutable, Pat, PatKind};
10 use rustc::ty::adjustment::{Adjust, Adjustment};
11 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
13 /// **What it does:** Checks for address of operations (`&`) that are going to
14 /// be dereferenced immediately by the compiler.
16 /// **Why is this bad?** Suggests that the receiver of the expression borrows
21 /// let x: &i32 = &&&&&&5;
24 /// **Known problems:** This will cause false positives in code generated by `derive`.
25 /// For instance in the following snippet:
34 /// A warning will be emitted that `&'static str` should be replaced with `&'static str`,
35 /// however there is nothing that can or should be done to fix this.
36 declare_clippy_lint! {
39 "taking a reference that is going to be automatically dereferenced"
42 #[derive(Copy, Clone)]
43 pub struct NeedlessBorrow;
45 impl LintPass for NeedlessBorrow {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(NEEDLESS_BORROW)
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
52 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
56 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
57 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
58 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
60 kind: Adjust::Deref(_),
63 kind: Adjust::Deref(_),
66 kind: Adjust::Borrow(_),
74 "this expression borrows a reference that is immediately dereferenced \
77 if let Some(snippet) = snippet_opt(cx, inner.span) {
78 db.span_suggestion(e.span, "change this to", snippet);
87 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
88 if in_macro(pat.span) {
92 if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
93 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
94 if mutbl == MutImmutable;
95 if let ty::Ref(_, _, mutbl) = tam.sty;
96 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
97 if mutbl == MutImmutable;
103 "this pattern creates a reference to a reference",
105 if let Some(snippet) = snippet_opt(cx, name.span) {
106 db.span_suggestion(pat.span, "change this to", snippet);