]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/invalid_ref.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / invalid_ref.rs
1 use crate::utils::{match_def_path, paths, span_help_and_lint};
2 use if_chain::if_chain;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty;
6 use rustc::{declare_tool_lint, lint_array};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for creation of references to zeroed or uninitialized memory.
10     ///
11     /// **Why is this bad?** Creation of null references is undefined behavior.
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     /// ```no_run
17     /// let bad_ref: &usize = unsafe { std::mem::zeroed() };
18     /// ```
19     pub INVALID_REF,
20     correctness,
21     "creation of invalid reference"
22 }
23
24 const ZERO_REF_SUMMARY: &str = "reference to zeroed memory";
25 const UNINIT_REF_SUMMARY: &str = "reference to uninitialized memory";
26 const HELP: &str = "Creation of a null reference is undefined behavior; \
27                     see https://doc.rust-lang.org/reference/behavior-considered-undefined.html";
28
29 pub struct InvalidRef;
30
31 impl LintPass for InvalidRef {
32     fn get_lints(&self) -> LintArray {
33         lint_array!(INVALID_REF)
34     }
35
36     fn name(&self) -> &'static str {
37         "InvalidRef"
38     }
39 }
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
42     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
43         if_chain! {
44             if let ExprKind::Call(ref path, ref args) = expr.node;
45             if let ExprKind::Path(ref qpath) = path.node;
46             if args.len() == 0;
47             if let ty::Ref(..) = cx.tables.expr_ty(expr).sty;
48             if let Some(def_id) = cx.tables.qpath_def(qpath, path.hir_id).opt_def_id();
49             then {
50                 let msg = if match_def_path(cx.tcx, def_id, &paths::MEM_ZEROED) |
51                              match_def_path(cx.tcx, def_id, &paths::INIT)
52                 {
53                     ZERO_REF_SUMMARY
54                 } else if match_def_path(cx.tcx, def_id, &paths::MEM_UNINIT) |
55                           match_def_path(cx.tcx, def_id, &paths::UNINIT)
56                 {
57                     UNINIT_REF_SUMMARY
58                 } else {
59                     return;
60                 };
61                 span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);
62             }
63         }
64         return;
65     }
66 }