|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use clippy_utils::last_path_segment; |
| 3 | +use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; |
| 4 | +use if_chain::if_chain; |
| 5 | + |
| 6 | +use rustc_hir::{Expr, ExprKind}; |
| 7 | +use rustc_lint::LateContext; |
| 8 | +use rustc_lint::LateLintPass; |
| 9 | +use rustc_middle::ty; |
| 10 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 11 | +use rustc_span::symbol::sym; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// ### What it does. |
| 15 | + /// This lint warns when you use `Arc` with a type that does not implement `Send` or `Sync`. |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// Wrapping a type in Arc doesn't add thread safety to the underlying data, so data races |
| 19 | + /// could occur when touching the underlying data. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```rust |
| 23 | + /// # use std::cell::RefCell; |
| 24 | + /// # use std::sync::Arc; |
| 25 | + /// |
| 26 | + /// fn main() { |
| 27 | + /// // This is safe, as `i32` implements `Send` and `Sync`. |
| 28 | + /// let a = Arc::new(42); |
| 29 | + /// |
| 30 | + /// // This is not safe, as `RefCell` does not implement `Sync`. |
| 31 | + /// let b = Arc::new(RefCell::new(42)); |
| 32 | + /// } |
| 33 | + /// ``` |
| 34 | + #[clippy::version = "1.72.0"] |
| 35 | + pub ARC_WITH_NON_SEND_SYNC, |
| 36 | + correctness, |
| 37 | + "using `Arc` with a type that does not implement `Send` or `Sync`" |
| 38 | +} |
| 39 | +declare_lint_pass!(ArcWithNonSendSync => [ARC_WITH_NON_SEND_SYNC]); |
| 40 | + |
| 41 | +impl LateLintPass<'_> for ArcWithNonSendSync { |
| 42 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 43 | + let ty = cx.typeck_results().expr_ty(expr); |
| 44 | + if_chain! { |
| 45 | + if is_type_diagnostic_item(cx, ty, sym::Arc); |
| 46 | + if let ExprKind::Call(func, [arg]) = expr.kind; |
| 47 | + if let ExprKind::Path(func_path) = func.kind; |
| 48 | + if last_path_segment(&func_path).ident.name == sym::new; |
| 49 | + if let arg_ty = cx.typeck_results().expr_ty(arg); |
| 50 | + if !matches!(arg_ty.kind(), ty::Param(_)); |
| 51 | + if !cx.tcx |
| 52 | + .lang_items() |
| 53 | + .sync_trait() |
| 54 | + .map_or(false, |id| implements_trait(cx, arg_ty, id, &[])) || |
| 55 | + !cx.tcx |
| 56 | + .get_diagnostic_item(sym::Send) |
| 57 | + .map_or(false, |id| implements_trait(cx, arg_ty, id, &[])); |
| 58 | + |
| 59 | + then { |
| 60 | + span_lint_and_help( |
| 61 | + cx, |
| 62 | + ARC_WITH_NON_SEND_SYNC, |
| 63 | + expr.span, |
| 64 | + "usage of `Arc<T>` where `T` is not `Send` or `Sync`", |
| 65 | + None, |
| 66 | + "consider using `Rc<T>` instead or wrapping `T` in a std::sync type like \ |
| 67 | + `Mutex<T>`", |
| 68 | + ); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments