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;
8 use utils::{is_expn_of, match_path, paths, recover_for_loop, snippet, span_lint_and_then};
10 /// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
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 LateLintPass for Pass {
36 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
37 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
39 let TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
40 let TypeVariants::TySlice(..) = ty.ty.sty,
41 let ExprAddrOf(_, ref addressee) = expr.node,
43 check_vec_macro(cx, addressee, expr.span);
46 // search for `for _ in vec![…]`
47 if let Some((_, arg, _)) = recover_for_loop(expr) {
48 // report the error around the `vec!` not inside `<std macros>:`
49 let span = cx.sess().codemap().source_callsite(arg.span);
50 check_vec_macro(cx, arg, span);
55 fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
56 if let Some(vec_args) = unexpand(cx, vec) {
58 let snippet = match vec_args {
59 Args::Repeat(elem, len) => {
60 // Check that the length is a constant expression
61 if eval_const_expr_partial(cx.tcx, len, ExprTypeChecked, None).is_ok() {
62 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
68 if let Some(last) = args.iter().last() {
72 expn_id: args[0].span.expn_id,
75 format!("&[{}]", snippet(cx, span, "..")).into()
82 span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
83 db.span_suggestion(span, "you can use a slice directly", snippet);
88 /// Represent the pre-expansion arguments of a `vec!` invocation.
91 Repeat(&'a P<Expr>, &'a P<Expr>),
96 /// Returns the arguments of the `vec!` macro if this expression was expanded from `vec!`.
97 pub fn unexpand<'e>(cx: &LateContext, expr: &'e Expr) -> Option<Args<'e>> {
99 let ExprCall(ref fun, ref args) = expr.node,
100 let ExprPath(_, ref path) = fun.node,
101 is_expn_of(cx, fun.span, "vec").is_some()
103 return if match_path(path, &paths::VEC_FROM_ELEM) && args.len() == 2 {
104 // `vec![elem; size]` case
105 Some(Args::Repeat(&args[0], &args[1]))
107 else if match_path(path, &["into_vec"]) && args.len() == 1 {
108 // `vec![a, b, c]` case
110 let ExprBox(ref boxed) = args[0].node,
111 let ExprVec(ref args) = boxed.node
113 return Some(Args::Vec(&*args));