1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use rustc::lint::{LintPass, LintArray, LateLintPass, LateContext};
9 use utils::{match_type, paths, span_lint};
11 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
13 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
14 /// reference sequential is shooting flies with cannons.
15 /// `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are leaner and
18 /// **Known problems:** This lint cannot detect if the mutex is actually used
19 /// for waiting before a critical section.
23 /// let x = Mutex::new(&y);
28 "using a mutex where an atomic value could be used instead"
31 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral type.
33 /// **Why is this bad?** Using a mutex just to make access to a plain integer sequential is
34 /// shooting flies with cannons. `std::atomic::usize` is leaner and faster.
36 /// **Known problems:** This lint cannot detect if the mutex is actually used
37 /// for waiting before a critical section.
41 /// let x = Mutex::new(0usize);
46 "using a mutex for an integer type"
49 impl LintPass for MutexAtomic {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
55 pub struct MutexAtomic;
57 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutexAtomic {
58 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
59 let ty = cx.tcx.tables().expr_ty(expr);
60 if let ty::TyAdt(_, subst) = ty.sty {
61 if match_type(cx, ty, &paths::MUTEX) {
62 let mutex_param = &subst.type_at(0).sty;
63 if let Some(atomic_name) = get_atomic_name(mutex_param) {
64 let msg = format!("Consider using an {} instead of a Mutex here. If you just want the locking \
65 behaviour and not the internal type, consider using Mutex<()>.",
68 ty::TyUint(t) if t != ast::UintTy::Us => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
69 ty::TyInt(t) if t != ast::IntTy::Is => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
70 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
78 fn get_atomic_name(ty: &ty::TypeVariants) -> Option<(&'static str)> {
80 ty::TyBool => Some("AtomicBool"),
81 ty::TyUint(_) => Some("AtomicUsize"),
82 ty::TyInt(_) => Some("AtomicIsize"),
83 ty::TyRawPtr(_) => Some("AtomicPtr"),