]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mem_forget.rs
Rollup merge of #96336 - Nilstrieb:link-to-correct-as_mut-in-ptr-as_ref, r=JohnTitor
[rust.git] / src / tools / clippy / clippy_lints / src / mem_forget.rs
1 use clippy_utils::diagnostics::span_lint;
2 use rustc_hir::{Expr, ExprKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5 use rustc_span::sym;
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     #[clippy::version = "pre 1.29.0"]
23     pub MEM_FORGET,
24     restriction,
25     "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
26 }
27
28 declare_lint_pass!(MemForget => [MEM_FORGET]);
29
30 impl<'tcx> LateLintPass<'tcx> for MemForget {
31     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
32         if let ExprKind::Call(path_expr, [ref first_arg, ..]) = e.kind {
33             if let ExprKind::Path(ref qpath) = path_expr.kind {
34                 if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
35                     if cx.tcx.is_diagnostic_item(sym::mem_forget, def_id) {
36                         let forgot_ty = cx.typeck_results().expr_ty(first_arg);
37
38                         if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
39                             span_lint(cx, MEM_FORGET, e.span, "usage of `mem::forget` on `Drop` type");
40                         }
41                     }
42                 }
43             }
44         }
45     }
46 }