]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mut_mutex_lock.rs
Update lint documentation to use markdown headlines
[rust.git] / 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
12     /// Checks for `&mut Mutex::lock` calls
13     ///
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
18     /// guarantee.
19     ///
20     /// ### Example
21     /// ```rust
22     /// use std::sync::{Arc, Mutex};
23     ///
24     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
25     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
26     ///
27     /// let mut value = value_mutex.lock().unwrap();
28     /// *value += 1;
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// use std::sync::{Arc, Mutex};
33     ///
34     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
35     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
36     ///
37     /// let value = value_mutex.get_mut().unwrap();
38     /// *value += 1;
39     /// ```
40     pub MUT_MUTEX_LOCK,
41     style,
42     "`&mut Mutex::lock` does unnecessary locking"
43 }
44
45 declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
46
47 impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
48     fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
49         if_chain! {
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));
55             then {
56                 span_lint_and_sugg(
57                     cx,
58                     MUT_MUTEX_LOCK,
59                     *method_span,
60                     "calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
61                     "change this to",
62                     "get_mut".to_owned(),
63                     Applicability::MaybeIncorrect,
64                 );
65             }
66         }
67     }
68 }