1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind, Mutability};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
13 /// Checks for `&mut Mutex::lock` calls
15 /// ### Why is this bad?
16 /// `Mutex::lock` is less efficient than
17 /// calling `Mutex::get_mut`. In addition you also have a statically
18 /// guarantee that the mutex isn't locked, instead of just a runtime
23 /// use std::sync::{Arc, Mutex};
25 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
26 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
28 /// let mut value = value_mutex.lock().unwrap();
33 /// use std::sync::{Arc, Mutex};
35 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
36 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
38 /// let value = value_mutex.get_mut().unwrap();
41 #[clippy::version = "1.49.0"]
44 "`&mut Mutex::lock` does unnecessary locking"
47 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
49 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
50 fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
52 if let ExprKind::MethodCall(path, [self_arg, ..], _) = &ex.kind;
53 if path.ident.name == sym!(lock);
54 let ty = cx.typeck_results().expr_ty(self_arg);
55 if let ty::Ref(_, inner_ty, Mutability::Mut) = ty.kind();
56 if is_type_diagnostic_item(cx, inner_ty, sym::Mutex);
62 "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
65 Applicability::MaybeIncorrect,