1 use crate::utils::{is_type_diagnostic_item, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind, Mutability};
5 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// **What it does:** Checks for `&mut Mutex::lock` calls
12 /// **Why is this bad?** `Mutex::lock` is less efficient than
13 /// calling `Mutex::get_mut`. In addition you also have a statically
14 /// guarantee that the mutex isn't locked, instead of just a runtime
17 /// **Known problems:** None.
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,