1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! Checks for uses of mutex where an atomic value could be used
13 //! This lint is **warn** by default
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::{declare_tool_lint, lint_array};
17 use crate::rustc::ty::{self, Ty};
18 use crate::rustc::hir::Expr;
19 use crate::syntax::ast;
20 use crate::utils::{match_type, paths, span_lint};
22 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
24 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
25 /// reference sequential is shooting flies with cannons.
26 /// `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are leaner and
29 /// **Known problems:** This lint cannot detect if the mutex is actually used
30 /// for waiting before a critical section.
34 /// let x = Mutex::new(&y);
36 declare_clippy_lint! {
39 "using a mutex where an atomic value could be used instead"
42 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
45 /// **Why is this bad?** Using a mutex just to make access to a plain integer
47 /// shooting flies with cannons. `std::atomic::usize` is leaner and faster.
49 /// **Known problems:** This lint cannot detect if the mutex is actually used
50 /// for waiting before a critical section.
54 /// let x = Mutex::new(0usize);
56 declare_clippy_lint! {
59 "using a mutex for an integer type"
62 impl LintPass for MutexAtomic {
63 fn get_lints(&self) -> LintArray {
64 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
68 pub struct MutexAtomic;
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutexAtomic {
71 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
72 let ty = cx.tables.expr_ty(expr);
73 if let ty::Adt(_, subst) = ty.sty {
74 if match_type(cx, ty, &paths::MUTEX) {
75 let mutex_param = subst.type_at(0);
76 if let Some(atomic_name) = get_atomic_name(mutex_param) {
78 "Consider using an {} instead of a Mutex here. If you just want the locking \
79 behaviour and not the internal type, consider using Mutex<()>.",
82 match mutex_param.sty {
83 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
84 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
85 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
93 fn get_atomic_name(ty: Ty<'_>) -> Option<(&'static str)> {
95 ty::Bool => Some("AtomicBool"),
96 ty::Uint(_) => Some("AtomicUsize"),
97 ty::Int(_) => Some("AtomicIsize"),
98 ty::RawPtr(_) => Some("AtomicPtr"),