1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use crate::utils::{match_type, paths, span_lint};
6 use rustc::declare_lint_pass;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::ty::{self, Ty};
10 use rustc_session::declare_tool_lint;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
16 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
17 /// reference sequential is shooting flies with cannons.
18 /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and
21 /// **Known problems:** This lint cannot detect if the mutex is actually used
22 /// for waiting before a critical section.
26 /// # use std::sync::Mutex;
28 /// let x = Mutex::new(&y);
32 "using a mutex where an atomic value could be used instead"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
39 /// **Why is this bad?** Using a mutex just to make access to a plain integer
41 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
43 /// **Known problems:** This lint cannot detect if the mutex is actually used
44 /// for waiting before a critical section.
48 /// # use std::sync::Mutex;
49 /// let x = Mutex::new(0usize);
53 "using a mutex for an integer type"
56 declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]);
58 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Mutex {
59 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
60 let ty = cx.tables.expr_ty(expr);
61 if let ty::Adt(_, subst) = ty.kind {
62 if match_type(cx, ty, &paths::MUTEX) {
63 let mutex_param = subst.type_at(0);
64 if let Some(atomic_name) = get_atomic_name(mutex_param) {
66 "Consider using an {} instead of a Mutex here. If you just want the locking \
67 behaviour and not the internal type, consider using Mutex<()>.",
70 match mutex_param.kind {
71 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
72 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
73 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
81 fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> {
83 ty::Bool => Some("AtomicBool"),
84 ty::Uint(_) => Some("AtomicUsize"),
85 ty::Int(_) => Some("AtomicIsize"),
86 ty::RawPtr(_) => Some("AtomicPtr"),