4 use rustc_const_eval::EvalHint::ExprTypeChecked;
5 use rustc_const_eval::eval_const_expr_partial;
6 use syntax::codemap::Span;
7 use utils::{higher, is_copy, snippet, span_lint_and_then};
9 /// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
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 LateLintPass for Pass {
35 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
36 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
38 let ty::TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
39 let ty::TypeVariants::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.tcx.expr_ty_adjusted(arg)), cx.tcx.map.get_parent(expr.id)),
52 // report the error around the `vec!` not inside `<std macros>:`
53 let span = cx.sess().codemap().source_callsite(arg.span);
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 eval_const_expr_partial(cx.tcx, len, ExprTypeChecked, None).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 expn_id: args[0].span.expn_id,
76 format!("&[{}]", snippet(cx, span, "..")).into()
83 span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
84 db.span_suggestion(span, "you can use a slice directly", snippet);
88 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
89 fn vec_type(ty: ty::Ty) -> ty::Ty {
90 if let ty::TyStruct(_, substs) = ty.sty {
91 substs.types.get(ty::subst::ParamSpace::TypeSpace, 0)
93 panic!("The type of `vec!` is a not a struct?");