2020-02-21 02:39:38 -06:00
|
|
|
use rustc_hir::{Expr, ExprKind};
|
2020-01-12 00:08:41 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2020-03-30 04:02:14 -05:00
|
|
|
use rustc_middle::mir::interpret::ConstValue;
|
|
|
|
use rustc_middle::ty::{self, ConstKind};
|
2020-01-11 05:37:08 -06:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2019-11-12 16:22:53 -06:00
|
|
|
|
|
|
|
use if_chain::if_chain;
|
|
|
|
|
|
|
|
use crate::rustc_target::abi::LayoutOf;
|
2020-01-26 19:56:22 -06:00
|
|
|
use crate::utils::{snippet, span_lint_and_help};
|
2019-11-12 16:22:53 -06:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
|
|
|
/// **What it does:** Checks for local arrays that may be too large.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Large local arrays may cause stack overflow.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// let a = [0u32; 1_000_000];
|
|
|
|
/// ```
|
|
|
|
pub LARGE_STACK_ARRAYS,
|
|
|
|
pedantic,
|
|
|
|
"allocating large arrays on stack may cause stack overflow"
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct LargeStackArrays {
|
|
|
|
maximum_allowed_size: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl LargeStackArrays {
|
|
|
|
#[must_use]
|
|
|
|
pub fn new(maximum_allowed_size: u64) -> Self {
|
|
|
|
Self { maximum_allowed_size }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]);
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for LargeStackArrays {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
|
2019-11-12 16:22:53 -06:00
|
|
|
if_chain! {
|
|
|
|
if let ExprKind::Repeat(_, _) = expr.kind;
|
2020-08-03 17:18:29 -05:00
|
|
|
if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind();
|
2019-11-23 11:09:09 -06:00
|
|
|
if let ConstKind::Value(val) = cst.val;
|
|
|
|
if let ConstValue::Scalar(element_count) = val;
|
2019-11-12 16:22:53 -06:00
|
|
|
if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
|
|
|
|
if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
|
|
|
|
if self.maximum_allowed_size < element_count * element_size;
|
|
|
|
then {
|
2020-01-26 19:56:22 -06:00
|
|
|
span_lint_and_help(
|
2019-11-12 16:22:53 -06:00
|
|
|
cx,
|
|
|
|
LARGE_STACK_ARRAYS,
|
|
|
|
expr.span,
|
|
|
|
&format!(
|
|
|
|
"allocating a local array larger than {} bytes",
|
|
|
|
self.maximum_allowed_size
|
|
|
|
),
|
2020-04-18 05:28:29 -05:00
|
|
|
None,
|
2019-11-12 16:22:53 -06:00
|
|
|
&format!(
|
2020-01-06 00:30:43 -06:00
|
|
|
"consider allocating on the heap with `vec!{}.into_boxed_slice()`",
|
2019-11-12 16:22:53 -06:00
|
|
|
snippet(cx, expr.span, "[...]")
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|