]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_forget.rs
Merge pull request #3314 from matthiaskrgr/mem_forget_sample
[rust.git] / clippy_lints / src / mem_forget.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 crate::rustc::hir::{Expr, ExprKind};
14 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
15
16 /// **What it does:** Checks for usage of `std::mem::forget(t)` where `t` is
17 /// `Drop`.
18 ///
19 /// **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its
20 /// destructor, possibly causing leaks.
21 ///
22 /// **Known problems:** None.
23 ///
24 /// **Example:**
25 /// ```rust
26 /// mem::forget(Rc::new(55))
27 /// ```
28 declare_clippy_lint! {
29     pub MEM_FORGET,
30     restriction,
31     "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
32 }
33
34 pub struct MemForget;
35
36 impl LintPass for MemForget {
37     fn get_lints(&self) -> LintArray {
38         lint_array![MEM_FORGET]
39     }
40 }
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemForget {
43     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
44         if let ExprKind::Call(ref path_expr, ref args) = e.node {
45             if let ExprKind::Path(ref qpath) = path_expr.node {
46                 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
47                     if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
48                         let forgot_ty = cx.tables.expr_ty(&args[0]);
49
50                         if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
51                             span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type");
52                         }
53                     }
54                 }
55             }
56         }
57     }
58 }