|
| 1 | +use rustc::hir::Expr; |
| 2 | +use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass}; |
| 3 | +use rustc::ty; |
| 4 | +use utils::{match_type, span_lint_and_sugg, walk_ptrs_ty}; |
| 5 | +use utils::paths; |
| 6 | + |
| 7 | +/// **What it does:** |
| 8 | +/// Checks for usage of `Rc<String>` or `Rc<Vec<T>>`. |
| 9 | +/// |
| 10 | +/// **Why is this bad?** |
| 11 | +/// Using a `Rc<str>` or `Rc<[T]>` is more efficient and easy to construct with |
| 12 | +/// `into()`. |
| 13 | +/// |
| 14 | +/// **Known problems:** |
| 15 | +/// None. |
| 16 | +/// |
| 17 | +/// **Example:** |
| 18 | +/// |
| 19 | +/// ```rust |
| 20 | +/// use std::rc::Rc; |
| 21 | +/// |
| 22 | +/// // Bad |
| 23 | +/// let bad_ref: Rc<Vec<usize>> = Rc::new(vec!(1, 2, 3)); |
| 24 | +/// |
| 25 | +/// // Good |
| 26 | +/// let good_ref: Rc<[usize]> = Rc::new(vec!(1, 2, 3).into()); |
| 27 | +/// ``` |
| 28 | +declare_clippy_lint! { |
| 29 | + pub USE_SHARED_FROM_SLICE, |
| 30 | + nursery, |
| 31 | + "use `into()` to construct `Rc` from slice" |
| 32 | +} |
| 33 | + |
| 34 | +#[derive(Copy, Clone, Debug)] |
| 35 | +pub struct Pass; |
| 36 | + |
| 37 | +impl LintPass for Pass { |
| 38 | + fn get_lints(&self) -> LintArray { |
| 39 | + lint_array!(USE_SHARED_FROM_SLICE) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl <'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { |
| 44 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { |
| 45 | + let expr_ty = walk_ptrs_ty(cx.tables.expr_ty(expr)); |
| 46 | + |
| 47 | + // Check for expressions with the type `Rc<Vec<T>>`. |
| 48 | + if_chain! { |
| 49 | + if let ty::TyAdt(_, subst) = expr_ty.sty; |
| 50 | + if match_type(cx, expr_ty, &paths::RC); |
| 51 | + if match_type(cx, subst.type_at(1), &paths::VEC); |
| 52 | + then { |
| 53 | + span_lint_and_sugg( |
| 54 | + cx, |
| 55 | + USE_SHARED_FROM_SLICE, |
| 56 | + expr.span, |
| 57 | + "constructing reference-counted type from vec", |
| 58 | + "consider using `into()`", |
| 59 | + format!("TODO"), |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // TODO |
| 65 | + // Check for expressions with the type `Rc<String>`. |
| 66 | + // Check for expressions with the type `Arc<String>`. |
| 67 | + // Check for expressions with the type `Arc<Vec<T>>`. |
| 68 | + } |
| 69 | +} |
0 commit comments