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.
10 //! Checks for useless borrowed references.
12 //! This lint is **warn** by default
14 use crate::rustc::hir::{BindingAnnotation, MutImmutable, Pat, PatKind};
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::{declare_tool_lint, lint_array};
17 use crate::rustc_errors::Applicability;
18 use crate::utils::{in_macro, snippet, span_lint_and_then};
19 use if_chain::if_chain;
21 /// **What it does:** Checks for useless borrowed references.
23 /// **Why is this bad?** It is mostly useless and make the code look more
27 /// **Known problems:** It seems that the `&ref` pattern is sometimes useful.
28 /// For instance in the following snippet:
35 /// fn foo(a: &Animal, b: &Animal) {
37 /// (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime
39 /// (&Animal::Dog(ref c), &Animal::Dog(_)) => ()
43 /// There is a lifetime mismatch error for `k` (indeed a and b have distinct
45 /// This can be fixed by using the `&ref` pattern.
46 /// However, the code can also be fixed by much cleaner ways
50 /// let mut v = Vec::<String>::new();
51 /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
53 /// This closure takes a reference on something that has been matched as a
56 /// As such, it could just be |a| a.is_empty()
57 declare_clippy_lint! {
58 pub NEEDLESS_BORROWED_REFERENCE,
60 "taking a needless borrowed reference"
63 #[derive(Copy, Clone)]
64 pub struct NeedlessBorrowedRef;
66 impl LintPass for NeedlessBorrowedRef {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(NEEDLESS_BORROWED_REFERENCE)
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
73 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
74 if in_macro(pat.span) {
75 // OK, simple enough, lints doesn't check in macro.
80 // Only lint immutable refs, because `&mut ref T` may be useful.
81 if let PatKind::Ref(ref sub_pat, MutImmutable) = pat.node;
83 // Check sub_pat got a `ref` keyword (excluding `ref mut`).
84 if let PatKind::Binding(BindingAnnotation::Ref, _, spanned_name, ..) = sub_pat.node;
86 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
87 "this pattern takes a reference on something that is being de-referenced",
89 let hint = snippet(cx, spanned_name.span, "..").into_owned();
90 db.span_suggestion_with_applicability(
92 "try removing the `&ref` part and just keep",
94 Applicability::MachineApplicable, // snippet