]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_forget.rs
Match on ast/hir::ExprKind::Err
[rust.git] / clippy_lints / src / mem_forget.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::hir::{Expr, ExprKind};
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
14
15 /// **What it does:** Checks for usage of `std::mem::forget(t)` where `t` is
16 /// `Drop`.
17 ///
18 /// **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its
19 /// destructor, possibly causing leaks.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// mem::forget(Rc::new(55))
26 /// ```
27 declare_clippy_lint! {
28     pub MEM_FORGET,
29     restriction,
30     "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
31 }
32
33 pub struct MemForget;
34
35 impl LintPass for MemForget {
36     fn get_lints(&self) -> LintArray {
37         lint_array![MEM_FORGET]
38     }
39 }
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemForget {
42     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
43         if let ExprKind::Call(ref path_expr, ref args) = e.node {
44             if let ExprKind::Path(ref qpath) = path_expr.node {
45                 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path_expr.hir_id)) {
46                     if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
47                         let forgot_ty = cx.tables.expr_ty(&args[0]);
48
49                         if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
50                             span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type");
51                         }
52                     }
53                 }
54             }
55         }
56     }
57 }