1 use crate::utils::{is_type_diagnostic_item, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_hir::{Expr, ExprKind, Mutability};
4 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 /// **What it does:** Checks for `&mut Mutex::lock` calls
11 /// **Why is this bad?** `Mutex::lock` is less efficient than
12 /// calling `Mutex::get_mut`
14 /// **Known problems:** None.
19 /// use std::sync::{Arc, Mutex};
21 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
22 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
24 /// let mut value = value_mutex.lock().unwrap();
29 /// use std::sync::{Arc, Mutex};
31 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
32 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
34 /// let value = value_mutex.get_mut().unwrap();
39 "`&mut Mutex::lock` does unnecessary locking"
42 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
44 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
45 fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
47 if is_mut_mutex_lock_call(cx, ex).is_some();
53 "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
55 "use `&mut Mutex::get_mut` instead",
62 fn is_mut_mutex_lock_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
64 if let ExprKind::MethodCall(path, _span, args, _) = &expr.kind;
65 if path.ident.name == sym!(lock);
66 let ty = cx.typeck_results().expr_ty(&args[0]);
67 if let ty::Ref(_, inner_ty, Mutability::Mut) = ty.kind();
68 if is_type_diagnostic_item(cx, inner_ty, sym!(mutex_type));