Lint mem_forget
if fields are Drop
This commit is contained in:
parent
62972ae2dd
commit
d8d59965f1
@ -7,7 +7,7 @@ use rustc_span::sym;
|
||||
declare_clippy_lint! {
|
||||
/// ### What it does
|
||||
/// Checks for usage of `std::mem::forget(t)` where `t` is
|
||||
/// `Drop`.
|
||||
/// `Drop` or has a field that implements `Drop`.
|
||||
///
|
||||
/// ### Why is this bad?
|
||||
/// `std::mem::forget(t)` prevents `t` from running its
|
||||
@ -29,18 +29,26 @@ declare_lint_pass!(MemForget => [MEM_FORGET]);
|
||||
|
||||
impl<'tcx> LateLintPass<'tcx> for MemForget {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
|
||||
if let ExprKind::Call(path_expr, [ref first_arg, ..]) = e.kind {
|
||||
if let ExprKind::Path(ref qpath) = path_expr.kind {
|
||||
if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
|
||||
if cx.tcx.is_diagnostic_item(sym::mem_forget, def_id) {
|
||||
let forgot_ty = cx.typeck_results().expr_ty(first_arg);
|
||||
|
||||
if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
|
||||
span_lint(cx, MEM_FORGET, e.span, "usage of `mem::forget` on `Drop` type");
|
||||
}
|
||||
if let ExprKind::Call(path_expr, [ref first_arg, ..]) = e.kind
|
||||
&& let ExprKind::Path(ref qpath) = path_expr.kind
|
||||
&& let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
|
||||
&& cx.tcx.is_diagnostic_item(sym::mem_forget, def_id)
|
||||
&& let forgot_ty = cx.typeck_results().expr_ty(first_arg)
|
||||
&& forgot_ty.needs_drop(cx.tcx, cx.param_env)
|
||||
{
|
||||
span_lint(
|
||||
cx,
|
||||
MEM_FORGET,
|
||||
e.span,
|
||||
&format!(
|
||||
"usage of `mem::forget` on {}",
|
||||
if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
|
||||
"`Drop` type"
|
||||
} else {
|
||||
"type with `Drop` fields"
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -19,5 +19,8 @@ fn main() {
|
||||
let eight: Vec<i32> = vec![8];
|
||||
forgetSomething(eight);
|
||||
|
||||
let string = String::new();
|
||||
std::mem::forget(string);
|
||||
|
||||
std::mem::forget(7);
|
||||
}
|
||||
|
@ -18,5 +18,11 @@ error: usage of `mem::forget` on `Drop` type
|
||||
LL | forgetSomething(eight);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: aborting due to 3 previous errors
|
||||
error: usage of `mem::forget` on type with `Drop` fields
|
||||
--> $DIR/mem_forget.rs:23:5
|
||||
|
|
||||
LL | std::mem::forget(string);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: aborting due to 4 previous errors
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user