1 //! Checks for useless borrowed references.
3 //! This lint is **warn** by default
7 use rustc::hir::{MutImmutable, Pat, PatKind, BindingAnnotation};
9 use rustc::hir::{MutImmutable, Pat, PatKind};
10 >>>>>>> e30bf721... Improve needless_borrowed_ref and add suggestion to it.
12 use utils::{span_lint_and_then, in_macro, snippet};
13 use syntax_pos::{Span, BytePos};
15 /// **What it does:** Checks for useless borrowed references.
17 /// **Why is this bad?** It is completely useless and make the code look more
21 /// **Known problems:** None.
25 /// let mut v = Vec::<String>::new();
26 /// let _ = v.iter_mut().filter(|&ref a| a.is_empty());
28 /// This clojure takes a reference on something that has been matched as a
31 /// As such, it could just be |a| a.is_empty()
33 pub NEEDLESS_BORROWED_REFERENCE,
35 "taking a needless borrowed reference"
38 #[derive(Copy, Clone)]
39 pub struct NeedlessBorrowedRef;
41 impl LintPass for NeedlessBorrowedRef {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(NEEDLESS_BORROWED_REFERENCE)
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef {
48 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
49 if in_macro(pat.span) {
50 // OK, simple enough, lints doesn't check in macro.
55 // Pat is a pattern whose node
56 // is a binding which "involves" an immutable reference...
57 let PatKind::Binding(BindingAnnotation::Ref, ..) = pat.node,
58 // Pattern's type is a reference. Get the type and mutability of referenced value (tam: TypeAndMut).
59 let ty::TyRef(_, ref tam) = cx.tables.pat_ty(pat).sty,
60 // Only lint immutable refs, because `&mut ref T` may be useful.
61 let PatKind::Ref(ref sub_pat, MutImmutable) = pat.node,
63 // Check sub_pat got a 'ref' keyword.
64 let ty::TyRef(_, _) = cx.tables.pat_ty(sub_pat).sty,
66 let part_to_keep = Span{ lo: pat.span.lo + BytePos(5), hi: pat.span.hi, ctxt: pat.span.ctxt };
67 span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span,
68 "this pattern takes a reference on something that is being de-referenced",
70 let hint = snippet(cx, part_to_keep, "..").into_owned();
71 db.span_suggestion(pat.span, "try removing the `&ref` part and just keep", hint);