|
| 1 | +use super::READONLY_WRITE_LOCK; |
| 2 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 3 | +use clippy_utils::mir::{enclosing_mir, visit_local_usage}; |
| 4 | +use clippy_utils::source::snippet; |
| 5 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::{Expr, ExprKind, Node}; |
| 8 | +use rustc_lint::LateContext; |
| 9 | +use rustc_middle::mir::{Location, START_BLOCK}; |
| 10 | +use rustc_span::sym; |
| 11 | + |
| 12 | +fn is_unwrap_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 13 | + if let ExprKind::MethodCall(path, receiver, ..) = expr.kind |
| 14 | + && path.ident.name == sym::unwrap |
| 15 | + { |
| 16 | + is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(receiver).peel_refs(), sym::Result) |
| 17 | + } else { |
| 18 | + false |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, receiver: &Expr<'_>) { |
| 23 | + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(receiver).peel_refs(), sym::RwLock) |
| 24 | + && let Node::Expr(unwrap_call_expr) = cx.tcx.hir().get_parent(expr.hir_id) |
| 25 | + && is_unwrap_call(cx, unwrap_call_expr) |
| 26 | + && let parent = cx.tcx.hir().get_parent(unwrap_call_expr.hir_id) |
| 27 | + && let Node::Local(local) = parent |
| 28 | + && let Some(mir) = enclosing_mir(cx.tcx, expr.hir_id) |
| 29 | + && let Some((local, _)) = mir.local_decls.iter_enumerated().find(|(_, decl)| { |
| 30 | + local.span.contains(decl.source_info.span) |
| 31 | + }) |
| 32 | + && let Some(usages) = visit_local_usage(&[local], mir, Location { |
| 33 | + block: START_BLOCK, |
| 34 | + statement_index: 0, |
| 35 | + }) |
| 36 | + && let [usage] = usages.as_slice() |
| 37 | + { |
| 38 | + let writer_never_mutated = usage.local_consume_or_mutate_locs.is_empty(); |
| 39 | + |
| 40 | + if writer_never_mutated { |
| 41 | + span_lint_and_sugg( |
| 42 | + cx, |
| 43 | + READONLY_WRITE_LOCK, |
| 44 | + expr.span, |
| 45 | + "this write lock is used only for reading", |
| 46 | + "consider using a read lock instead", |
| 47 | + format!("{}.read()", snippet(cx, receiver.span, "<receiver>")), |
| 48 | + Applicability::MaybeIncorrect // write lock might be intentional for enforcing exclusiveness |
| 49 | + ); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments