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};
6 use rustc::ty::subst::ParamSpace;
10 use utils::{match_type, paths, span_lint};
12 /// **What it does:** This lint 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 reference sequential
15 /// is shooting flies with cannons. `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are
16 /// leaner and faster.
18 /// **Known problems:** This lint cannot detect if the mutex is actually used for waiting before a critical section.
22 /// let x = Mutex::new(&y);
27 "using a mutex where an atomic value could be used instead"
30 /// **What it does:** This lint checks for usages of `Mutex<X>` where `X` is an integral type.
32 /// **Why is this bad?** Using a mutex just to make access to a plain integer sequential is
33 /// shooting flies with cannons. `std::atomic::usize` is leaner and faster.
35 /// **Known problems:** This lint cannot detect if the mutex is actually used for waiting before a critical section.
39 /// let x = Mutex::new(0usize);
44 "using a mutex for an integer type"
47 impl LintPass for MutexAtomic {
48 fn get_lints(&self) -> LintArray {
49 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
53 pub struct MutexAtomic;
55 impl LateLintPass for MutexAtomic {
56 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
57 let ty = cx.tcx.expr_ty(expr);
58 if let ty::TyStruct(_, subst) = ty.sty {
59 if match_type(cx, ty, &paths::MUTEX) {
60 let mutex_param = &subst.types.get(ParamSpace::TypeSpace, 0).sty;
61 if let Some(atomic_name) = get_atomic_name(mutex_param) {
62 let msg = format!("Consider using an {} instead of a Mutex here. If you just want the locking \
63 behaviour and not the internal type, consider using Mutex<()>.",
66 ty::TyUint(t) if t != ast::UintTy::Us => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
67 ty::TyInt(t) if t != ast::IntTy::Is => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
68 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
76 fn get_atomic_name(ty: &ty::TypeVariants) -> Option<(&'static str)> {
78 ty::TyBool => Some("AtomicBool"),
79 ty::TyUint(_) => Some("AtomicUsize"),
80 ty::TyInt(_) => Some("AtomicIsize"),
81 ty::TyRawPtr(_) => Some("AtomicPtr"),