4 use rustc_const_eval::EvalHint::ExprTypeChecked;
5 use rustc_const_eval::ConstContext;
6 use syntax::codemap::Span;
7 use utils::{higher, is_copy, snippet, span_lint_and_then};
9 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
12 /// **Why is this bad?** This is less efficient.
14 /// **Known problems:** None.
26 #[derive(Copy, Clone, Debug)]
29 impl LintPass for Pass {
30 fn get_lints(&self) -> LintArray {
31 lint_array!(USELESS_VEC)
35 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
36 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
37 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
39 let ty::TypeVariants::TyRef(_, ref ty) = cx.tables.expr_ty_adjusted(expr).sty,
40 let ty::TypeVariants::TySlice(..) = ty.ty.sty,
41 let ExprAddrOf(_, ref addressee) = expr.node,
42 let Some(vec_args) = higher::vec_macro(cx, addressee),
44 check_vec_macro(cx, &vec_args, expr.span);
47 // search for `for _ in vec![…]`
49 let Some((_, arg, _)) = higher::for_loop(expr),
50 let Some(vec_args) = higher::vec_macro(cx, arg),
51 is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)), cx.tcx.hir.get_parent(expr.id)),
53 // report the error around the `vec!` not inside `<std macros>:`
54 let span = cx.sess().codemap().source_callsite(arg.span);
55 check_vec_macro(cx, &vec_args, span);
60 fn check_vec_macro(cx: &LateContext, vec_args: &higher::VecArgs, span: Span) {
61 let snippet = match *vec_args {
62 higher::VecArgs::Repeat(elem, len) => {
63 if ConstContext::with_tables(cx.tcx, cx.tables).eval(len, ExprTypeChecked).is_ok() {
64 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
69 higher::VecArgs::Vec(args) => {
70 if let Some(last) = args.iter().last() {
74 expn_id: args[0].span.expn_id,
77 format!("&[{}]", snippet(cx, span, "..")).into()
84 span_lint_and_then(cx,
87 "useless use of `vec!`",
88 |db| { db.span_suggestion(span, "you can use a slice directly", snippet); });
91 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
92 fn vec_type(ty: ty::Ty) -> ty::Ty {
93 if let ty::TyAdt(_, substs) = ty.sty {
96 panic!("The type of `vec!` is a not a struct?");