]> git.lizzy.rs Git - rust.git/blob - src/mem_forget.rs
Limited mem_forget error to only Drop types (fails)
[rust.git] / src / mem_forget.rs
1 use rustc::lint::*;
2 use rustc::hir::{Expr, ExprCall, ExprPath};
3 use utils::{get_trait_def_id, implements_trait, match_def_path, paths, span_lint};
4
5 /// **What it does:** This lint checks for usage of `std::mem::forget(t)` where `t` is `Drop`.
6 ///
7 /// **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its destructor, possibly causing leaks
8 ///
9 /// **Known problems:** None.
10 ///
11 /// **Example:** `mem::forget(Rc::new(55)))`
12 declare_lint! {
13     pub MEM_FORGET,
14     Allow,
15     "`mem::forget` usage on `Drop` types is likely to cause memory leaks"
16 }
17
18 pub struct MemForget;
19
20 impl LintPass for MemForget {
21     fn get_lints(&self) -> LintArray {
22         lint_array![MEM_FORGET]
23     }
24 }
25
26 impl LateLintPass for MemForget {
27     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
28         if let ExprCall(ref path_expr, ref args) = e.node {
29             if let ExprPath(None, _) = path_expr.node {
30                 let def_id = cx.tcx.def_map.borrow()[&path_expr.id].def_id();
31                 if match_def_path(cx, def_id, &paths::MEM_FORGET) {
32                     if let Some(drop_trait_id) = get_trait_def_id(cx, &paths::DROP) {
33                         let forgot_ty = cx.tcx.expr_ty(&args[0]);
34
35                         if implements_trait(cx, forgot_ty, drop_trait_id, Vec::new()) {
36                             span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type");
37                         }
38                     }
39                 }
40             }
41         }
42     }
43 }