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.
10 //! Checks for uses of mutex where an atomic value could be used
12 //! This lint is **warn** by default
14 use crate::rustc::hir::Expr;
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::ty::{self, Ty};
17 use crate::rustc::{declare_tool_lint, lint_array};
18 use crate::syntax::ast;
19 use crate::utils::{match_type, paths, span_lint};
21 /// **What it does:** Checks for usages of `Mutex<X>` where an atomic will do.
23 /// **Why is this bad?** Using a mutex just to make access to a plain bool or
24 /// reference sequential is shooting flies with cannons.
25 /// `std::atomic::AtomicBool` and `std::atomic::AtomicPtr` are leaner and
28 /// **Known problems:** This lint cannot detect if the mutex is actually used
29 /// for waiting before a critical section.
33 /// let x = Mutex::new(&y);
35 declare_clippy_lint! {
38 "using a mutex where an atomic value could be used instead"
41 /// **What it does:** Checks for usages of `Mutex<X>` where `X` is an integral
44 /// **Why is this bad?** Using a mutex just to make access to a plain integer
46 /// shooting flies with cannons. `std::atomic::usize` is leaner and faster.
48 /// **Known problems:** This lint cannot detect if the mutex is actually used
49 /// for waiting before a critical section.
53 /// let x = Mutex::new(0usize);
55 declare_clippy_lint! {
58 "using a mutex for an integer type"
61 impl LintPass for MutexAtomic {
62 fn get_lints(&self) -> LintArray {
63 lint_array!(MUTEX_ATOMIC, MUTEX_INTEGER)
67 pub struct MutexAtomic;
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutexAtomic {
70 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
71 let ty = cx.tables.expr_ty(expr);
72 if let ty::Adt(_, subst) = ty.sty {
73 if match_type(cx, ty, &paths::MUTEX) {
74 let mutex_param = subst.type_at(0);
75 if let Some(atomic_name) = get_atomic_name(mutex_param) {
77 "Consider using an {} instead of a Mutex here. If you just want the locking \
78 behaviour and not the internal type, consider using Mutex<()>.",
81 match mutex_param.sty {
82 ty::Uint(t) if t != ast::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
83 ty::Int(t) if t != ast::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg),
84 _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg),
92 fn get_atomic_name(ty: Ty<'_>) -> Option<(&'static str)> {
94 ty::Bool => Some("AtomicBool"),
95 ty::Uint(_) => Some("AtomicUsize"),
96 ty::Int(_) => Some("AtomicIsize"),
97 ty::RawPtr(_) => Some("AtomicPtr"),