]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/vec.rs
Rollup merge of #72303 - yoshuawuyts:future-poll-fn, r=dtolnay
[rust.git] / src / tools / clippy / 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_errors::Applicability;
5 use rustc_hir::{BorrowKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::{self, Ty};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::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
21     /// # fn foo(my_vec: &[u8]) {}
22     ///
23     /// // Bad
24     /// foo(&vec![1, 2]);
25     ///
26     /// // Good
27     /// foo(&[1, 2]);
28     /// ```
29     pub USELESS_VEC,
30     perf,
31     "useless `vec!`"
32 }
33
34 declare_lint_pass!(UselessVec => [USELESS_VEC]);
35
36 impl<'tcx> LateLintPass<'tcx> for UselessVec {
37     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
38         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
39         if_chain! {
40             if let ty::Ref(_, ty, _) = cx.tables().expr_ty_adjusted(expr).kind;
41             if let ty::Slice(..) = ty.kind;
42             if let ExprKind::AddrOf(BorrowKind::Ref, _, ref addressee) = expr.kind;
43             if let Some(vec_args) = higher::vec_macro(cx, addressee);
44             then {
45                 check_vec_macro(cx, &vec_args, expr.span);
46             }
47         }
48
49         // search for `for _ in vec![…]`
50         if_chain! {
51             if let Some((_, arg, _)) = higher::for_loop(expr);
52             if let Some(vec_args) = higher::vec_macro(cx, arg);
53             if is_copy(cx, vec_type(cx.tables().expr_ty_adjusted(arg)));
54             then {
55                 // report the error around the `vec!` not inside `<std macros>:`
56                 let span = arg.span
57                     .ctxt()
58                     .outer_expn_data()
59                     .call_site
60                     .ctxt()
61                     .outer_expn_data()
62                     .call_site;
63                 check_vec_macro(cx, &vec_args, span);
64             }
65         }
66     }
67 }
68
69 fn check_vec_macro<'tcx>(cx: &LateContext<'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 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
106 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
107     if let ty::Adt(_, substs) = ty.kind {
108         substs.type_at(0)
109     } else {
110         panic!("The type of `vec!` is a not a struct?");
111     }
112 }