2 use rustc::ty::TypeVariants;
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, 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 TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
39 let TypeVariants::TySlice(..) = ty.ty.sty,
40 let ExprAddrOf(_, ref addressee) = expr.node,
42 check_vec_macro(cx, addressee, expr.span);
45 // search for `for _ in vec![…]`
46 if let Some((_, arg, _)) = higher::for_loop(expr) {
47 // report the error around the `vec!` not inside `<std macros>:`
48 let span = cx.sess().codemap().source_callsite(arg.span);
49 check_vec_macro(cx, arg, span);
54 fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
55 if let Some(vec_args) = higher::vec_macro(cx, vec) {
56 let snippet = match vec_args {
57 higher::VecArgs::Repeat(elem, len) => {
58 if eval_const_expr_partial(cx.tcx, len, ExprTypeChecked, None).is_ok() {
59 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
64 higher::VecArgs::Vec(args) => {
65 if let Some(last) = args.iter().last() {
69 expn_id: args[0].span.expn_id,
72 format!("&[{}]", snippet(cx, span, "..")).into()
79 span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
80 db.span_suggestion(span, "you can use a slice directly", snippet);