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};
11 declare_clippy_lint! {
13 /// Checks for local arrays that may be too large.
15 /// ### Why is this bad?
16 /// Large local arrays may cause stack overflow.
20 /// let a = [0u32; 1_000_000];
22 pub LARGE_STACK_ARRAYS,
24 "allocating large arrays on stack may cause stack overflow"
27 pub struct LargeStackArrays {
28 maximum_allowed_size: u64,
31 impl LargeStackArrays {
33 pub fn new(maximum_allowed_size: u64) -> Self {
34 Self { maximum_allowed_size }
38 impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]);
40 impl<'tcx> LateLintPass<'tcx> for LargeStackArrays {
41 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
43 if let ExprKind::Repeat(_, _) = expr.kind;
44 if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind();
45 if let ConstKind::Value(ConstValue::Scalar(element_count)) = cst.val;
46 if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
47 if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
48 if self.maximum_allowed_size < element_count * element_size;
55 "allocating a local array larger than {} bytes",
56 self.maximum_allowed_size
60 "consider allocating on the heap with `vec!{}.into_boxed_slice()`",
61 snippet(cx, expr.span, "[...]")