]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/vec.rs
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
[rust.git] / src / tools / clippy / clippy_lints / src / vec.rs
1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::higher;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::ty::is_copy;
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::layout::LayoutOf;
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::source_map::Span;
14
15 #[allow(clippy::module_name_repetitions)]
16 #[derive(Copy, Clone)]
17 pub struct UselessVec {
18     pub too_large_for_stack: u64,
19 }
20
21 declare_clippy_lint! {
22     /// ### What it does
23     /// Checks for usage of `&vec![..]` when using `&[..]` would
24     /// be possible.
25     ///
26     /// ### Why is this bad?
27     /// This is less efficient.
28     ///
29     /// ### Example
30     /// ```rust
31     /// # fn foo(my_vec: &[u8]) {}
32     ///
33     /// // Bad
34     /// foo(&vec![1, 2]);
35     ///
36     /// // Good
37     /// foo(&[1, 2]);
38     /// ```
39     pub USELESS_VEC,
40     perf,
41     "useless `vec!`"
42 }
43
44 impl_lint_pass!(UselessVec => [USELESS_VEC]);
45
46 impl<'tcx> LateLintPass<'tcx> for UselessVec {
47     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
48         // search for `&vec![_]` expressions where the adjusted type is `&[_]`
49         if_chain! {
50             if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty_adjusted(expr).kind();
51             if let ty::Slice(..) = ty.kind();
52             if let ExprKind::AddrOf(BorrowKind::Ref, mutability, addressee) = expr.kind;
53             if let Some(vec_args) = higher::VecArgs::hir(cx, addressee);
54             then {
55                 self.check_vec_macro(cx, &vec_args, mutability, expr.span);
56             }
57         }
58
59         // search for `for _ in vec![…]`
60         if_chain! {
61             if let Some(higher::ForLoop { arg, .. }) = higher::ForLoop::hir(expr);
62             if let Some(vec_args) = higher::VecArgs::hir(cx, arg);
63             if is_copy(cx, vec_type(cx.typeck_results().expr_ty_adjusted(arg)));
64             then {
65                 // report the error around the `vec!` not inside `<std macros>:`
66                 let span = arg.span.ctxt().outer_expn_data().call_site;
67                 self.check_vec_macro(cx, &vec_args, Mutability::Not, span);
68             }
69         }
70     }
71 }
72
73 impl UselessVec {
74     fn check_vec_macro<'tcx>(
75         self,
76         cx: &LateContext<'tcx>,
77         vec_args: &higher::VecArgs<'tcx>,
78         mutability: Mutability,
79         span: Span,
80     ) {
81         let mut applicability = Applicability::MachineApplicable;
82         let snippet = match *vec_args {
83             higher::VecArgs::Repeat(elem, len) => {
84                 if let Some((Constant::Int(len_constant), _)) = constant(cx, cx.typeck_results(), len) {
85                     #[allow(clippy::cast_possible_truncation)]
86                     if len_constant as u64 * size_of(cx, elem) > self.too_large_for_stack {
87                         return;
88                     }
89
90                     match mutability {
91                         Mutability::Mut => {
92                             format!(
93                                 "&mut [{}; {}]",
94                                 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
95                                 snippet_with_applicability(cx, len.span, "len", &mut applicability)
96                             )
97                         },
98                         Mutability::Not => {
99                             format!(
100                                 "&[{}; {}]",
101                                 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
102                                 snippet_with_applicability(cx, len.span, "len", &mut applicability)
103                             )
104                         },
105                     }
106                 } else {
107                     return;
108                 }
109             },
110             higher::VecArgs::Vec(args) => {
111                 if let Some(last) = args.iter().last() {
112                     #[allow(clippy::cast_possible_truncation)]
113                     if args.len() as u64 * size_of(cx, last) > self.too_large_for_stack {
114                         return;
115                     }
116                     let span = args[0].span.to(last.span);
117
118                     match mutability {
119                         Mutability::Mut => {
120                             format!(
121                                 "&mut [{}]",
122                                 snippet_with_applicability(cx, span, "..", &mut applicability)
123                             )
124                         },
125                         Mutability::Not => {
126                             format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
127                         },
128                     }
129                 } else {
130                     match mutability {
131                         Mutability::Mut => "&mut []".into(),
132                         Mutability::Not => "&[]".into(),
133                     }
134                 }
135             },
136         };
137
138         span_lint_and_sugg(
139             cx,
140             USELESS_VEC,
141             span,
142             "useless use of `vec!`",
143             "you can use a slice directly",
144             snippet,
145             applicability,
146         );
147     }
148 }
149
150 fn size_of(cx: &LateContext<'_>, expr: &Expr<'_>) -> u64 {
151     let ty = cx.typeck_results().expr_ty_adjusted(expr);
152     cx.layout_of(ty).map_or(0, |l| l.size.bytes())
153 }
154
155 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
156 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
157     if let ty::Adt(_, substs) = ty.kind() {
158         substs.type_at(0)
159     } else {
160         panic!("The type of `vec!` is a not a struct?");
161     }
162 }