Skip to content

Commit

Permalink
Limited mem_forget error to only Drop types (fails)
Browse files Browse the repository at this point in the history
  • Loading branch information
cramertj committed Apr 21, 2016
1 parent 5158a08 commit 77427b6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
19 changes: 12 additions & 7 deletions 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;
Expand All @@ -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");
}
}
}
}
}
Expand Down
13 changes: 10 additions & 3 deletions tests/compile-fail/mem_forget.rs
Expand Up @@ -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;
Expand All @@ -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<i32> = Arc::new(6);
memstuff::forget(six);
//~^ ERROR usage of mem::forget
//~^ ERROR usage of mem::forget on Drop type

let seven: Rc<i32> = Rc::new(7);
std::mem::forget(seven);
//~^ ERROR usage of mem::forget on Drop type

let eight: Vec<i32> = vec![8];
forgetSomething(eight);
//~^ ERROR usage of mem::forget on Drop type

std::mem::forget(7);
//~^ ERROR usage of mem::forget
}

0 comments on commit 77427b6

Please sign in to comment.