|
| 1 | +use clippy_config::msrvs::Msrv; |
| 2 | +use clippy_config::{Conf, msrvs}; |
| 3 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 4 | +use clippy_utils::visitors::for_each_local_use_after_expr; |
| 5 | +use clippy_utils::{is_from_proc_macro, std_or_core}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::def_id::LocalDefId; |
| 8 | +use rustc_hir::{Expr, ExprKind, LetStmt, Node, PatKind, QPath}; |
| 9 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 10 | +use rustc_middle::lint::in_external_macro; |
| 11 | +use rustc_session::impl_lint_pass; |
| 12 | +use rustc_span::{Span, sym}; |
| 13 | +use std::ops::ControlFlow; |
| 14 | + |
| 15 | +declare_clippy_lint! { |
| 16 | + /// ### What it does |
| 17 | + /// Checks for calls to `Box::pin` with the `Pin<Box<_>>` not moved and only used in places where a `Pin<&mut _>` |
| 18 | + /// suffices, in which case the `pin!` macro can be used. |
| 19 | + /// |
| 20 | + /// ### Why is this bad? |
| 21 | + /// `Box::pin` creates an extra heap allocation for the pointee, while `pin!` creates a local `Pin<&mut T>`, |
| 22 | + /// so this saves an extra heap allocation. |
| 23 | + /// |
| 24 | + /// See the documentation for [`pin!`](https://doc.rust-lang.org/stable/std/pin/macro.pin.html) |
| 25 | + /// for a more detailed explanation on how these two differ. |
| 26 | + /// |
| 27 | + /// ### Known issues |
| 28 | + /// Currently the lint is fairly limited and only emits a warning if the pinned box is used through `.as_mut()` |
| 29 | + /// to prevent false positives w.r.t. lifetimes |
| 30 | + /// (`Pin<Box<_>>` returned by `Box::pin` is `'static`, `Pin<&mut _>` returned by `pin!` is not). |
| 31 | + /// |
| 32 | + /// The following works with `Box::pin` but not with `pin!`: |
| 33 | + /// ``` |
| 34 | + /// fn assert_static<T: 'static>(_: T) {} |
| 35 | + /// assert_static(Box::pin(async {})); |
| 36 | + /// ``` |
| 37 | + /// |
| 38 | + /// Restricting to only lint `.as_mut()` means that we end up with a temporary in both cases, |
| 39 | + /// so if it compiled with `.as_mut()`, then it ought to work with `pin!` as well. |
| 40 | + /// |
| 41 | + /// ### Example |
| 42 | + /// ```no_run |
| 43 | + /// # #![feature(noop_waker)] |
| 44 | + /// # use std::task::{Poll, Waker, Context}; |
| 45 | + /// # use std::future::Future; |
| 46 | + /// |
| 47 | + /// fn now_or_never<F: Future>(fut: F) -> Option<F::Output> { |
| 48 | + /// let mut fut = Box::pin(fut); |
| 49 | + /// |
| 50 | + /// match fut.as_mut().poll(&mut Context::from_waker(Waker::noop())) { |
| 51 | + /// Poll::Ready(val) => Some(val), |
| 52 | + /// Poll::Pending => None |
| 53 | + /// } |
| 54 | + /// } |
| 55 | + /// ``` |
| 56 | + /// Use instead: |
| 57 | + /// ```no_run |
| 58 | + /// # #![feature(noop_waker)] |
| 59 | + /// # use std::task::{Poll, Waker, Context}; |
| 60 | + /// # use std::future::Future; |
| 61 | + /// |
| 62 | + /// fn now_or_never<F: Future>(fut: F) -> Option<F::Output> { |
| 63 | + /// let mut fut = std::pin::pin!(fut); |
| 64 | + /// |
| 65 | + /// match fut.as_mut().poll(&mut Context::from_waker(Waker::noop())) { |
| 66 | + /// Poll::Ready(val) => Some(val), |
| 67 | + /// Poll::Pending => None |
| 68 | + /// } |
| 69 | + /// } |
| 70 | + /// ``` |
| 71 | + #[clippy::version = "1.84.0"] |
| 72 | + pub UNNECESSARY_BOX_PIN, |
| 73 | + perf, |
| 74 | + "using `Box::pin` where `pin!` suffices" |
| 75 | +} |
| 76 | + |
| 77 | +pub struct UnnecessaryBoxPin { |
| 78 | + msrv: Msrv, |
| 79 | +} |
| 80 | + |
| 81 | +impl UnnecessaryBoxPin { |
| 82 | + pub fn new(conf: &'static Conf) -> Self { |
| 83 | + Self { |
| 84 | + msrv: conf.msrv.clone(), |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl_lint_pass!(UnnecessaryBoxPin => [UNNECESSARY_BOX_PIN]); |
| 90 | + |
| 91 | +impl<'tcx> LateLintPass<'tcx> for UnnecessaryBoxPin { |
| 92 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { |
| 93 | + if let ExprKind::Call(callee, [_]) = expr.kind |
| 94 | + && let ExprKind::Path(QPath::TypeRelative(bx, segment)) = &callee.kind |
| 95 | + && cx.typeck_results().node_type(bx.hir_id).is_box() |
| 96 | + && segment.ident.name == sym::pin |
| 97 | + && let Some(enclosing_body) = cx.enclosing_body |
| 98 | + && let Some(std_or_core) = std_or_core(cx) |
| 99 | + && self.msrv.meets(msrvs::PIN_MACRO) |
| 100 | + && !in_external_macro(cx.sess(), expr.span) |
| 101 | + && !is_from_proc_macro(cx, expr) |
| 102 | + { |
| 103 | + let enclosing_body_def_id = cx.tcx.hir().body_owner_def_id(enclosing_body); |
| 104 | + |
| 105 | + if let ControlFlow::Continue(as_mut_span) = check_pin_box_use(cx, expr, false, enclosing_body_def_id) { |
| 106 | + span_lint_and_then( |
| 107 | + cx, |
| 108 | + UNNECESSARY_BOX_PIN, |
| 109 | + expr.span, |
| 110 | + "pinning a value with `Box::pin` when local pinning suffices", |
| 111 | + |diag| { |
| 112 | + let mut replacements = vec![(callee.span, format!("{std_or_core}::pin::pin!"))]; |
| 113 | + replacements.extend(as_mut_span.map(|span| (span, String::new()))); |
| 114 | + |
| 115 | + diag.multipart_suggestion_verbose( |
| 116 | + "use the `pin!` macro", |
| 117 | + replacements, |
| 118 | + Applicability::MachineApplicable, |
| 119 | + ); |
| 120 | + }, |
| 121 | + ); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + extract_msrv_attr!(LateContext); |
| 127 | +} |
| 128 | + |
| 129 | +/// Checks how a `Pin<Box<_>>` is used. Returns `Continue(span)` if this use is valid with |
| 130 | +/// `Box::pin` changed to `pin!`. |
| 131 | +/// |
| 132 | +/// The span is the `.as_mut()` span that can be safely removed. |
| 133 | +/// Note that it's currently only returned if `Box::pin()` is the receiver of it (and not first |
| 134 | +/// stored in a binding) to avoid move errors. |
| 135 | +/// |
| 136 | +/// That is, `as_mut` can be safely removed here: |
| 137 | +/// ```ignore |
| 138 | +/// - Box::pin(async {}).as_mut().poll(...); |
| 139 | +/// + pin!(async {}).poll(...); |
| 140 | +/// ``` |
| 141 | +/// |
| 142 | +/// but not here, as the poll call consumes it and the binding cannot be used again in subsequent |
| 143 | +/// iterations: |
| 144 | +/// ```ignore |
| 145 | +/// - let mut bx = Box::pin(async {}); |
| 146 | +/// + let mut bx = pin!(async {}); |
| 147 | +/// loop { |
| 148 | +/// - bx.as_mut().poll(...); |
| 149 | +/// + bx.poll(...); |
| 150 | +/// } |
| 151 | +/// ``` |
| 152 | +fn check_pin_box_use<'tcx>( |
| 153 | + cx: &LateContext<'tcx>, |
| 154 | + expr: &'tcx Expr<'tcx>, |
| 155 | + moved: bool, |
| 156 | + enclosing_body: LocalDefId, |
| 157 | +) -> ControlFlow<(), Option<Span>> { |
| 158 | + match cx.tcx.parent_hir_node(expr.hir_id) { |
| 159 | + Node::Expr(as_mut_expr) |
| 160 | + if let ExprKind::MethodCall(segment, recv, [], span) = as_mut_expr.kind |
| 161 | + && recv.hir_id == expr.hir_id |
| 162 | + && segment.ident.name.as_str() == "as_mut" => |
| 163 | + { |
| 164 | + ControlFlow::Continue((!moved).then(|| span.with_lo(recv.span.hi()))) |
| 165 | + }, |
| 166 | + Node::LetStmt(LetStmt { pat, ty: None, .. }) |
| 167 | + if let PatKind::Binding(_, local_id, ..) = pat.kind |
| 168 | + && !moved => |
| 169 | + { |
| 170 | + for_each_local_use_after_expr(cx, local_id, expr.hir_id, |expr| { |
| 171 | + if check_pin_box_use(cx, expr, true, enclosing_body).is_continue() |
| 172 | + // Make sure the `Pin` is not captured by a closure. |
| 173 | + && cx.tcx.hir().enclosing_body_owner(expr.hir_id) == enclosing_body |
| 174 | + { |
| 175 | + ControlFlow::Continue(()) |
| 176 | + } else { |
| 177 | + ControlFlow::Break(()) |
| 178 | + } |
| 179 | + })?; |
| 180 | + ControlFlow::Continue(None) |
| 181 | + }, |
| 182 | + _ => ControlFlow::Break(()), |
| 183 | + } |
| 184 | +} |
0 commit comments