1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint, lint_array};
7 use rustc::ty::{self, Ty};
10 use crate::utils::{match_type, paths, span_lint};
12 /// **What it does:** 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
15 /// reference sequential is shooting flies with cannons.
16 /// `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are leaner and
19 /// **Known problems:** This lint cannot detect if the mutex is actually used
20 /// for waiting before a critical section.
24 /// let x = Mutex::new(&y);
26 declare_clippy_lint! {
29 "using a mutex where an atomic value could be used instead"
32 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
35 /// **Why is this bad?** Using a mutex just to make access to a plain integer
37 /// shooting flies with cannons. `std::atomic::usize` is leaner and faster.
39 /// **Known problems:** This lint cannot detect if the mutex is actually used
40 /// for waiting before a critical section.
44 /// let x = Mutex::new(0usize);
46 declare_clippy_lint! {
49 "using a mutex for an integer type"
52 impl LintPass for MutexAtomic {
53 fn get_lints(&self) -> LintArray {
54 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
58 pub struct MutexAtomic;
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutexAtomic {
61 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
62 let ty = cx.tables.expr_ty(expr);
63 if let ty::TyAdt(_, subst) = ty.sty {
64 if match_type(cx, ty, &paths::MUTEX) {
65 let mutex_param = subst.type_at(0);
66 if let Some(atomic_name) = get_atomic_name(mutex_param) {
68 "Consider using an {} instead of a Mutex here. If you just want the locking \
69 behaviour and not the internal type, consider using Mutex<()>.",
72 match mutex_param.sty {
73 ty::TyUint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
74 ty::TyInt(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
75 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
83 fn get_atomic_name(ty: Ty<'_>) -> Option<(&'static str)> {
85 ty::TyBool => Some("AtomicBool"),
86 ty::TyUint(_) => Some("AtomicUsize"),
87 ty::TyInt(_) => Some("AtomicIsize"),
88 ty::TyRawPtr(_) => Some("AtomicPtr"),