]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/invalid_ref.rs
Auto merge of #3985 - phansch:move_some_cast_tests, r=flip1995
[rust.git] / clippy_lints / src / invalid_ref.rs
1 use crate::utils::{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_lint_pass, declare_tool_lint};
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 declare_lint_pass!(InvalidRef => [INVALID_REF]);
30
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
32     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
33         if_chain! {
34             if let ExprKind::Call(ref path, ref args) = expr.node;
35             if let ExprKind::Path(ref qpath) = path.node;
36             if args.len() == 0;
37             if let ty::Ref(..) = cx.tables.expr_ty(expr).sty;
38             if let Some(def_id) = cx.tables.qpath_def(qpath, path.hir_id).opt_def_id();
39             then {
40                 let msg = if cx.match_def_path(def_id, &paths::MEM_ZEROED) |
41                              cx.match_def_path(def_id, &paths::INIT)
42                 {
43                     ZERO_REF_SUMMARY
44                 } else if cx.match_def_path(def_id, &paths::MEM_UNINIT) |
45                           cx.match_def_path(def_id, &paths::UNINIT)
46                 {
47                     UNINIT_REF_SUMMARY
48                 } else {
49                     return;
50                 };
51                 span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);
52             }
53         }
54         return;
55     }
56 }