]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/large_stack_arrays.rs
Auto merge of #76499 - guswynn:priv_des, r=petrochenkov
[rust.git] / src / tools / clippy / clippy_lints / src / large_stack_arrays.rs
1 use rustc_hir::{Expr, ExprKind};
2 use rustc_lint::{LateContext, LateLintPass};
3 use rustc_middle::mir::interpret::ConstValue;
4 use rustc_middle::ty::{self, ConstKind};
5 use rustc_session::{declare_tool_lint, impl_lint_pass};
6
7 use if_chain::if_chain;
8
9 use crate::rustc_target::abi::LayoutOf;
10 use crate::utils::{snippet, span_lint_and_help};
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for local arrays that may be too large.
14     ///
15     /// **Why is this bad?** Large local arrays may cause stack overflow.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust,ignore
21     /// let a = [0u32; 1_000_000];
22     /// ```
23     pub LARGE_STACK_ARRAYS,
24     pedantic,
25     "allocating large arrays on stack may cause stack overflow"
26 }
27
28 pub struct LargeStackArrays {
29     maximum_allowed_size: u64,
30 }
31
32 impl LargeStackArrays {
33     #[must_use]
34     pub fn new(maximum_allowed_size: u64) -> Self {
35         Self { maximum_allowed_size }
36     }
37 }
38
39 impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]);
40
41 impl<'tcx> LateLintPass<'tcx> for LargeStackArrays {
42     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
43         if_chain! {
44             if let ExprKind::Repeat(_, _) = expr.kind;
45             if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind();
46             if let ConstKind::Value(val) = cst.val;
47             if let ConstValue::Scalar(element_count) = val;
48             if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
49             if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
50             if self.maximum_allowed_size < element_count * element_size;
51             then {
52                 span_lint_and_help(
53                     cx,
54                     LARGE_STACK_ARRAYS,
55                     expr.span,
56                     &format!(
57                         "allocating a local array larger than {} bytes",
58                         self.maximum_allowed_size
59                     ),
60                     None,
61                     &format!(
62                         "consider allocating on the heap with `vec!{}.into_boxed_slice()`",
63                         snippet(cx, expr.span, "[...]")
64                     ),
65                 );
66             }
67         }
68     }
69 }