diff options
| author | flip1995 <philipp.krones@embecosm.com> | 2022-03-14 12:02:53 +0100 |
|---|---|---|
| committer | flip1995 <philipp.krones@embecosm.com> | 2022-03-14 12:02:53 +0100 |
| commit | d1b087fdee1024e11498e2d6c3e36d31e9371d3b (patch) | |
| tree | 456706ef4a9c850735a01d42886d38fc997400a4 /clippy_lints/src/loops/missing_spin_loop.rs | |
| parent | e1102312608f7d41160a37a3f7e60f88f87c046f (diff) | |
Merge commit 'dc5423ad448877e33cca28db2f1445c9c4473c75' into clippyup
Diffstat (limited to 'clippy_lints/src/loops/missing_spin_loop.rs')
| -rw-r--r-- | clippy_lints/src/loops/missing_spin_loop.rs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/clippy_lints/src/loops/missing_spin_loop.rs b/clippy_lints/src/loops/missing_spin_loop.rs new file mode 100644 index 00000000000..0696afa3922 --- /dev/null +++ b/clippy_lints/src/loops/missing_spin_loop.rs @@ -0,0 +1,56 @@ +use super::MISSING_SPIN_LOOP; +use clippy_utils::diagnostics::span_lint_and_sugg; +use clippy_utils::is_no_std_crate; +use rustc_errors::Applicability; +use rustc_hir::{Block, Expr, ExprKind}; +use rustc_lint::LateContext; +use rustc_middle::ty; +use rustc_span::sym; + +fn unpack_cond<'tcx>(cond: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> { + match &cond.kind { + ExprKind::Block( + Block { + stmts: [], + expr: Some(e), + .. + }, + _, + ) + | ExprKind::Unary(_, e) => unpack_cond(e), + ExprKind::Binary(_, l, r) => { + let l = unpack_cond(l); + if let ExprKind::MethodCall(..) = l.kind { + l + } else { + unpack_cond(r) + } + }, + _ => cond, + } +} + +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, body: &'tcx Expr<'_>) { + if_chain! { + if let ExprKind::Block(Block { stmts: [], expr: None, ..}, _) = body.kind; + if let ExprKind::MethodCall(method, [callee, ..], _) = unpack_cond(cond).kind; + if [sym::load, sym::compare_exchange, sym::compare_exchange_weak].contains(&method.ident.name); + if let ty::Adt(def, _substs) = cx.typeck_results().expr_ty(callee).kind(); + if cx.tcx.is_diagnostic_item(sym::AtomicBool, def.did()); + then { + span_lint_and_sugg( + cx, + MISSING_SPIN_LOOP, + body.span, + "busy-waiting loop should at least have a spin loop hint", + "try this", + (if is_no_std_crate(cx) { + "{ core::hint::spin_loop() }" + } else { + "{ std::hint::spin_loop() }" + }).into(), + Applicability::MachineApplicable + ); + } + } +} |
