rust/clippy_lints/src/mut_mutex_lock.rs

69 lines
2.3 KiB
Rust
Raw Normal View History

2020-10-10 05:07:47 -05:00
use crate::utils::{is_type_diagnostic_item, span_lint_and_sugg};
2020-10-01 20:05:30 -05:00
use if_chain::if_chain;
2020-10-10 05:07:47 -05:00
use rustc_errors::Applicability;
2020-10-01 20:05:30 -05:00
use rustc_hir::{Expr, ExprKind, Mutability};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// **What it does:** Checks for `&mut Mutex::lock` calls
///
/// **Why is this bad?** `Mutex::lock` is less efficient than
2020-10-10 05:07:47 -05:00
/// calling `Mutex::get_mut`. In addition you also have a statically
/// guarantee that the mutex isn't locked, instead of just a runtime
/// guarantee.
2020-10-01 20:05:30 -05:00
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```rust
/// use std::sync::{Arc, Mutex};
///
/// let mut value_rc = Arc::new(Mutex::new(42_u8));
/// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
///
2020-10-01 21:54:44 -05:00
/// let mut value = value_mutex.lock().unwrap();
/// *value += 1;
2020-10-01 20:05:30 -05:00
/// ```
/// Use instead:
/// ```rust
/// use std::sync::{Arc, Mutex};
///
/// let mut value_rc = Arc::new(Mutex::new(42_u8));
/// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
///
/// let value = value_mutex.get_mut().unwrap();
2020-10-01 21:54:44 -05:00
/// *value += 1;
2020-10-01 20:05:30 -05:00
/// ```
pub MUT_MUTEX_LOCK,
style,
2020-10-01 20:05:30 -05:00
"`&mut Mutex::lock` does unnecessary locking"
}
declare_lint_pass!(MutMutexLock => [MUT_MUTEX_LOCK]);
impl<'tcx> LateLintPass<'tcx> for MutMutexLock {
fn check_expr(&mut self, cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>) {
if_chain! {
2020-10-10 05:07:47 -05:00
if let ExprKind::MethodCall(path, method_span, args, _) = &ex.kind;
2020-10-04 22:44:54 -05:00
if path.ident.name == sym!(lock);
let ty = cx.typeck_results().expr_ty(&args[0]);
if let ty::Ref(_, inner_ty, Mutability::Mut) = ty.kind();
if is_type_diagnostic_item(cx, inner_ty, sym!(mutex_type));
2020-10-01 20:05:30 -05:00
then {
2020-10-10 05:07:47 -05:00
span_lint_and_sugg(
2020-10-01 20:05:30 -05:00
cx,
MUT_MUTEX_LOCK,
2020-10-10 05:07:47 -05:00
*method_span,
2020-10-01 20:05:30 -05:00
"calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference",
2020-10-10 05:07:47 -05:00
"change this to",
"get_mut".to_owned(),
Applicability::MaybeIncorrect,
2020-10-01 20:05:30 -05:00
);
}
}
}
}