|
| 1 | +use crate::{LateContext, LateLintPass, LintContext}; |
| 2 | +use rustc_hir as hir; |
| 3 | + |
| 4 | +declare_lint! { |
| 5 | + /// The `let_underscore_drop` lint checks for statements which don't bind |
| 6 | + /// an expression which has a non-trivial Drop implementation to anything, |
| 7 | + /// causing the expression to be dropped immediately instead of at end of |
| 8 | + /// scope. |
| 9 | + /// |
| 10 | + /// ### Example |
| 11 | + /// ```rust |
| 12 | + /// struct SomeStruct; |
| 13 | + /// impl Drop for SomeStruct { |
| 14 | + /// fn drop(&mut self) { |
| 15 | + /// println!("Dropping SomeStruct"); |
| 16 | + /// } |
| 17 | + /// } |
| 18 | + /// |
| 19 | + /// fn main() { |
| 20 | + /// // SomeStuct is dropped immediately instead of at end of scope, |
| 21 | + /// // so "Dropping SomeStruct" is printed before "end of main". |
| 22 | + /// // The order of prints would be reversed if SomeStruct was bound to |
| 23 | + /// // a name (such as "_foo"). |
| 24 | + /// let _ = SomeStruct; |
| 25 | + /// println!("end of main"); |
| 26 | + /// } |
| 27 | + /// ``` |
| 28 | + /// ### Explanation |
| 29 | + /// |
| 30 | + /// Statements which assign an expression to an underscore causes the |
| 31 | + /// expression to immediately drop instead of extending the expression's |
| 32 | + /// lifetime to the end of the scope. This is usually unintended, |
| 33 | + /// especially for types like `MutexGuard`, which are typically used to |
| 34 | + /// lock a mutex for the duration of an entire scope. |
| 35 | + /// |
| 36 | + /// If you want to extend the expression's lifetime to the end of the scope, |
| 37 | + /// assign an underscore-prefixed name (such as `_foo`) to the expression. |
| 38 | + /// If you do actually want to drop the expression immediately, then |
| 39 | + /// calling `std::mem::drop` on the expression is clearer and helps convey |
| 40 | + /// intent. |
| 41 | + pub LET_UNDERSCORE_DROP, |
| 42 | + Warn, |
| 43 | + "non-binding let on a type that implements `Drop`" |
| 44 | +} |
| 45 | + |
| 46 | +declare_lint_pass!(LetUnderscore => [LET_UNDERSCORE_DROP]); |
| 47 | + |
| 48 | +impl<'tcx> LateLintPass<'tcx> for LetUnderscore { |
| 49 | + fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::Local<'_>) { |
| 50 | + if !matches!(local.pat.kind, hir::PatKind::Wild) { |
| 51 | + return; |
| 52 | + } |
| 53 | + if let Some(init) = local.init { |
| 54 | + let init_ty = cx.typeck_results().expr_ty(init); |
| 55 | + let needs_drop = init_ty.needs_drop(cx.tcx, cx.param_env); |
| 56 | + if needs_drop { |
| 57 | + cx.struct_span_lint(LET_UNDERSCORE_DROP, local.span, |lint| { |
| 58 | + lint.build("non-binding let on a type that implements `Drop`") |
| 59 | + .help("consider binding to an unused variable") |
| 60 | + .help("consider explicitly droping with `std::mem::drop`") |
| 61 | + .emit(); |
| 62 | + }) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments