|
| 1 | +//! Checks for useless borrowed references. |
| 2 | +//! |
| 3 | +//! This lint is **warn** by default |
| 4 | +
|
| 5 | +use rustc::lint::*; |
| 6 | +use rustc::hir::{MutImmutable, Pat, PatKind, BindingMode}; |
| 7 | +use rustc::ty; |
| 8 | +use utils::{span_lint, in_macro}; |
| 9 | + |
| 10 | +/// **What it does:** Checks for useless borrowed references. |
| 11 | +/// |
| 12 | +/// **Why is this bad?** It is completely useless and make the code look more complex than it actually is. |
| 13 | +/// |
| 14 | +/// **Known problems:** None. |
| 15 | +/// |
| 16 | +/// **Example:** |
| 17 | +/// ```rust |
| 18 | +/// let mut v = Vec::<String>::new(); |
| 19 | +/// let _ = v.iter_mut().filter(|&ref a| a.is_empty()); |
| 20 | +/// ``` |
| 21 | +/// This clojure takes a reference on something that has been matched as a reference and de-referenced. |
| 22 | +/// As such, it could just be |a| a.is_empty() |
| 23 | +declare_lint! { |
| 24 | + pub NEEDLESS_BORROWED_REFERENCE, |
| 25 | + Warn, |
| 26 | + "taking a needless borrowed reference" |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Copy, Clone)] |
| 30 | +pub struct NeedlessBorrowedRef; |
| 31 | + |
| 32 | +impl LintPass for NeedlessBorrowedRef { |
| 33 | + fn get_lints(&self) -> LintArray { |
| 34 | + lint_array!(NEEDLESS_BORROWED_REFERENCE) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef { |
| 39 | + fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) { |
| 40 | + if in_macro(pat.span) { |
| 41 | + // OK, simple enough, lints doesn't check in macro. |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + if_let_chain! {[ |
| 46 | + // Pat is a pattern whose node |
| 47 | + // is a binding which "involves" a immutable reference... |
| 48 | + let PatKind::Binding(BindingMode::BindByRef(MutImmutable), ..) = pat.node, |
| 49 | + // Pattern's type is a reference. Get the type and mutability of referenced value (tam: TypeAndMut). |
| 50 | + let ty::TyRef(_, ref tam) = cx.tables.pat_ty(pat).sty, |
| 51 | + // This is an immutable reference. |
| 52 | + tam.mutbl == MutImmutable, |
| 53 | + ], { |
| 54 | + span_lint(cx, NEEDLESS_BORROWED_REFERENCE, pat.span, "this pattern takes a reference on something that is being de-referenced") |
| 55 | + }} |
| 56 | + } |
| 57 | +} |
| 58 | + |
0 commit comments