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.
28 /// # use std::sync::Mutex;
29 /// let x = Mutex::new(&y);
32 /// # use std::sync::atomic::AtomicBool;
33 /// let x = AtomicBool::new(y);
37 "using a mutex where an atomic value could be used instead"
40 declare_clippy_lint! {
41 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
44 /// **Why is this bad?** Using a mutex just to make access to a plain integer
46 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
48 /// **Known problems:** This lint cannot detect if the mutex is actually used
49 /// for waiting before a critical section.
53 /// # use std::sync::Mutex;
54 /// let x = Mutex::new(0usize);
57 /// # use std::sync::atomic::AtomicUsize;
58 /// let x = AtomicUsize::new(0usize);
62 "using a mutex for an integer type"
65 declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]);
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Mutex {
68 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
69 let ty = cx.tables.expr_ty(expr);
70 if let ty::Adt(_, subst) = ty.kind {
71 if is_type_diagnostic_item(cx, ty, sym!(mutex_type)) {
72 let mutex_param = subst.type_at(0);
73 if let Some(atomic_name) = get_atomic_name(mutex_param) {
75 "Consider using an `{}` instead of a `Mutex` here. If you just want the locking \
76 behavior and not the internal type, consider using `Mutex<()>`.",
79 match mutex_param.kind {
80 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
81 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
82 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
90 fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> {
92 ty::Bool => Some("AtomicBool"),
93 ty::Uint(_) => Some("AtomicUsize"),
94 ty::Int(_) => Some("AtomicIsize"),
95 ty::RawPtr(_) => Some("AtomicPtr"),