1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use crate::utils::{is_type_diagnostic_item, span_lint};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::{self, Ty};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
15 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
16 /// reference sequential is shooting flies with cannons.
17 /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and
20 /// **Known problems:** This lint cannot detect if the mutex is actually used
21 /// for waiting before a critical section.
25 /// # use std::sync::Mutex;
27 /// let x = Mutex::new(&y);
31 "using a mutex where an atomic value could be used instead"
34 declare_clippy_lint! {
35 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
38 /// **Why is this bad?** Using a mutex just to make access to a plain integer
40 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
42 /// **Known problems:** This lint cannot detect if the mutex is actually used
43 /// for waiting before a critical section.
47 /// # use std::sync::Mutex;
48 /// let x = Mutex::new(0usize);
52 "using a mutex for an integer type"
55 declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]);
57 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Mutex {
58 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
59 let ty = cx.tables.expr_ty(expr);
60 if let ty::Adt(_, subst) = ty.kind {
61 if is_type_diagnostic_item(cx, ty, sym!(mutex_type)) {
62 let mutex_param = subst.type_at(0);
63 if let Some(atomic_name) = get_atomic_name(mutex_param) {
65 "Consider using an `{}` instead of a `Mutex` here. If you just want the locking \
66 behavior and not the internal type, consider using `Mutex<()>`.",
69 match mutex_param.kind {
70 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
71 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
72 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
80 fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> {
82 ty::Bool => Some("AtomicBool"),
83 ty::Uint(_) => Some("AtomicUsize"),
84 ty::Int(_) => Some("AtomicIsize"),
85 ty::RawPtr(_) => Some("AtomicPtr"),