]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
8e09f9341c2dffb74b6523d0cc367a17e159a8c6
[rust.git] / clippy_lints / src / vec.rs
1 use rustc::lint::*;
2 use rustc::ty::TypeVariants;
3 use rustc::hir::*;
4 use syntax::codemap::Span;
5 use utils::{higher, snippet, span_lint_and_then};
6
7 /// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
8 ///
9 /// **Why is this bad?** This is less efficient.
10 ///
11 /// **Known problems:** None.
12 ///
13 /// **Example:**
14 /// ```rust,ignore
15 /// foo(&vec![1, 2])
16 /// ```
17 declare_lint! {
18     pub USELESS_VEC,
19     Warn,
20     "useless `vec!`"
21 }
22
23 #[derive(Copy, Clone, Debug)]
24 pub struct Pass;
25
26 impl LintPass for Pass {
27     fn get_lints(&self) -> LintArray {
28         lint_array!(USELESS_VEC)
29     }
30 }
31
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 `&[_]`
35         if_let_chain!{[
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,
39         ], {
40             check_vec_macro(cx, addressee, expr.span);
41         }}
42
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);
48         }
49     }
50 }
51
52 fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
53     if let Some(vec_args) = higher::vec_macro(cx, vec) {
54         let snippet = match vec_args {
55             higher::VecArgs::Repeat(elem, len) => {
56                 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
57             }
58             higher::VecArgs::Vec(args) => {
59                 if let Some(last) = args.iter().last() {
60                     let span = Span {
61                         lo: args[0].span.lo,
62                         hi: last.span.hi,
63                         expn_id: args[0].span.expn_id,
64                     };
65
66                     format!("&[{}]", snippet(cx, span, "..")).into()
67                 } else {
68                     "&[]".into()
69                 }
70             }
71         };
72
73         span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
74             db.span_suggestion(span, "you can use a slice directly", snippet);
75         });
76     }
77 }
78