2 use rustc::ty::TypeVariants;
4 use syntax::codemap::Span;
5 use utils::{higher, snippet, span_lint_and_then};
7 /// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
9 /// **Why is this bad?** This is less efficient.
11 /// **Known problems:** None.
23 #[derive(Copy, Clone, Debug)]
26 impl LintPass for Pass {
27 fn get_lints(&self) -> LintArray {
28 lint_array!(USELESS_VEC)
32 impl LateLintPass for Pass {
33 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
34 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
36 let TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
37 let TypeVariants::TySlice(..) = ty.ty.sty,
38 let ExprAddrOf(_, ref addressee) = expr.node,
40 check_vec_macro(cx, addressee, expr.span);
43 // search for `for _ in vec![…]`
44 if let Some((_, arg, _)) = higher::for_loop(expr) {
45 // report the error around the `vec!` not inside `<std macros>:`
46 let span = cx.sess().codemap().source_callsite(arg.span);
47 check_vec_macro(cx, arg, span);
52 fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
53 if let Some(vec_args) = higher::vec_macro(cx, vec) {
54 span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
55 let snippet = match vec_args {
56 higher::VecArgs::Repeat(elem, len) => {
57 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
59 higher::VecArgs::Vec(args) => {
60 if let Some(last) = args.iter().last() {
64 expn_id: args[0].span.expn_id,
67 format!("&[{}]", snippet(cx, span, "..")).into()
74 db.span_suggestion(span, "you can use a slice directly", snippet);