diff --git a/src/mem_forget.rs b/src/mem_forget.rs index d857adf10d65..0568e70023a7 100644 --- a/src/mem_forget.rs +++ b/src/mem_forget.rs @@ -1,18 +1,18 @@ use rustc::lint::*; use rustc::hir::{Expr, ExprCall, ExprPath}; -use utils::{match_def_path, paths, span_lint}; +use utils::{get_trait_def_id, implements_trait, match_def_path, paths, span_lint}; -/// **What it does:** This lint checks for usage of `std::mem::forget(_)`. +/// **What it does:** This lint checks for usage of `std::mem::forget(t)` where `t` is `Drop`. /// /// **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its destructor, possibly causing leaks /// /// **Known problems:** None. /// -/// **Example:** `mem::forget(_))` +/// **Example:** `mem::forget(Rc::new(55)))` declare_lint! { pub MEM_FORGET, Allow, - "`mem::forget` usage is likely to cause memory leaks" + "`mem::forget` usage on `Drop` types is likely to cause memory leaks" } pub struct MemForget; @@ -25,12 +25,17 @@ impl LintPass for MemForget { impl LateLintPass for MemForget { fn check_expr(&mut self, cx: &LateContext, e: &Expr) { - if let ExprCall(ref path_expr, _) = e.node { + if let ExprCall(ref path_expr, ref args) = e.node { if let ExprPath(None, _) = path_expr.node { let def_id = cx.tcx.def_map.borrow()[&path_expr.id].def_id(); - if match_def_path(cx, def_id, &paths::MEM_FORGET) { - span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget"); + if let Some(drop_trait_id) = get_trait_def_id(cx, &paths::DROP) { + let forgot_ty = cx.tcx.expr_ty(&args[0]); + + if implements_trait(cx, forgot_ty, drop_trait_id, Vec::new()) { + span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type"); + } + } } } } diff --git a/tests/compile-fail/mem_forget.rs b/tests/compile-fail/mem_forget.rs index 5198b4ea8d3a..c8cebcb2a42d 100644 --- a/tests/compile-fail/mem_forget.rs +++ b/tests/compile-fail/mem_forget.rs @@ -2,6 +2,7 @@ #![plugin(clippy)] use std::sync::Arc; +use std::rc::Rc; use std::mem::forget as forgetSomething; use std::mem as memstuff; @@ -10,12 +11,18 @@ use std::mem as memstuff; fn main() { let five: i32 = 5; forgetSomething(five); - //~^ ERROR usage of mem::forget let six: Arc = Arc::new(6); memstuff::forget(six); - //~^ ERROR usage of mem::forget + //~^ ERROR usage of mem::forget on Drop type + + let seven: Rc = Rc::new(7); + std::mem::forget(seven); + //~^ ERROR usage of mem::forget on Drop type + + let eight: Vec = vec![8]; + forgetSomething(eight); + //~^ ERROR usage of mem::forget on Drop type std::mem::forget(7); - //~^ ERROR usage of mem::forget }