summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs
blob: 8412875b11b7ecbfae00e57166f5712f5a61307c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
            );
        }
    }
}