2019-12-03 23:16:03 +00:00
|
|
|
use rustc::impl_lint_pass;
|
2019-11-12 22:22:53 +00:00
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
|
|
|
use rustc::mir::interpret::ConstValue;
|
2019-11-23 17:09:09 +00:00
|
|
|
use rustc::ty::{self, ConstKind};
|
2020-01-06 16:39:50 +00:00
|
|
|
use rustc_hir::*;
|
2019-12-03 23:16:03 +00:00
|
|
|
use rustc_session::declare_tool_lint;
|
2019-11-12 22:22:53 +00:00
|
|
|
|
|
|
|
use if_chain::if_chain;
|
|
|
|
|
|
|
|
use crate::rustc_target::abi::LayoutOf;
|
|
|
|
use crate::utils::{snippet, span_help_and_lint};
|
|
|
|
|
|
|
|
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]);
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeStackArrays {
|
2019-12-27 07:12:26 +00:00
|
|
|
fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
|
2019-11-12 22:22:53 +00:00
|
|
|
if_chain! {
|
|
|
|
if let ExprKind::Repeat(_, _) = expr.kind;
|
|
|
|
if let ty::Array(element_type, cst) = cx.tables.expr_ty(expr).kind;
|
2019-11-23 17:09:09 +00:00
|
|
|
if let ConstKind::Value(val) = cst.val;
|
|
|
|
if let ConstValue::Scalar(element_count) = val;
|
2019-11-12 22:22:53 +00: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 {
|
|
|
|
span_help_and_lint(
|
|
|
|
cx,
|
|
|
|
LARGE_STACK_ARRAYS,
|
|
|
|
expr.span,
|
|
|
|
&format!(
|
|
|
|
"allocating a local array larger than {} bytes",
|
|
|
|
self.maximum_allowed_size
|
|
|
|
),
|
|
|
|
&format!(
|
|
|
|
"consider allocating on the heap with vec!{}.into_boxed_slice()",
|
|
|
|
snippet(cx, expr.span, "[...]")
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|