2 use rustc::impl_lint_pass;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::mir::interpret::ConstValue;
5 use rustc::ty::{self, ConstKind};
6 use rustc_session::declare_tool_lint;
8 use if_chain::if_chain;
10 use crate::rustc_target::abi::LayoutOf;
11 use crate::utils::{snippet, span_help_and_lint};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for local arrays that may be too large.
16 /// **Why is this bad?** Large local arrays may cause stack overflow.
18 /// **Known problems:** None.
22 /// let a = [0u32; 1_000_000];
24 pub LARGE_STACK_ARRAYS,
26 "allocating large arrays on stack may cause stack overflow"
29 pub struct LargeStackArrays {
30 maximum_allowed_size: u64,
33 impl LargeStackArrays {
35 pub fn new(maximum_allowed_size: u64) -> Self {
36 Self { maximum_allowed_size }
40 impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]);
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeStackArrays {
43 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
45 if let ExprKind::Repeat(_, _) = expr.kind;
46 if let ty::Array(element_type, cst) = cx.tables.expr_ty(expr).kind;
47 if let ConstKind::Value(val) = cst.val;
48 if let ConstValue::Scalar(element_count) = val;
49 if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
50 if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
51 if self.maximum_allowed_size < element_count * element_size;
58 "allocating a local array larger than {} bytes",
59 self.maximum_allowed_size
62 "consider allocating on the heap with vec!{}.into_boxed_slice()",
63 snippet(cx, expr.span, "[...]")