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};
10 declare_clippy_lint! {
12 /// Checks for `&mut Mutex::lock` calls
14 /// ### Why is this bad?
15 /// `Mutex::lock` is less efficient than
16 /// calling `Mutex::get_mut`. In addition you also have a statically
17 /// guarantee that the mutex isn't locked, instead of just a runtime
22 /// use std::sync::{Arc, Mutex};
24 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
25 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
27 /// let mut value = value_mutex.lock().unwrap();
32 /// use std::sync::{Arc, Mutex};
34 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
35 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
37 /// let value = value_mutex.get_mut().unwrap();
42 "`&mut Mutex::lock` does unnecessary locking"
45 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
47 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
48 fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
50 if let ExprKind::MethodCall(path, method_span, args, _) = &ex.kind;
51 if path.ident.name == sym!(lock);
52 let ty = cx.typeck_results().expr_ty(&args[0]);
53 if let ty::Ref(_, inner_ty, Mutability::Mut) = ty.kind();
54 if is_type_diagnostic_item(cx, inner_ty, sym!(mutex_type));
60 "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
63 Applicability::MaybeIncorrect,