3 use rustc::ty::{self, Ty};
4 use rustc_const_eval::ConstContext;
5 use syntax::codemap::Span;
6 use utils::{higher, is_copy, snippet, span_lint_and_then};
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.
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 let ty::TyRef(_, ref ty) = cx.tables.expr_ty_adjusted(expr).sty,
39 let ty::TySlice(..) = ty.ty.sty,
40 let ExprAddrOf(_, ref addressee) = expr.node,
41 let Some(vec_args) = higher::vec_macro(cx, addressee),
43 check_vec_macro(cx, &vec_args, expr.span);
46 // search for `for _ in vec![…]`
48 let Some((_, arg, _)) = higher::for_loop(expr),
49 let Some(vec_args) = higher::vec_macro(cx, arg),
50 is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg))),
52 // report the error around the `vec!` not inside `<std macros>:`
53 let span = arg.span.ctxt.outer().expn_info().map(|info| info.call_site).expect("unable to get call_site");
54 check_vec_macro(cx, &vec_args, span);
59 fn check_vec_macro(cx: &LateContext, vec_args: &higher::VecArgs, span: Span) {
60 let snippet = match *vec_args {
61 higher::VecArgs::Repeat(elem, len) => {
62 if ConstContext::with_tables(cx.tcx, cx.tables).eval(len).is_ok() {
63 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
68 higher::VecArgs::Vec(args) => {
69 if let Some(last) = args.iter().last() {
73 ctxt: args[0].span.ctxt,
76 format!("&[{}]", snippet(cx, span, "..")).into()
83 span_lint_and_then(cx,
86 "useless use of `vec!`",
87 |db| { db.span_suggestion(span, "you can use a slice directly", snippet); });
90 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
91 fn vec_type(ty: Ty) -> Ty {
92 if let ty::TyAdt(_, substs) = ty.sty {
95 panic!("The type of `vec!` is a not a struct?");