1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use clippy_utils::diagnostics::span_lint;
6 use clippy_utils::ty::is_type_diagnostic_item;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::{self, Ty};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 declare_clippy_lint! {
15 /// Checks for usages of `Mutex<X>` where an atomic will do.
17 /// ### Why is this bad?
18 /// Using a mutex just to make access to a plain bool or
19 /// reference sequential is shooting flies with cannons.
20 /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and
23 /// ### Known problems
24 /// This lint cannot detect if the mutex is actually used
25 /// for waiting before a critical section.
32 /// # use std::sync::Mutex;
33 /// let x = Mutex::new(&y);
36 /// # use std::sync::atomic::AtomicBool;
37 /// let x = AtomicBool::new(y);
39 #[clippy::version = "pre 1.29.0"]
42 "using a mutex where an atomic value could be used instead"
45 declare_clippy_lint! {
47 /// Checks for usages of `Mutex<X>` where `X` is an integral
50 /// ### Why is this bad?
51 /// Using a mutex just to make access to a plain integer
53 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
55 /// ### Known problems
56 /// This lint cannot detect if the mutex is actually used
57 /// for waiting before a critical section.
61 /// # use std::sync::Mutex;
62 /// let x = Mutex::new(0usize);
65 /// # use std::sync::atomic::AtomicUsize;
66 /// let x = AtomicUsize::new(0usize);
68 #[clippy::version = "pre 1.29.0"]
71 "using a mutex for an integer type"
74 declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]);
76 impl<'tcx> LateLintPass<'tcx> for Mutex {
77 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
78 let ty = cx.typeck_results().expr_ty(expr);
79 if let ty::Adt(_, subst) = ty.kind() {
80 if is_type_diagnostic_item(cx, ty, sym::Mutex) {
81 let mutex_param = subst.type_at(0);
82 if let Some(atomic_name) = get_atomic_name(mutex_param) {
84 "consider using an `{}` instead of a `Mutex` here; if you just want the locking \
85 behavior and not the internal type, consider using `Mutex<()>`",
88 match *mutex_param.kind() {
89 ty::Uint(t) if t != ty::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
90 ty::Int(t) if t != ty::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
91 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
99 fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> {
101 ty::Bool => Some("AtomicBool"),
102 ty::Uint(_) => Some("AtomicUsize"),
103 ty::Int(_) => Some("AtomicIsize"),
104 ty::RawPtr(_) => Some("AtomicPtr"),