]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/large_const_arrays.rs
bump version to 1.80.1+dfsg1-1~bpo12+pve1
[rustc.git] / src / tools / clippy / clippy_lints / src / large_const_arrays.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use rustc_errors::Applicability;
3 use rustc_hir::{Item, ItemKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::layout::LayoutOf;
6 use rustc_middle::ty::{self, ConstKind};
7 use rustc_session::impl_lint_pass;
8 use rustc_span::{BytePos, Pos, Span};
9
10 declare_clippy_lint! {
11 /// ### What it does
12 /// Checks for large `const` arrays that should
13 /// be defined as `static` instead.
14 ///
15 /// ### Why is this bad?
16 /// Performance: const variables are inlined upon use.
17 /// Static items result in only one instance and has a fixed location in memory.
18 ///
19 /// ### Example
20 /// ```rust,ignore
21 /// pub const a = [0u32; 1_000_000];
22 /// ```
23 ///
24 /// Use instead:
25 /// ```rust,ignore
26 /// pub static a = [0u32; 1_000_000];
27 /// ```
28 #[clippy::version = "1.44.0"]
29 pub LARGE_CONST_ARRAYS,
30 perf,
31 "large non-scalar const array may cause performance overhead"
32 }
33
34 pub struct LargeConstArrays {
35 maximum_allowed_size: u128,
36 }
37
38 impl LargeConstArrays {
39 #[must_use]
40 pub fn new(maximum_allowed_size: u128) -> Self {
41 Self { maximum_allowed_size }
42 }
43 }
44
45 impl_lint_pass!(LargeConstArrays => [LARGE_CONST_ARRAYS]);
46
47 impl<'tcx> LateLintPass<'tcx> for LargeConstArrays {
48 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
49 if !item.span.from_expansion()
50 && let ItemKind::Const(_, generics, _) = &item.kind
51 // Since static items may not have generics, skip generic const items.
52 // FIXME(generic_const_items): I don't think checking `generics.hwcp` suffices as it
53 // doesn't account for empty where-clauses that only consist of keyword `where` IINM.
54 && generics.params.is_empty() && !generics.has_where_clause_predicates
55 && let ty = cx.tcx.type_of(item.owner_id).instantiate_identity()
56 && let ty::Array(element_type, cst) = ty.kind()
57 && let ConstKind::Value(ty::ValTree::Leaf(element_count)) = cst.kind()
58 && let Ok(element_count) = element_count.try_to_target_usize(cx.tcx)
59 && let Ok(element_size) = cx.layout_of(*element_type).map(|l| l.size.bytes())
60 && self.maximum_allowed_size < u128::from(element_count) * u128::from(element_size)
61 {
62 let hi_pos = item.ident.span.lo() - BytePos::from_usize(1);
63 let sugg_span = Span::new(
64 hi_pos - BytePos::from_usize("const".len()),
65 hi_pos,
66 item.span.ctxt(),
67 item.span.parent(),
68 );
69 span_lint_and_then(
70 cx,
71 LARGE_CONST_ARRAYS,
72 item.span,
73 "large array defined as const",
74 |diag| {
75 diag.span_suggestion(
76 sugg_span,
77 "make this a static item",
78 "static",
79 Applicability::MachineApplicable,
80 );
81 },
82 );
83 }
84 }
85 }