]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/invalid_ref.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[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 use crate::utils::{match_def_path, opt_def_id, paths, span_help_and_lint};
11 use if_chain::if_chain;
12 use rustc::hir::*;
13 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use rustc::ty;
15 use rustc::{declare_tool_lint, lint_array};
16
17 /// **What it does:** Checks for creation of references to zeroed or uninitialized memory.
18 ///
19 /// **Why is this bad?** Creation of null references is undefined behavior.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// let bad_ref: &usize = std::mem::zeroed();
26 /// ```
27 declare_clippy_lint! {
28     pub INVALID_REF,
29     correctness,
30     "creation of invalid reference"
31 }
32
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";
37
38 pub struct InvalidRef;
39
40 impl LintPass for InvalidRef {
41     fn get_lints(&self) -> LintArray {
42         lint_array!(INVALID_REF)
43     }
44 }
45
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48         if_chain! {
49             if let ExprKind::Call(ref path, ref args) = expr.node;
50             if let ExprKind::Path(ref qpath) = path.node;
51             if args.len() == 0;
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));
54             then {
55                 let msg = if match_def_path(cx.tcx, def_id, &paths::MEM_ZEROED) |
56                              match_def_path(cx.tcx, def_id, &paths::INIT)
57                 {
58                     ZERO_REF_SUMMARY
59                 } else if match_def_path(cx.tcx, def_id, &paths::MEM_UNINIT) |
60                           match_def_path(cx.tcx, def_id, &paths::UNINIT)
61                 {
62                     UNINIT_REF_SUMMARY
63                 } else {
64                     return;
65                 };
66                 span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);
67             }
68         }
69         return;
70     }
71 }