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};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::{self, Ty};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
12 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
14 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
15 /// reference sequential is shooting flies with cannons.
16 /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and
19 /// **Known problems:** This lint cannot detect if the mutex is actually used
20 /// for waiting before a critical section.
27 /// # use std::sync::Mutex;
28 /// let x = Mutex::new(&y);
31 /// # use std::sync::atomic::AtomicBool;
32 /// let x = AtomicBool::new(y);
36 "using a mutex where an atomic value could be used instead"
39 declare_clippy_lint! {
40 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
43 /// **Why is this bad?** Using a mutex just to make access to a plain integer
45 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
47 /// **Known problems:** This lint cannot detect if the mutex is actually used
48 /// for waiting before a critical section.
52 /// # use std::sync::Mutex;
53 /// let x = Mutex::new(0usize);
56 /// # use std::sync::atomic::AtomicUsize;
57 /// let x = AtomicUsize::new(0usize);
61 "using a mutex for an integer type"
64 declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]);
66 impl<'tcx> LateLintPass<'tcx> for Mutex {
67 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
68 let ty = cx.typeck_results().expr_ty(expr);
69 if let ty::Adt(_, subst) = ty.kind() {
70 if is_type_diagnostic_item(cx, ty, sym!(mutex_type)) {
71 let mutex_param = subst.type_at(0);
72 if let Some(atomic_name) = get_atomic_name(mutex_param) {
74 "consider using an `{}` instead of a `Mutex` here; if you just want the locking \
75 behavior and not the internal type, consider using `Mutex<()>`",
78 match *mutex_param.kind() {
79 ty::Uint(t) if t != ty::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
80 ty::Int(t) if t != ty::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
81 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
89 fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> {
91 ty::Bool => Some("AtomicBool"),
92 ty::Uint(_) => Some("AtomicUsize"),
93 ty::Int(_) => Some("AtomicIsize"),
94 ty::RawPtr(_) => Some("AtomicPtr"),