]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
Merge pull request #1841 from sanxiyn/span-lint-and-sugg
[rust.git] / clippy_lints / src / vec.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::ty::{self, Ty};
4 use rustc_const_eval::ConstContext;
5 use syntax::codemap::Span;
6 use utils::{higher, is_copy, snippet, span_lint_and_sugg};
7
8 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
9 /// be possible.
10 ///
11 /// **Why is this bad?** This is less efficient.
12 ///
13 /// **Known problems:** None.
14 ///
15 /// **Example:**
16 /// ```rust,ignore
17 /// foo(&vec![1, 2])
18 /// ```
19 declare_lint! {
20     pub USELESS_VEC,
21     Warn,
22     "useless `vec!`"
23 }
24
25 #[derive(Copy, Clone, Debug)]
26 pub struct Pass;
27
28 impl LintPass for Pass {
29     fn get_lints(&self) -> LintArray {
30         lint_array!(USELESS_VEC)
31     }
32 }
33
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
35     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
36         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
37         if_let_chain!{[
38             let ty::TyRef(_, ref ty) = cx.tables.expr_ty_adjusted(expr).sty,
39             let ty::TySlice(..) = ty.ty.sty,
40             let ExprAddrOf(_, ref addressee) = expr.node,
41             let Some(vec_args) = higher::vec_macro(cx, addressee),
42         ], {
43             check_vec_macro(cx, &vec_args, expr.span);
44         }}
45
46         // search for `for _ in vec![…]`
47         if_let_chain!{[
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.tables.expr_ty_adjusted(arg))),
51         ], {
52             // report the error around the `vec!` not inside `<std macros>:`
53             let span = arg.span.ctxt.outer().expn_info().map(|info| info.call_site).expect("unable to get call_site");
54             check_vec_macro(cx, &vec_args, span);
55         }}
56     }
57 }
58
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 ConstContext::with_tables(cx.tcx, cx.tables).eval(len).is_ok() {
63                 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
64             } else {
65                 return;
66             }
67         },
68         higher::VecArgs::Vec(args) => {
69             if let Some(last) = args.iter().last() {
70                 let span = Span {
71                     lo: args[0].span.lo,
72                     hi: last.span.hi,
73                     ctxt: args[0].span.ctxt,
74                 };
75
76                 format!("&[{}]", snippet(cx, span, "..")).into()
77             } else {
78                 "&[]".into()
79             }
80         },
81     };
82
83     span_lint_and_sugg(cx,
84                        USELESS_VEC,
85                        span,
86                        "useless use of `vec!`",
87                        "you can use a slice directly",
88                        snippet);
89 }
90
91 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
92 fn vec_type(ty: Ty) -> Ty {
93     if let ty::TyAdt(_, substs) = ty.sty {
94         substs.type_at(0)
95     } else {
96         panic!("The type of `vec!` is a not a struct?");
97     }
98 }