1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! Checks for needless address of operations (`&`)
13 //! This lint is **warn** by default
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::{declare_tool_lint, lint_array};
17 use if_chain::if_chain;
18 use crate::rustc::hir::{BindingAnnotation, Expr, ExprKind, MutImmutable, Pat, PatKind};
20 use crate::rustc::ty::adjustment::{Adjust, Adjustment};
21 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
22 use crate::rustc_errors::Applicability;
24 /// **What it does:** Checks for address of operations (`&`) that are going to
25 /// be dereferenced immediately by the compiler.
27 /// **Why is this bad?** Suggests that the receiver of the expression borrows
32 /// let x: &i32 = &&&&&&5;
35 /// **Known problems:** This will cause false positives in code generated by `derive`.
36 /// For instance in the following snippet:
45 /// A warning will be emitted that `&'static str` should be replaced with `&'static str`,
46 /// however there is nothing that can or should be done to fix this.
47 declare_clippy_lint! {
50 "taking a reference that is going to be automatically dereferenced"
53 #[derive(Copy, Clone)]
54 pub struct NeedlessBorrow;
56 impl LintPass for NeedlessBorrow {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(NEEDLESS_BORROW)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
63 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
67 if let ExprKind::AddrOf(MutImmutable, ref inner) = e.node {
68 if let ty::Ref(..) = cx.tables.expr_ty(inner).sty {
69 for adj3 in cx.tables.expr_adjustments(e).windows(3) {
71 kind: Adjust::Deref(_),
74 kind: Adjust::Deref(_),
77 kind: Adjust::Borrow(_),
85 "this expression borrows a reference that is immediately dereferenced \
88 if let Some(snippet) = snippet_opt(cx, inner.span) {
89 db.span_suggestion_with_applicability(
93 Applicability::MachineApplicable,
103 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
104 if in_macro(pat.span) {
108 if let PatKind::Binding(BindingAnnotation::Ref, _, name, _) = pat.node;
109 if let ty::Ref(_, tam, mutbl) = cx.tables.pat_ty(pat).sty;
110 if mutbl == MutImmutable;
111 if let ty::Ref(_, _, mutbl) = tam.sty;
112 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
113 if mutbl == MutImmutable;
119 "this pattern creates a reference to a reference",
121 if let Some(snippet) = snippet_opt(cx, name.span) {
122 db.span_suggestion_with_applicability(
126 Applicability::MachineApplicable,