1 use clippy_utils::diagnostics::span_lint_and_note;
2 use clippy_utils::get_parent_node;
3 use clippy_utils::is_must_use_func_call;
4 use clippy_utils::ty::{is_copy, is_must_use_ty, is_type_lang_item};
5 use rustc_hir::{Arm, Expr, ExprKind, LangItem, Node};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::sym;
9 use std::borrow::Cow;
10
11 declare_clippy_lint! {
12 /// ### What it does
13 /// Checks for calls to `std::mem::drop` with a value that does not implement `Drop`.
14 ///
15 /// ### Why is this bad?
16 /// Calling `std::mem::drop` is no different than dropping such a type. A different value may
17 /// have been intended.
18 ///
19 /// ### Example
20 /// ```rust
21 /// struct Foo;
22 /// let x = Foo;
23 /// std::mem::drop(x);
24 /// ```
25 #[clippy::version = "1.62.0"]
26 pub DROP_NON_DROP,
27 suspicious,
28 "call to `std::mem::drop` with a value which does not implement `Drop`"
29 }
30
31 declare_clippy_lint! {
32 /// ### What it does
33 /// Checks for calls to `std::mem::forget` with a value that does not implement `Drop`.
34 ///
35 /// ### Why is this bad?
36 /// Calling `std::mem::forget` is no different than dropping such a type. A different value may
37 /// have been intended.
38 ///
39 /// ### Example
40 /// ```rust
41 /// struct Foo;
42 /// let x = Foo;
43 /// std::mem::forget(x);
44 /// ```
45 #[clippy::version = "1.62.0"]
46 pub FORGET_NON_DROP,
47 suspicious,
48 "call to `std::mem::forget` with a value which does not implement `Drop`"
49 }
50
51 declare_clippy_lint! {
52 /// ### What it does
53 /// Checks for usage of `std::mem::forget(t)` where `t` is
54 /// `Drop` or has a field that implements `Drop`.
55 ///
56 /// ### Why is this bad?
57 /// `std::mem::forget(t)` prevents `t` from running its
58 /// destructor, possibly causing leaks.
59 ///
60 /// ### Example
61 /// ```rust
62 /// # use std::mem;
63 /// # use std::rc::Rc;
64 /// mem::forget(Rc::new(55))
65 /// ```
66 #[clippy::version = "pre 1.29.0"]
67 pub MEM_FORGET,
68 restriction,
69 "`mem::forget` usage on `Drop` types, likely to cause memory leaks"
70 }
71
72 const DROP_NON_DROP_SUMMARY: &str = "call to `std::mem::drop` with a value that does not implement `Drop`. \
73 Dropping such a type only extends its contained lifetimes";
74 const FORGET_NON_DROP_SUMMARY: &str = "call to `std::mem::forget` with a value that does not implement `Drop`. \
75 Forgetting such a type is the same as dropping it";
76
77 declare_lint_pass!(DropForgetRef => [
78 DROP_NON_DROP,
79 FORGET_NON_DROP,
80 MEM_FORGET,
81 ]);
82
83 impl<'tcx> LateLintPass<'tcx> for DropForgetRef {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)84 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
85 if let ExprKind::Call(path, [arg]) = expr.kind
86 && let ExprKind::Path(ref qpath) = path.kind
87 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
88 && let Some(fn_name) = cx.tcx.get_diagnostic_name(def_id)
89 {
90 let arg_ty = cx.typeck_results().expr_ty(arg);
91 let is_copy = is_copy(cx, arg_ty);
92 let drop_is_single_call_in_arm = is_single_call_in_arm(cx, arg, expr);
93 let (lint, msg, note_span) = match fn_name {
94 // early return for uplifted lints: dropping_references, dropping_copy_types, forgetting_references, forgetting_copy_types
95 sym::mem_drop if arg_ty.is_ref() && !drop_is_single_call_in_arm => return,
96 sym::mem_forget if arg_ty.is_ref() => return,
97 sym::mem_drop if is_copy && !drop_is_single_call_in_arm => return,
98 sym::mem_forget if is_copy => return,
99 sym::mem_drop if is_type_lang_item(cx, arg_ty, LangItem::ManuallyDrop) => return,
100 sym::mem_drop
101 if !(arg_ty.needs_drop(cx.tcx, cx.param_env)
102 || is_must_use_func_call(cx, arg)
103 || is_must_use_ty(cx, arg_ty)
104 || drop_is_single_call_in_arm
105 ) =>
106 {
107 (DROP_NON_DROP, DROP_NON_DROP_SUMMARY.into(), Some(arg.span))
108 },
109 sym::mem_forget => {
110 if arg_ty.needs_drop(cx.tcx, cx.param_env) {
111 (
112 MEM_FORGET,
113 Cow::Owned(format!(
114 "usage of `mem::forget` on {}",
115 if arg_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) {
116 "`Drop` type"
117 } else {
118 "type with `Drop` fields"
119 }
120 )),
121 None,
122 )
123 } else {
124 (FORGET_NON_DROP, FORGET_NON_DROP_SUMMARY.into(), Some(arg.span))
125 }
126 }
127 _ => return,
128 };
129 span_lint_and_note(
130 cx,
131 lint,
132 expr.span,
133 &msg,
134 note_span,
135 &format!("argument has type `{arg_ty}`"),
136 );
137 }
138 }
139 }
140
141 // dropping returned value of a function like in the following snippet is considered idiomatic, see
142 // #9482 for examples match <var> {
143 // <pat> => drop(fn_with_side_effect_and_returning_some_value()),
144 // ..
145 // }
is_single_call_in_arm<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'_>, drop_expr: &'tcx Expr<'_>) -> bool146 fn is_single_call_in_arm<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'_>, drop_expr: &'tcx Expr<'_>) -> bool {
147 if matches!(arg.kind, ExprKind::Call(..) | ExprKind::MethodCall(..)) {
148 let parent_node = get_parent_node(cx.tcx, drop_expr.hir_id);
149 if let Some(Node::Arm(Arm { body, .. })) = &parent_node {
150 return body.hir_id == drop_expr.hir_id;
151 }
152 }
153 false
154 }
155