]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_forget.rs
Auto merge of #3705 - matthiaskrgr:rustup, r=phansch
[rust.git] / clippy_lints / src / mem_forget.rs
1 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
2 use rustc::hir::{Expr, ExprKind};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5
6 /// **What it does:** Checks for usage of `std::mem::forget(t)` where `t` is
7 /// `Drop`.
8 ///
9 /// **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its
10 /// destructor, possibly causing leaks.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// mem::forget(Rc::new(55))
17 /// ```
18 declare_clippy_lint! {
19     pub MEM_FORGET,
20     restriction,
21     "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
22 }
23
24 pub struct MemForget;
25
26 impl LintPass for MemForget {
27     fn get_lints(&self) -> LintArray {
28         lint_array![MEM_FORGET]
29     }
30
31     fn name(&self) -> &'static str {
32         "MemForget"
33     }
34 }
35
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemForget {
37     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
38         if let ExprKind::Call(ref path_expr, ref args) = e.node {
39             if let ExprKind::Path(ref qpath) = path_expr.node {
40                 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
41                     if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
42                         let forgot_ty = cx.tables.expr_ty(&args[0]);
43
44                         if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
45                             span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type");
46                         }
47                     }
48                 }
49             }
50         }
51     }
52 }