1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::utils::{match_def_path, opt_def_id, paths, span_help_and_lint};
15 use if_chain::if_chain;
17 /// **What it does:** Checks for creation of references to zeroed or uninitialized memory.
19 /// **Why is this bad?** Creation of null references is undefined behavior.
21 /// **Known problems:** None.
25 /// let bad_ref: &usize = std::mem::zeroed();
27 declare_clippy_lint! {
30 "creation of invalid reference"
33 const ZERO_REF_SUMMARY: &str = "reference to zeroed memory";
34 const UNINIT_REF_SUMMARY: &str = "reference to uninitialized memory";
35 const HELP: &str = "Creation of a null reference is undefined behavior; \
36 see https://doc.rust-lang.org/reference/behavior-considered-undefined.html";
38 pub struct InvalidRef;
40 impl LintPass for InvalidRef {
41 fn get_lints(&self) -> LintArray {
42 lint_array!(INVALID_REF)
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
47 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49 if let ExprKind::Call(ref path, ref args) = expr.node;
50 if let ExprKind::Path(ref qpath) = path.node;
52 if let ty::Ref(..) = cx.tables.expr_ty(expr).sty;
53 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
55 let msg = if match_def_path(cx.tcx, def_id, &paths::MEM_ZEROED) |
56 match_def_path(cx.tcx, def_id, &paths::INIT)
59 } else if match_def_path(cx.tcx, def_id, &paths::MEM_UNINIT) |
60 match_def_path(cx.tcx, def_id, &paths::UNINIT)
66 span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);