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