1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::{implements_trait, is_copy};
4 use clippy_utils::{is_lint_allowed, match_def_path, paths};
5 use rustc_ast::ImplPolarity;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::{FieldDef, Item, ItemKind, Node};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 declare_clippy_lint! {
16 /// This lint warns about a `Send` implementation for a type that
17 /// contains fields that are not safe to be sent across threads.
18 /// It tries to detect fields that can cause a soundness issue
19 /// when sent to another thread (e.g., `Rc`) while allowing `!Send` fields
20 /// that are expected to exist in a `Send` type, such as raw pointers.
22 /// ### Why is this bad?
23 /// Sending the struct to another thread effectively sends all of its fields,
24 /// and the fields that do not implement `Send` can lead to soundness bugs
25 /// such as data races when accessed in a thread
26 /// that is different from the thread that created it.
29 /// * [*The Rustonomicon* about *Send and Sync*](https://doc.rust-lang.org/nomicon/send-and-sync.html)
30 /// * [The documentation of `Send`](https://doc.rust-lang.org/std/marker/trait.Send.html)
32 /// ### Known Problems
33 /// This lint relies on heuristics to distinguish types that are actually
34 /// unsafe to be sent across threads and `!Send` types that are expected to
35 /// exist in `Send` type. Its rule can filter out basic cases such as
36 /// `Vec<*const T>`, but it's not perfect. Feel free to create an issue if
37 /// you have a suggestion on how this heuristic can be improved.
41 /// struct ExampleStruct<T> {
42 /// rc_is_not_send: Rc<String>,
43 /// unbounded_generic_field: T,
46 /// // This impl is unsound because it allows sending `!Send` types through `ExampleStruct`
47 /// unsafe impl<T> Send for ExampleStruct<T> {}
49 /// Use thread-safe types like [`std::sync::Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html)
50 /// or specify correct bounds on generic type parameters (`T: Send`).
51 #[clippy::version = "1.57.0"]
52 pub NON_SEND_FIELDS_IN_SEND_TY,
54 "there is a field that is not safe to be sent to another thread in a `Send` struct"
57 #[derive(Copy, Clone)]
58 pub struct NonSendFieldInSendTy {
59 enable_raw_pointer_heuristic: bool,
62 impl NonSendFieldInSendTy {
63 pub fn new(enable_raw_pointer_heuristic: bool) -> Self {
65 enable_raw_pointer_heuristic,
70 impl_lint_pass!(NonSendFieldInSendTy => [NON_SEND_FIELDS_IN_SEND_TY]);
72 impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy {
73 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
74 let ty_allowed_in_send = if self.enable_raw_pointer_heuristic {
75 ty_allowed_with_raw_pointer_heuristic
77 ty_allowed_without_raw_pointer_heuristic
80 // Checks if we are in `Send` impl item.
81 // We start from `Send` impl instead of `check_field_def()` because
82 // single `AdtDef` may have multiple `Send` impls due to generic
83 // parameters, and the lint is much easier to implement in this way.
85 if !in_external_macro(cx.tcx.sess, item.span);
86 if let Some(send_trait) = cx.tcx.get_diagnostic_item(sym::Send);
87 if let ItemKind::Impl(hir_impl) = &item.kind;
88 if let Some(trait_ref) = &hir_impl.of_trait;
89 if let Some(trait_id) = trait_ref.trait_def_id();
90 if send_trait == trait_id;
91 if hir_impl.polarity == ImplPolarity::Positive;
92 if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
93 if let self_ty = ty_trait_ref.self_ty();
94 if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind();
96 let mut non_send_fields = Vec::new();
98 let hir_map = cx.tcx.hir();
99 for variant in adt_def.variants() {
100 for field in &variant.fields {
102 if let Some(field_hir_id) = field
105 .map(|local_def_id| hir_map.local_def_id_to_hir_id(local_def_id));
106 if !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id);
107 if let field_ty = field.ty(cx.tcx, impl_trait_substs);
108 if !ty_allowed_in_send(cx, field_ty, send_trait);
109 if let Node::Field(field_def) = hir_map.get(field_hir_id);
111 non_send_fields.push(NonSendField {
114 generic_params: collect_generic_params(field_ty),
121 if !non_send_fields.is_empty() {
124 NON_SEND_FIELDS_IN_SEND_TY,
127 "some fields in `{}` are not safe to be sent to another thread",
128 snippet(cx, hir_impl.self_ty.span, "Unknown")
131 for field in non_send_fields {
134 &format!("it is not safe to send field `{}` to another thread", field.def.ident.name),
137 match field.generic_params.len() {
138 0 => diag.help("use a thread-safe type that implements `Send`"),
139 1 if is_ty_param(field.ty) => diag.help(&format!("add `{}: Send` bound in `Send` impl", field.ty)),
140 _ => diag.help(&format!(
141 "add bounds on type parameter{} `{}` that satisfy `{}: Send`",
142 if field.generic_params.len() > 1 { "s" } else { "" },
143 field.generic_params_string(),
144 snippet(cx, field.def.ty.span, "Unknown"),
156 struct NonSendField<'tcx> {
157 def: &'tcx FieldDef<'tcx>,
159 generic_params: Vec<Ty<'tcx>>,
162 impl<'tcx> NonSendField<'tcx> {
163 fn generic_params_string(&self) -> String {
166 .map(ToString::to_string)
172 /// Given a type, collect all of its generic parameters.
173 /// Example: `MyStruct<P, Box<Q, R>>` => `vec![P, Q, R]`
174 fn collect_generic_params(ty: Ty<'_>) -> Vec<Ty<'_>> {
176 .filter_map(|inner| match inner.unpack() {
177 GenericArgKind::Type(inner_ty) => Some(inner_ty),
180 .filter(|&inner_ty| is_ty_param(inner_ty))
184 /// Be more strict when the heuristic is disabled
185 fn ty_allowed_without_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
186 if implements_trait(cx, ty, send_trait, &[]) {
190 if is_copy(cx, ty) && !contains_pointer_like(cx, ty) {
197 /// Heuristic to allow cases like `Vec<*const u8>`
198 fn ty_allowed_with_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
199 if implements_trait(cx, ty, send_trait, &[]) || is_copy(cx, ty) {
203 // The type is known to be `!Send` and `!Copy`
205 ty::Tuple(fields) => fields
207 .all(|ty| ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait)),
208 ty::Array(ty, _) | ty::Slice(ty) => ty_allowed_with_raw_pointer_heuristic(cx, *ty, send_trait),
209 ty::Adt(_, substs) => {
210 if contains_pointer_like(cx, ty) {
211 // descends only if ADT contains any raw pointers
212 substs.iter().all(|generic_arg| match generic_arg.unpack() {
213 GenericArgKind::Type(ty) => ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait),
214 // Lifetimes and const generics are not solid part of ADT and ignored
215 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => true,
221 // Raw pointers are `!Send` but allowed by the heuristic
222 ty::RawPtr(_) => true,
227 /// Checks if the type contains any pointer-like types in substs (including nested ones)
228 fn contains_pointer_like<'tcx>(cx: &LateContext<'tcx>, target_ty: Ty<'tcx>) -> bool {
229 for ty_node in target_ty.walk() {
230 if let GenericArgKind::Type(inner_ty) = ty_node.unpack() {
231 match inner_ty.kind() {
235 ty::Adt(adt_def, _) => {
236 if match_def_path(cx, adt_def.did(), &paths::PTR_NON_NULL) {
248 /// Returns `true` if the type is a type parameter such as `T`.
249 fn is_ty_param(target_ty: Ty<'_>) -> bool {
250 matches!(target_ty.kind(), ty::Param(_))