3 use rustc::ty::{self, Ty};
4 use syntax::codemap::Span;
5 use utils::{higher, is_copy, snippet, span_lint_and_sugg};
8 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
11 /// **Why is this bad?** This is less efficient.
13 /// **Known problems:** None.
19 declare_clippy_lint! {
25 #[derive(Copy, Clone, Debug)]
28 impl LintPass for Pass {
29 fn get_lints(&self) -> LintArray {
30 lint_array!(USELESS_VEC)
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
35 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
36 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
38 if let ty::TyRef(_, ty, _) = cx.tables.expr_ty_adjusted(expr).sty;
39 if let ty::TySlice(..) = ty.sty;
40 if let ExprAddrOf(_, ref addressee) = expr.node;
41 if let Some(vec_args) = higher::vec_macro(cx, addressee);
43 check_vec_macro(cx, &vec_args, expr.span);
47 // search for `for _ in vec![…]`
49 if let Some((_, arg, _)) = higher::for_loop(expr);
50 if let Some(vec_args) = higher::vec_macro(cx, arg);
51 if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
53 // report the error around the `vec!` not inside `<std macros>:`
58 .map(|info| info.call_site)
59 .expect("unable to get call_site");
60 check_vec_macro(cx, &vec_args, span);
66 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
67 let snippet = match *vec_args {
68 higher::VecArgs::Repeat(elem, len) => {
69 if constant(cx, len).is_some() {
70 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len"))
75 higher::VecArgs::Vec(args) => if let Some(last) = args.iter().last() {
76 let span = args[0].span.to(last.span);
78 format!("&[{}]", snippet(cx, span, ".."))
88 "useless use of `vec!`",
89 "you can use a slice directly",
94 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
95 fn vec_type(ty: Ty) -> Ty {
96 if let ty::TyAdt(_, substs) = ty.sty {
99 panic!("The type of `vec!` is a not a struct?");