Limited mem_forget error to only Drop types (fails)

This commit is contained in:
Taylor Cramer 2016-04-20 19:24:31 -07:00
parent 5158a08c5b
commit 77427b6ead
2 changed files with 22 additions and 10 deletions

View file

@ -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");
}
}
}
}
}

View file

@ -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<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
}