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