1 //! Checks for uses of mutex where an atomic value could be used
3 //! This lint is **warn** by default
5 use crate::utils::{match_type, paths, span_lint};
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::ty::{self, Ty};
9 use rustc::{declare_tool_lint, lint_array};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
15 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
16 /// reference sequential is shooting flies with cannons.
17 /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and
20 /// **Known problems:** This lint cannot detect if the mutex is actually used
21 /// for waiting before a critical section.
25 /// let x = Mutex::new(&y);
29 "using a mutex where an atomic value could be used instead"
32 declare_clippy_lint! {
33 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
36 /// **Why is this bad?** Using a mutex just to make access to a plain integer
38 /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.
40 /// **Known problems:** This lint cannot detect if the mutex is actually used
41 /// for waiting before a critical section.
45 /// let x = Mutex::new(0usize);
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)
57 fn name(&self) -> &'static str {
62 pub struct MutexAtomic;
64 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutexAtomic {
65 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
66 let ty = cx.tables.expr_ty(expr);
67 if let ty::Adt(_, subst) = ty.sty {
68 if match_type(cx, ty, &paths::MUTEX) {
69 let mutex_param = subst.type_at(0);
70 if let Some(atomic_name) = get_atomic_name(mutex_param) {
72 "Consider using an {} instead of a Mutex here. If you just want the locking \
73 behaviour and not the internal type, consider using Mutex<()>.",
76 match mutex_param.sty {
77 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
78 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
79 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
87 fn get_atomic_name(ty: Ty<'_>) -> Option<(&'static str)> {
89 ty::Bool => Some("AtomicBool"),
90 ty::Uint(_) => Some("AtomicUsize"),
91 ty::Int(_) => Some("AtomicIsize"),
92 ty::RawPtr(_) => Some("AtomicPtr"),