]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
Merge remote-tracking branch 'origin/rust-1.31.0' into HEAD
[rust.git] / clippy_lints / src / vec.rs
1 use crate::consts::constant;
2 use crate::utils::{higher, is_copy, snippet_with_applicability, span_lint_and_sugg};
3 use if_chain::if_chain;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty::{self, Ty};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
13     /// be possible.
14     ///
15     /// **Why is this bad?** This is less efficient.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust,ignore
21     /// foo(&vec![1, 2])
22     /// ```
23     pub USELESS_VEC,
24     perf,
25     "useless `vec!`"
26 }
27
28 declare_lint_pass!(UselessVec => [USELESS_VEC]);
29
30 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec {
31     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
32         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
33         if_chain! {
34             if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).sty;
35             if let ty::Slice(..) = ty.sty;
36             if let ExprKind::AddrOf(_, ref addressee) = expr.node;
37             if let Some(vec_args) = higher::vec_macro(cx, addressee);
38             then {
39                 check_vec_macro(cx, &vec_args, expr.span);
40             }
41         }
42
43         // search for `for _ in vec![…]`
44         if_chain! {
45             if let Some((_, arg, _)) = higher::for_loop(expr);
46             if let Some(vec_args) = higher::vec_macro(cx, arg);
47             if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
48             then {
49                 // report the error around the `vec!` not inside `<std macros>:`
50                 let span = arg.span
51                     .ctxt()
52                     .outer()
53                     .expn_info()
54                     .map(|info| info.call_site)
55                     .expect("unable to get call_site")
56                     .ctxt()
57                     .outer()
58                     .expn_info()
59                     .map(|info| info.call_site)
60                     .expect("unable to get call_site");
61                 check_vec_macro(cx, &vec_args, span);
62             }
63         }
64     }
65 }
66
67 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
68     let mut applicability = Applicability::MachineApplicable;
69     let snippet = match *vec_args {
70         higher::VecArgs::Repeat(elem, len) => {
71             if constant(cx, cx.tables, len).is_some() {
72                 format!(
73                     "&[{}; {}]",
74                     snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
75                     snippet_with_applicability(cx, len.span, "len", &mut applicability)
76                 )
77             } else {
78                 return;
79             }
80         },
81         higher::VecArgs::Vec(args) => {
82             if let Some(last) = args.iter().last() {
83                 let span = args[0].span.to(last.span);
84
85                 format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
86             } else {
87                 "&[]".into()
88             }
89         },
90     };
91
92     span_lint_and_sugg(
93         cx,
94         USELESS_VEC,
95         span,
96         "useless use of `vec!`",
97         "you can use a slice directly",
98         snippet,
99         applicability,
100     );
101 }
102
103 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
104 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
105     if let ty::Adt(_, substs) = ty.sty {
106         substs.type_at(0)
107     } else {
108         panic!("The type of `vec!` is a not a struct?");
109     }
110 }