• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use rustc_hir::{Arm, Expr, ExprKind, Node};
2 use rustc_middle::ty;
3 use rustc_span::sym;
4 
5 use crate::{
6     lints::{
7         DropCopyDiag, DropRefDiag, ForgetCopyDiag, ForgetRefDiag, UndroppedManuallyDropsDiag,
8         UndroppedManuallyDropsSuggestion,
9     },
10     LateContext, LateLintPass, LintContext,
11 };
12 
13 declare_lint! {
14     /// The `dropping_references` lint checks for calls to `std::mem::drop` with a reference
15     /// instead of an owned value.
16     ///
17     /// ### Example
18     ///
19     /// ```rust
20     /// # fn operation_that_requires_mutex_to_be_unlocked() {} // just to make it compile
21     /// # let mutex = std::sync::Mutex::new(1); // just to make it compile
22     /// let mut lock_guard = mutex.lock();
23     /// std::mem::drop(&lock_guard); // Should have been drop(lock_guard), mutex
24     /// // still locked
25     /// operation_that_requires_mutex_to_be_unlocked();
26     /// ```
27     ///
28     /// {{produces}}
29     ///
30     /// ### Explanation
31     ///
32     /// Calling `drop` on a reference will only drop the
33     /// reference itself, which is a no-op. It will not call the `drop` method (from
34     /// the `Drop` trait implementation) on the underlying referenced value, which
35     /// is likely what was intended.
36     pub DROPPING_REFERENCES,
37     Warn,
38     "calls to `std::mem::drop` with a reference instead of an owned value"
39 }
40 
41 declare_lint! {
42     /// The `forgetting_references` lint checks for calls to `std::mem::forget` with a reference
43     /// instead of an owned value.
44     ///
45     /// ### Example
46     ///
47     /// ```rust
48     /// let x = Box::new(1);
49     /// std::mem::forget(&x); // Should have been forget(x), x will still be dropped
50     /// ```
51     ///
52     /// {{produces}}
53     ///
54     /// ### Explanation
55     ///
56     /// Calling `forget` on a reference will only forget the
57     /// reference itself, which is a no-op. It will not forget the underlying
58     /// referenced value, which is likely what was intended.
59     pub FORGETTING_REFERENCES,
60     Warn,
61     "calls to `std::mem::forget` with a reference instead of an owned value"
62 }
63 
64 declare_lint! {
65     /// The `dropping_copy_types` lint checks for calls to `std::mem::drop` with a value
66     /// that derives the Copy trait.
67     ///
68     /// ### Example
69     ///
70     /// ```rust
71     /// let x: i32 = 42; // i32 implements Copy
72     /// std::mem::drop(x); // A copy of x is passed to the function, leaving the
73     ///                    // original unaffected
74     /// ```
75     ///
76     /// {{produces}}
77     ///
78     /// ### Explanation
79     ///
80     /// Calling `std::mem::drop` [does nothing for types that
81     /// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the
82     /// value will be copied and moved into the function on invocation.
83     pub DROPPING_COPY_TYPES,
84     Warn,
85     "calls to `std::mem::drop` with a value that implements Copy"
86 }
87 
88 declare_lint! {
89     /// The `forgetting_copy_types` lint checks for calls to `std::mem::forget` with a value
90     /// that derives the Copy trait.
91     ///
92     /// ### Example
93     ///
94     /// ```rust
95     /// let x: i32 = 42; // i32 implements Copy
96     /// std::mem::forget(x); // A copy of x is passed to the function, leaving the
97     ///                      // original unaffected
98     /// ```
99     ///
100     /// {{produces}}
101     ///
102     /// ### Explanation
103     ///
104     /// Calling `std::mem::forget` [does nothing for types that
105     /// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the
106     /// value will be copied and moved into the function on invocation.
107     ///
108     /// An alternative, but also valid, explanation is that Copy types do not
109     /// implement the Drop trait, which means they have no destructors. Without a
110     /// destructor, there is nothing for `std::mem::forget` to ignore.
111     pub FORGETTING_COPY_TYPES,
112     Warn,
113     "calls to `std::mem::forget` with a value that implements Copy"
114 }
115 
116 declare_lint! {
117     /// The `undropped_manually_drops` lint check for calls to `std::mem::drop` with
118     /// a value of `std::mem::ManuallyDrop` which doesn't drop.
119     ///
120     /// ### Example
121     ///
122     /// ```rust,compile_fail
123     /// struct S;
124     /// drop(std::mem::ManuallyDrop::new(S));
125     /// ```
126     ///
127     /// {{produces}}
128     ///
129     /// ### Explanation
130     ///
131     /// `ManuallyDrop` does not drop it's inner value so calling `std::mem::drop` will
132     /// not drop the inner value of the `ManuallyDrop` either.
133     pub UNDROPPED_MANUALLY_DROPS,
134     Deny,
135     "calls to `std::mem::drop` with `std::mem::ManuallyDrop` instead of it's inner value"
136 }
137 
138 declare_lint_pass!(DropForgetUseless => [DROPPING_REFERENCES, FORGETTING_REFERENCES, DROPPING_COPY_TYPES, FORGETTING_COPY_TYPES, UNDROPPED_MANUALLY_DROPS]);
139 
140 impl<'tcx> LateLintPass<'tcx> for DropForgetUseless {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>)141     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
142         if let ExprKind::Call(path, [arg]) = expr.kind
143             && let ExprKind::Path(ref qpath) = path.kind
144             && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
145             && let Some(fn_name) = cx.tcx.get_diagnostic_name(def_id)
146         {
147             let arg_ty = cx.typeck_results().expr_ty(arg);
148             let is_copy = arg_ty.is_copy_modulo_regions(cx.tcx, cx.param_env);
149             let drop_is_single_call_in_arm = is_single_call_in_arm(cx, arg, expr);
150             match fn_name {
151                 sym::mem_drop if arg_ty.is_ref() && !drop_is_single_call_in_arm => {
152                     cx.emit_spanned_lint(DROPPING_REFERENCES, expr.span, DropRefDiag { arg_ty, label: arg.span });
153                 },
154                 sym::mem_forget if arg_ty.is_ref() => {
155                     cx.emit_spanned_lint(FORGETTING_REFERENCES, expr.span, ForgetRefDiag { arg_ty, label: arg.span });
156                 },
157                 sym::mem_drop if is_copy && !drop_is_single_call_in_arm => {
158                     cx.emit_spanned_lint(DROPPING_COPY_TYPES, expr.span, DropCopyDiag { arg_ty, label: arg.span });
159                 }
160                 sym::mem_forget if is_copy => {
161                     cx.emit_spanned_lint(FORGETTING_COPY_TYPES, expr.span, ForgetCopyDiag { arg_ty, label: arg.span });
162                 }
163                 sym::mem_drop if let ty::Adt(adt, _) = arg_ty.kind() && adt.is_manually_drop() => {
164                     cx.emit_spanned_lint(
165                         UNDROPPED_MANUALLY_DROPS,
166                         expr.span,
167                         UndroppedManuallyDropsDiag {
168                             arg_ty,
169                             label: arg.span,
170                             suggestion: UndroppedManuallyDropsSuggestion {
171                                 start_span: arg.span.shrink_to_lo(),
172                                 end_span: arg.span.shrink_to_hi()
173                             }
174                         }
175                     );
176                 }
177                 _ => return,
178             };
179         }
180     }
181 }
182 
183 // Dropping returned value of a function, as in the following snippet is considered idiomatic, see
184 // rust-lang/rust-clippy#9482 for examples.
185 //
186 // ```
187 // match <var> {
188 //     <pat> => drop(fn_with_side_effect_and_returning_some_value()),
189 //     ..
190 // }
191 // ```
is_single_call_in_arm<'tcx>( cx: &LateContext<'tcx>, arg: &'tcx Expr<'_>, drop_expr: &'tcx Expr<'_>, ) -> bool192 fn is_single_call_in_arm<'tcx>(
193     cx: &LateContext<'tcx>,
194     arg: &'tcx Expr<'_>,
195     drop_expr: &'tcx Expr<'_>,
196 ) -> bool {
197     if arg.can_have_side_effects() {
198         let parent_node = cx.tcx.hir().find_parent(drop_expr.hir_id);
199         if let Some(Node::Arm(Arm { body, .. })) = &parent_node {
200             return body.hir_id == drop_expr.hir_id;
201         }
202     }
203     false
204 }
205