|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::res::MaybeDef; |
| 3 | +use clippy_utils::source::{IntoSpan, SpanRangeExt}; |
| 4 | +use clippy_utils::sugg::Sugg; |
| 5 | +use clippy_utils::ty::ty_from_hir_ty; |
| 6 | +use rustc_errors::{Applicability, Diag}; |
| 7 | +use rustc_hir::{self as hir, Expr, ExprKind, Item, ItemKind, LetStmt, QPath}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 9 | +use rustc_middle::mir::Mutability; |
| 10 | +use rustc_middle::ty::{self, IntTy, Ty, UintTy}; |
| 11 | +use rustc_session::declare_lint_pass; |
| 12 | +use rustc_span::sym; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Checks for usage of `RwLock<X>` where an atomic will do. |
| 17 | + /// |
| 18 | + /// ### Why restrict this? |
| 19 | + /// Using a RwLock just to make access to a plain bool or |
| 20 | + /// reference sequential is shooting flies with cannons. |
| 21 | + /// `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and |
| 22 | + /// faster. |
| 23 | + /// |
| 24 | + /// On the other hand, `RwLock`s are, in general, easier to |
| 25 | + /// verify correctness. An atomic does not behave the same as |
| 26 | + /// an equivalent RwLock. |
| 27 | + /// |
| 28 | + /// ### Example |
| 29 | + /// ```no_run |
| 30 | + /// # let y = true; |
| 31 | + /// # use std::sync::RwLock; |
| 32 | + /// let x = RwLock::new(&y); |
| 33 | + /// ``` |
| 34 | + /// |
| 35 | + /// Use instead: |
| 36 | + /// ```no_run |
| 37 | + /// # let y = true; |
| 38 | + /// # use std::sync::atomic::AtomicBool; |
| 39 | + /// let x = AtomicBool::new(y); |
| 40 | + /// ``` |
| 41 | + #[clippy::version = "1.90.0"] |
| 42 | + pub RWLOCK_ATOMIC, |
| 43 | + restriction, |
| 44 | + "using a RwLock where an atomic value could be used instead." |
| 45 | +} |
| 46 | + |
| 47 | +declare_clippy_lint! { |
| 48 | + /// ### What it does |
| 49 | + /// Checks for usage of `RwLock<X>` where `X` is an integral |
| 50 | + /// type. |
| 51 | + /// |
| 52 | + /// ### Why restrict this? |
| 53 | + /// Using a RwLock just to make access to a plain integer |
| 54 | + /// sequential is |
| 55 | + /// shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster. |
| 56 | + /// |
| 57 | + /// On the other hand, `RwLock`s are, in general, easier to |
| 58 | + /// verify correctness. An atomic does not behave the same as |
| 59 | + /// an equivalent RwLock. |
| 60 | + /// |
| 61 | + /// ### Example |
| 62 | + /// ```no_run |
| 63 | + /// # use std::sync::RwLock; |
| 64 | + /// let x = RwLock::new(0usize); |
| 65 | + /// ``` |
| 66 | + /// |
| 67 | + /// Use instead: |
| 68 | + /// ```no_run |
| 69 | + /// # use std::sync::atomic::AtomicUsize; |
| 70 | + /// let x = AtomicUsize::new(0usize); |
| 71 | + /// ``` |
| 72 | + #[clippy::version = "1.90.0"] |
| 73 | + pub RWLOCK_INTEGER, |
| 74 | + restriction, |
| 75 | + "using a RwLock for an integer type" |
| 76 | +} |
| 77 | + |
| 78 | +declare_lint_pass!(RwLock => [RWLOCK_ATOMIC, RWLOCK_INTEGER]); |
| 79 | + |
| 80 | +// NOTE: we don't use `check_expr` because that would make us lint every _use_ of such RwLocks, not |
| 81 | +// just their definitions |
| 82 | +impl<'tcx> LateLintPass<'tcx> for RwLock { |
| 83 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { |
| 84 | + if !item.span.from_expansion() |
| 85 | + && let ItemKind::Static(_, _, ty, body_id) = item.kind |
| 86 | + { |
| 87 | + let body = cx.tcx.hir_body(body_id); |
| 88 | + let mid_ty = ty_from_hir_ty(cx, ty); |
| 89 | + check_expr(cx, body.value.peel_blocks(), &TypeAscriptionKind::Required(ty), mid_ty); |
| 90 | + } |
| 91 | + } |
| 92 | + fn check_local(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx LetStmt<'_>) { |
| 93 | + if !stmt.span.from_expansion() |
| 94 | + && let Some(init) = stmt.init |
| 95 | + { |
| 96 | + let mid_ty = cx.typeck_results().expr_ty(init); |
| 97 | + check_expr(cx, init.peel_blocks(), &TypeAscriptionKind::Optional(stmt.ty), mid_ty); |
| 98 | + } |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +/// Whether the type ascription `: RwLock<X>` (which we'll suggest replacing with `AtomicX`) is |
| 103 | +/// required |
| 104 | +enum TypeAscriptionKind<'tcx> { |
| 105 | + /// Yes; for us, this is the case for statics |
| 106 | + Required(&'tcx hir::Ty<'tcx>), |
| 107 | + /// No; the ascription might've been necessary in an expression like: |
| 108 | + /// ```ignore |
| 109 | + /// let rwlock: RwLock<u64> = RwLock::new(0); |
| 110 | + /// ``` |
| 111 | + /// to specify the type of `0`, but since `AtomicX` already refers to a concrete type, we won't |
| 112 | + /// need this ascription anymore. |
| 113 | + Optional(Option<&'tcx hir::Ty<'tcx>>), |
| 114 | +} |
| 115 | + |
| 116 | +fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, ty_ascription: &TypeAscriptionKind<'tcx>, ty: Ty<'tcx>) { |
| 117 | + if let ty::Adt(_, subst) = ty.kind() |
| 118 | + && ty.is_diag_item(cx, sym::RwLock) |
| 119 | + && let rwlock_param = subst.type_at(0) |
| 120 | + && let Some(atomic_name) = get_atomic_name(rwlock_param) |
| 121 | + { |
| 122 | + let msg = "using a `RwLock` where an atomic would do"; |
| 123 | + let diag = |diag: &mut Diag<'_, _>| { |
| 124 | + // if `expr = RwLock::new(arg)`, we can try emitting a suggestion |
| 125 | + if let ExprKind::Call(qpath, [arg]) = expr.kind |
| 126 | + && let ExprKind::Path(QPath::TypeRelative(_rwlock, new)) = qpath.kind |
| 127 | + && new.ident.name == sym::new |
| 128 | + { |
| 129 | + let mut applicability = Applicability::MaybeIncorrect; |
| 130 | + let arg = Sugg::hir_with_applicability(cx, arg, "_", &mut applicability); |
| 131 | + let mut suggs = vec![(expr.span, format!("std::sync::atomic::{atomic_name}::new({arg})"))]; |
| 132 | + match ty_ascription { |
| 133 | + TypeAscriptionKind::Required(ty_ascription) => { |
| 134 | + suggs.push((ty_ascription.span, format!("std::sync::atomic::{atomic_name}"))); |
| 135 | + }, |
| 136 | + TypeAscriptionKind::Optional(Some(ty_ascription)) => { |
| 137 | + // See https://github.com/rust-lang/rust-clippy/pull/15386 for why this is |
| 138 | + // required |
| 139 | + let colon_ascription = (cx.sess().source_map()) |
| 140 | + .span_extend_to_prev_char_before(ty_ascription.span, ':', true) |
| 141 | + .with_leading_whitespace(cx) |
| 142 | + .into_span(); |
| 143 | + suggs.push((colon_ascription, String::new())); |
| 144 | + }, |
| 145 | + TypeAscriptionKind::Optional(None) => {}, // nothing to remove/replace |
| 146 | + } |
| 147 | + diag.multipart_suggestion("try", suggs, applicability); |
| 148 | + } else { |
| 149 | + diag.help(format!("consider using an `{atomic_name}` instead")); |
| 150 | + } |
| 151 | + diag.help("if you just want the locking behavior and not the internal type, consider using `RwLock<()>`"); |
| 152 | + }; |
| 153 | + match *rwlock_param.kind() { |
| 154 | + ty::Uint(t) if t != UintTy::Usize => span_lint_and_then(cx, RWLOCK_INTEGER, expr.span, msg, diag), |
| 155 | + ty::Int(t) if t != IntTy::Isize => span_lint_and_then(cx, RWLOCK_INTEGER, expr.span, msg, diag), |
| 156 | + _ => span_lint_and_then(cx, RWLOCK_ATOMIC, expr.span, msg, diag), |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +fn get_atomic_name(ty: Ty<'_>) -> Option<&'static str> { |
| 162 | + match ty.kind() { |
| 163 | + ty::Bool => Some("AtomicBool"), |
| 164 | + ty::Uint(uint_ty) => { |
| 165 | + match uint_ty { |
| 166 | + UintTy::U8 => Some("AtomicU8"), |
| 167 | + UintTy::U16 => Some("AtomicU16"), |
| 168 | + UintTy::U32 => Some("AtomicU32"), |
| 169 | + UintTy::U64 => Some("AtomicU64"), |
| 170 | + UintTy::Usize => Some("AtomicUsize"), |
| 171 | + // `AtomicU128` is unstable and only available on a few platforms: https://github.com/rust-lang/rust/issues/99069 |
| 172 | + UintTy::U128 => None, |
| 173 | + } |
| 174 | + }, |
| 175 | + ty::Int(int_ty) => { |
| 176 | + match int_ty { |
| 177 | + IntTy::I8 => Some("AtomicI8"), |
| 178 | + IntTy::I16 => Some("AtomicI16"), |
| 179 | + IntTy::I32 => Some("AtomicI32"), |
| 180 | + IntTy::I64 => Some("AtomicI64"), |
| 181 | + IntTy::Isize => Some("AtomicIsize"), |
| 182 | + // `AtomicU128` is unstable and only available on a few platforms: https://github.com/rust-lang/rust/issues/99069 |
| 183 | + IntTy::I128 => None, |
| 184 | + } |
| 185 | + }, |
| 186 | + // `AtomicPtr` only accepts `*mut T` |
| 187 | + ty::RawPtr(_, Mutability::Mut) => Some("AtomicPtr"), |
| 188 | + _ => None, |
| 189 | + } |
| 190 | +} |
0 commit comments