]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_stack_arrays.rs
Update iterator_step_by_zero
[rust.git] / clippy_lints / src / large_stack_arrays.rs
1 use rustc::hir::*;
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;
7
8 use if_chain::if_chain;
9
10 use crate::rustc_target::abi::LayoutOf;
11 use crate::utils::{snippet, span_help_and_lint};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for local arrays that may be too large.
15     ///
16     /// **Why is this bad?** Large local arrays may cause stack overflow.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust,ignore
22     /// let a = [0u32; 1_000_000];
23     /// ```
24     pub LARGE_STACK_ARRAYS,
25     pedantic,
26     "allocating large arrays on stack may cause stack overflow"
27 }
28
29 pub struct LargeStackArrays {
30     maximum_allowed_size: u64,
31 }
32
33 impl LargeStackArrays {
34     #[must_use]
35     pub fn new(maximum_allowed_size: u64) -> Self {
36         Self { maximum_allowed_size }
37     }
38 }
39
40 impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]);
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeStackArrays {
43     fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
44         if_chain! {
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;
52             then {
53                 span_help_and_lint(
54                     cx,
55                     LARGE_STACK_ARRAYS,
56                     expr.span,
57                     &format!(
58                         "allocating a local array larger than {} bytes",
59                         self.maximum_allowed_size
60                     ),
61                     &format!(
62                         "consider allocating on the heap with vec!{}.into_boxed_slice()",
63                         snippet(cx, expr.span, "[...]")
64                     ),
65                 );
66             }
67         }
68     }
69 }