|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use clippy_utils::{is_empty_block, sym}; |
| 3 | +use rustc_hir::{ImplItemKind, Item, ItemKind}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_session::declare_lint_pass; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// Checks for manual implementations of `std::task::Wake` that are empty. |
| 10 | + /// |
| 11 | + /// ### Why is this bad? |
| 12 | + /// `Waker::noop()` provides a more performant and cleaner way to create a |
| 13 | + /// waker that does nothing, avoiding unnecessary `Arc` allocations and |
| 14 | + /// reference count increments. |
| 15 | + /// |
| 16 | + /// ### Example |
| 17 | + /// ```rust |
| 18 | + /// # use std::sync::Arc; |
| 19 | + /// # use std::task::Wake; |
| 20 | + /// struct MyWaker; |
| 21 | + /// impl Wake for MyWaker { |
| 22 | + /// fn wake(self: Arc<Self>) {} |
| 23 | + /// fn wake_by_ref(self: &Arc<Self>) {} |
| 24 | + /// } |
| 25 | + /// ``` |
| 26 | + /// |
| 27 | + /// Use instead: |
| 28 | + /// ```rust |
| 29 | + /// use std::task::Waker; |
| 30 | + /// let waker = Waker::noop(); |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.96.0"] |
| 33 | + pub MANUAL_NOOP_WAKER, |
| 34 | + complexity, |
| 35 | + "manual implementations of noop wakers can be simplified using Waker::noop()" |
| 36 | +} |
| 37 | + |
| 38 | +declare_lint_pass!(ManualNoopWaker => [MANUAL_NOOP_WAKER]); |
| 39 | + |
| 40 | +impl<'tcx> LateLintPass<'tcx> for ManualNoopWaker { |
| 41 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 42 | + if let ItemKind::Impl(imp) = item.kind |
| 43 | + && let Some(trait_ref) = imp.of_trait |
| 44 | + && let Some(trait_id) = trait_ref.trait_ref.trait_def_id() |
| 45 | + && cx.tcx.is_diagnostic_item(sym::Wake, trait_id) |
| 46 | + { |
| 47 | + for impl_item_ref in imp.items { |
| 48 | + let impl_item = cx |
| 49 | + .tcx |
| 50 | + .hir_node_by_def_id(impl_item_ref.owner_id.def_id) |
| 51 | + .expect_impl_item(); |
| 52 | + |
| 53 | + if let ImplItemKind::Fn(_, body_id) = &impl_item.kind { |
| 54 | + let body = cx.tcx.hir_body(*body_id); |
| 55 | + if !is_empty_block(body.value) { |
| 56 | + return; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + span_lint_and_help( |
| 62 | + cx, |
| 63 | + MANUAL_NOOP_WAKER, |
| 64 | + trait_ref.trait_ref.path.span, |
| 65 | + "manual implementation of a no-op waker", |
| 66 | + None, |
| 67 | + "use `std::task::Waker::noop()` instead", |
| 68 | + ); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments