]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/large_stack_arrays.rs
Rollup merge of #89090 - cjgillot:bare-dyn, r=jackh726
[rust.git] / src / tools / clippy / clippy_lints / src / large_stack_arrays.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::snippet;
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::mir::interpret::ConstValue;
7 use rustc_middle::ty::layout::LayoutOf;
8 use rustc_middle::ty::{self, ConstKind};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for local arrays that may be too large.
14     ///
15     /// ### Why is this bad?
16     /// Large local arrays may cause stack overflow.
17     ///
18     /// ### Example
19     /// ```rust,ignore
20     /// let a = [0u32; 1_000_000];
21     /// ```
22     #[clippy::version = "1.41.0"]
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(ConstValue::Scalar(element_count)) = cst.val;
47             if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
48             if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
49             if self.maximum_allowed_size < element_count * element_size;
50             then {
51                 span_lint_and_help(
52                     cx,
53                     LARGE_STACK_ARRAYS,
54                     expr.span,
55                     &format!(
56                         "allocating a local array larger than {} bytes",
57                         self.maximum_allowed_size
58                     ),
59                     None,
60                     &format!(
61                         "consider allocating on the heap with `vec!{}.into_boxed_slice()`",
62                         snippet(cx, expr.span, "[...]")
63                     ),
64                 );
65             }
66         }
67     }
68 }