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