]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[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_tool_lint, lint_array};
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 #[derive(Copy, Clone, Debug)]
29 pub struct Pass;
30
31 impl LintPass for Pass {
32     fn get_lints(&self) -> LintArray {
33         lint_array!(USELESS_VEC)
34     }
35
36     fn name(&self) -> &'static str {
37         "UselessVec"
38     }
39 }
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
42     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
43         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
44         if_chain! {
45             if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).sty;
46             if let ty::Slice(..) = ty.sty;
47             if let ExprKind::AddrOf(_, ref addressee) = expr.node;
48             if let Some(vec_args) = higher::vec_macro(cx, addressee);
49             then {
50                 check_vec_macro(cx, &vec_args, expr.span);
51             }
52         }
53
54         // search for `for _ in vec![…]`
55         if_chain! {
56             if let Some((_, arg, _)) = higher::for_loop(expr);
57             if let Some(vec_args) = higher::vec_macro(cx, arg);
58             if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
59             then {
60                 // report the error around the `vec!` not inside `<std macros>:`
61                 let span = arg.span
62                     .ctxt()
63                     .outer()
64                     .expn_info()
65                     .map(|info| info.call_site)
66                     .expect("unable to get call_site")
67                     .ctxt()
68                     .outer()
69                     .expn_info()
70                     .map(|info| info.call_site)
71                     .expect("unable to get call_site");
72                 check_vec_macro(cx, &vec_args, span);
73             }
74         }
75     }
76 }
77
78 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
79     let mut applicability = Applicability::MachineApplicable;
80     let snippet = match *vec_args {
81         higher::VecArgs::Repeat(elem, len) => {
82             if constant(cx, cx.tables, len).is_some() {
83                 format!(
84                     "&[{}; {}]",
85                     snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
86                     snippet_with_applicability(cx, len.span, "len", &mut applicability)
87                 )
88             } else {
89                 return;
90             }
91         },
92         higher::VecArgs::Vec(args) => {
93             if let Some(last) = args.iter().last() {
94                 let span = args[0].span.to(last.span);
95
96                 format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
97             } else {
98                 "&[]".into()
99             }
100         },
101     };
102
103     span_lint_and_sugg(
104         cx,
105         USELESS_VEC,
106         span,
107         "useless use of `vec!`",
108         "you can use a slice directly",
109         snippet,
110         applicability,
111     );
112 }
113
114 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
115 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
116     if let ty::Adt(_, substs) = ty.sty {
117         substs.type_at(0)
118     } else {
119         panic!("The type of `vec!` is a not a struct?");
120     }
121 }