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 useless borrowed references.
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, MutImmutable, Pat, PatKind};
19 use crate::utils::{in_macro, snippet, span_lint_and_then};
20 use crate::rustc_errors::Applicability;
22 /// **What it does:** Checks for useless borrowed references.
24 /// **Why is this bad?** It is mostly useless and make the code look more
28 /// **Known problems:** It seems that the `&ref` pattern is sometimes useful.
29 /// For instance in the following snippet:
36 /// fn foo(a: &Animal, b: &Animal) {
38 /// (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime
40 /// (&Animal::Dog(ref c), &Animal::Dog(_)) => ()
44 /// There is a lifetime mismatch error for `k` (indeed a and b have distinct
46 /// This can be fixed by using the `&ref` pattern.
47 /// However, the code can also be fixed by much cleaner ways
51 /// let mut v = Vec::<String>::new();
52 /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
54 /// This closure takes a reference on something that has been matched as a
57 /// As such, it could just be |a| a.is_empty()
58 declare_clippy_lint! {
59 pub NEEDLESS_BORROWED_REFERENCE,
61 "taking a needless borrowed reference"
64 #[derive(Copy, Clone)]
65 pub struct NeedlessBorrowedRef;
67 impl LintPass for NeedlessBorrowedRef {
68 fn get_lints(&self) -> LintArray {
69 lint_array!(NEEDLESS_BORROWED_REFERENCE)
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
74 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
75 if in_macro(pat.span) {
76 // OK, simple enough, lints doesn't check in macro.
81 // Only lint immutable refs, because `&mut ref T` may be useful.
82 if let PatKind::Ref(ref sub_pat, MutImmutable) = pat.node;
84 // Check sub_pat got a `ref` keyword (excluding `ref mut`).
85 if let PatKind::Binding(BindingAnnotation::Ref, _, spanned_name, ..) = sub_pat.node;
87 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
88 "this pattern takes a reference on something that is being de-referenced",
90 let hint = snippet(cx, spanned_name.span, "..").into_owned();
91 db.span_suggestion_with_applicability(
93 "try removing the `&ref` part and just keep",
95 Applicability::MachineApplicable, // snippet