]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mut_mutex_lock.rs
Replace `&mut DiagnosticBuilder`, in signatures, with `&mut Diagnostic`.
[rust.git] / src / tools / clippy / clippy_lints / src / mut_mutex_lock.rs
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};
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::sym;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for `&mut Mutex::lock` calls
14     ///
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
19     /// guarantee.
20     ///
21     /// ### Example
22     /// ```rust
23     /// use std::sync::{Arc, Mutex};
24     ///
25     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
26     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
27     ///
28     /// let mut value = value_mutex.lock().unwrap();
29     /// *value += 1;
30     /// ```
31     /// Use instead:
32     /// ```rust
33     /// use std::sync::{Arc, Mutex};
34     ///
35     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
36     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
37     ///
38     /// let value = value_mutex.get_mut().unwrap();
39     /// *value += 1;
40     /// ```
41     #[clippy::version = "1.49.0"]
42     pub MUT_MUTEX_LOCK,
43     style,
44     "`&mut Mutex::lock` does unnecessary locking"
45 }
46
47 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
48
49 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
51         if_chain! {
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);
57             then {
58                 span_lint_and_sugg(
59                     cx,
60                     MUT_MUTEX_LOCK,
61                     path.ident.span,
62                     "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
63                     "change this to",
64                     "get_mut".to_owned(),
65                     Applicability::MaybeIncorrect,
66                 );
67             }
68         }
69     }
70 }