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