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_front::hir::Expr;
10 use rustc::middle::subst::ParamSpace;
12 use utils::{span_lint, MUTEX_PATH, match_type};
14 /// **What it does:** It `Warn`s on 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 reference sequential is shooting flies with cannons. `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are leaner and faster.
18 /// **Known problems:** This lint cannot detect if the Mutex is actually used for waiting before a critical section.
20 /// **Example:** `let x = Mutex::new(&y);`
24 "using a Mutex where an atomic value could be used instead"
27 /// **What it does:** It `Warn`s on usages of `Mutex<X>` where `X` is an integral type.
29 /// **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.
31 /// **Known problems:** This lint cannot detect if the Mutex is actually used for waiting before a critical section.
33 /// **Example:** `let x = Mutex::new(0usize);`
37 "using a Mutex for an integer type"
40 impl LintPass for MutexAtomic {
41 fn get_lints(&self) -> LintArray {
42 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
46 pub struct MutexAtomic;
48 impl LateLintPass for MutexAtomic {
49 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
50 let ty = cx.tcx.expr_ty(expr);
51 if let ty::TyStruct(_, subst) = ty.sty {
52 if match_type(cx, ty, &MUTEX_PATH) {
53 let mutex_param = &subst.types.get(ParamSpace::TypeSpace, 0).sty;
54 if let Some(atomic_name) = get_atomic_name(mutex_param) {
55 let msg = format!("Consider using an {} instead of a \
56 Mutex here. If you just want the \
57 locking behaviour and not the internal \
58 type, consider using Mutex<()>.",
61 ty::TyUint(t) if t != ast::TyUs =>
62 span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
63 ty::TyInt(t) if t != ast::TyIs =>
64 span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
65 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg)
73 fn get_atomic_name(ty: &ty::TypeVariants) -> Option<(&'static str)> {
75 ty::TyBool => Some("AtomicBool"),
76 ty::TyUint(_) => Some("AtomicUsize"),
77 ty::TyInt(_) => Some("AtomicIsize"),
78 ty::TyRawPtr(_) => Some("AtomicPtr"),