]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mem_forget.rs
Rollup merge of #87166 - de-vri-es:show-discriminant-before-overflow, r=jackh726
[rust.git] / src / tools / clippy / clippy_lints / src / mem_forget.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{match_def_path, paths};
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     /// Checks for usage of `std::mem::forget(t)` where `t` is
10     /// `Drop`.
11     ///
12     /// ### Why is this bad?
13     /// `std::mem::forget(t)` prevents `t` from running its
14     /// destructor, possibly causing leaks.
15     ///
16     /// ### Example
17     /// ```rust
18     /// # use std::mem;
19     /// # use std::rc::Rc;
20     /// mem::forget(Rc::new(55))
21     /// ```
22     pub MEM_FORGET,
23     restriction,
24     "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
25 }
26
27 declare_lint_pass!(MemForget => [MEM_FORGET]);
28
29 impl<'tcx> LateLintPass<'tcx> for MemForget {
30     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
31         if let ExprKind::Call(path_expr, args) = e.kind {
32             if let ExprKind::Path(ref qpath) = path_expr.kind {
33                 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
34                     if match_def_path(cx, def_id, &paths::MEM_FORGET) {
35                         let forgot_ty = cx.typeck_results().expr_ty(&args[0]);
36
37                         if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
38                             span_lint(cx, MEM_FORGET, e.span, "usage of `mem::forget` on `Drop` type");
39                         }
40                     }
41                 }
42             }
43         }
44     }
45 }