2017-09-29 02:24:31 +00:00
|
|
|
use rustc::lint::*;
|
|
|
|
use rustc::ty;
|
|
|
|
use rustc::hir::*;
|
2018-05-30 08:15:50 +00:00
|
|
|
use crate::utils::{match_def_path, opt_def_id, paths, span_help_and_lint};
|
2017-09-29 02:24:31 +00:00
|
|
|
|
|
|
|
/// **What it does:** Checks for creation of references to zeroed or uninitialized memory.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Creation of null references is undefined behavior.
|
|
|
|
///
|
2017-11-04 19:55:56 +00:00
|
|
|
/// **Known problems:** None.
|
2017-09-29 02:24:31 +00:00
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust
|
|
|
|
/// let bad_ref: &usize = std::mem::zeroed();
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
declare_clippy_lint! {
|
2017-09-29 02:24:31 +00:00
|
|
|
pub INVALID_REF,
|
2018-03-28 13:24:26 +00:00
|
|
|
correctness,
|
2017-09-29 02:24:31 +00:00
|
|
|
"creation of invalid reference"
|
|
|
|
}
|
|
|
|
|
|
|
|
const ZERO_REF_SUMMARY: &str = "reference to zeroed memory";
|
|
|
|
const UNINIT_REF_SUMMARY: &str = "reference to uninitialized memory";
|
2017-11-04 19:56:05 +00:00
|
|
|
const HELP: &str = "Creation of a null reference is undefined behavior; \
|
|
|
|
see https://doc.rust-lang.org/reference/behavior-considered-undefined.html";
|
2017-09-29 02:24:31 +00:00
|
|
|
|
2017-11-04 19:55:56 +00:00
|
|
|
pub struct InvalidRef;
|
2017-09-29 02:24:31 +00:00
|
|
|
|
|
|
|
impl LintPass for InvalidRef {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array!(INVALID_REF)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
|
2017-10-23 19:18:02 +00:00
|
|
|
if_chain! {
|
|
|
|
if let ExprCall(ref path, ref args) = expr.node;
|
|
|
|
if let ExprPath(ref qpath) = path.node;
|
|
|
|
if args.len() == 0;
|
2017-11-04 19:55:56 +00:00
|
|
|
if let ty::TyRef(..) = cx.tables.expr_ty(expr).sty;
|
2017-10-23 19:18:02 +00:00
|
|
|
if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
|
|
|
|
then {
|
2017-11-04 19:56:05 +00:00
|
|
|
let msg = if match_def_path(cx.tcx, def_id, &paths::MEM_ZEROED) |
|
|
|
|
match_def_path(cx.tcx, def_id, &paths::INIT)
|
|
|
|
{
|
2017-10-23 19:18:02 +00:00
|
|
|
ZERO_REF_SUMMARY
|
2017-11-04 19:56:05 +00:00
|
|
|
} else if match_def_path(cx.tcx, def_id, &paths::MEM_UNINIT) |
|
|
|
|
match_def_path(cx.tcx, def_id, &paths::UNINIT)
|
|
|
|
{
|
2017-10-23 19:18:02 +00:00
|
|
|
UNINIT_REF_SUMMARY
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);
|
|
|
|
}
|
2017-11-04 19:55:56 +00:00
|
|
|
}
|
2017-09-29 02:24:31 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|