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