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