]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
Check for constant expression in useless_vec lint
[rust.git] / clippy_lints / src / vec.rs
1 use rustc::lint::*;
2 use rustc::ty::TypeVariants;
3 use rustc::hir::*;
4 use rustc_const_eval::EvalHint::ExprTypeChecked;
5 use rustc_const_eval::eval_const_expr_partial;
6 use syntax::codemap::Span;
7 use syntax::ptr::P;
8 use utils::{is_expn_of, match_path, paths, recover_for_loop, snippet, span_lint_and_then};
9
10 /// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would 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 LateLintPass for Pass {
36     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
37         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
38         if_let_chain!{[
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,
42         ], {
43             check_vec_macro(cx, addressee, expr.span);
44         }}
45
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);
51         }
52     }
53 }
54
55 fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
56     if let Some(vec_args) = unexpand(cx, vec) {
57
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()
63                 } else {
64                     return;
65                 }
66             }
67             Args::Vec(args) => {
68                 if let Some(last) = args.iter().last() {
69                     let span = Span {
70                         lo: args[0].span.lo,
71                         hi: last.span.hi,
72                         expn_id: args[0].span.expn_id,
73                     };
74
75                     format!("&[{}]", snippet(cx, span, "..")).into()
76                 } else {
77                     "&[]".into()
78                 }
79             }
80         };
81
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);
84         });
85     }
86 }
87
88 /// Represent the pre-expansion arguments of a `vec!` invocation.
89 pub enum Args<'a> {
90     /// `vec![elem; len]`
91     Repeat(&'a P<Expr>, &'a P<Expr>),
92     /// `vec![a, b, c]`
93     Vec(&'a [P<Expr>]),
94 }
95
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>> {
98     if_let_chain!{[
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()
102     ], {
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]))
106         }
107         else if match_path(path, &["into_vec"]) && args.len() == 1 {
108             // `vec![a, b, c]` case
109             if_let_chain!{[
110                 let ExprBox(ref boxed) = args[0].node,
111                 let ExprVec(ref args) = boxed.node
112             ], {
113                 return Some(Args::Vec(&*args));
114             }}
115
116             None
117         }
118         else {
119             None
120         };
121     }}
122
123     None
124 }