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