]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mut_mutex_lock.rs
Rollup merge of #85760 - ChrisDenton:path-doc-platform-specific, r=m-ou-se
[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
10 declare_clippy_lint! {
11     /// **What it does:** Checks for `&mut Mutex::lock` calls
12     ///
13     /// **Why is this bad?** `Mutex::lock` is less efficient than
14     /// calling `Mutex::get_mut`. In addition you also have a statically
15     /// guarantee that the mutex isn't locked, instead of just a runtime
16     /// guarantee.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     ///
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     pub MUT_MUTEX_LOCK,
42     style,
43     "`&mut Mutex::lock` does unnecessary locking"
44 }
45
46 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
47
48 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
49     fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
50         if_chain! {
51             if let ExprKind::MethodCall(path, method_span, args, _) = &ex.kind;
52             if path.ident.name == sym!(lock);
53             let ty = cx.typeck_results().expr_ty(&args[0]);
54             if let ty::Ref(_, inner_ty, Mutability::Mut) = ty.kind();
55             if is_type_diagnostic_item(cx, inner_ty, sym!(mutex_type));
56             then {
57                 span_lint_and_sugg(
58                     cx,
59                     MUT_MUTEX_LOCK,
60                     *method_span,
61                     "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
62                     "change this to",
63                     "get_mut".to_owned(),
64                     Applicability::MaybeIncorrect,
65                 );
66             }
67         }
68     }
69 }