]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / non_send_fields_in_send_ty.rs
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};
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Warns about fields in struct implementing `Send` that are neither `Send` nor `Copy`.
17     ///
18     /// ### Why is this bad?
19     /// Sending the struct to another thread will transfer the ownership to
20     /// the new thread by dropping in the current thread during the transfer.
21     /// This causes soundness issues for non-`Send` fields, as they are also
22     /// dropped and might not be set up to handle this.
23     ///
24     /// See:
25     /// * [*The Rustonomicon* about *Send and Sync*](https://doc.rust-lang.org/nomicon/send-and-sync.html)
26     /// * [The documentation of `Send`](https://doc.rust-lang.org/std/marker/trait.Send.html)
27     ///
28     /// ### Known Problems
29     /// Data structures that contain raw pointers may cause false positives.
30     /// They are sometimes safe to be sent across threads but do not implement
31     /// the `Send` trait. This lint has a heuristic to filter out basic cases
32     /// such as `Vec<*const T>`, but it's not perfect. Feel free to create an
33     /// issue if you have a suggestion on how this heuristic can be improved.
34     ///
35     /// ### Example
36     /// ```rust,ignore
37     /// struct ExampleStruct<T> {
38     ///     rc_is_not_send: Rc<String>,
39     ///     unbounded_generic_field: T,
40     /// }
41     ///
42     /// // This impl is unsound because it allows sending `!Send` types through `ExampleStruct`
43     /// unsafe impl<T> Send for ExampleStruct<T> {}
44     /// ```
45     /// Use thread-safe types like [`std::sync::Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html)
46     /// or specify correct bounds on generic type parameters (`T: Send`).
47     #[clippy::version = "1.57.0"]
48     pub NON_SEND_FIELDS_IN_SEND_TY,
49     suspicious,
50     "there is field that does not implement `Send` in a `Send` struct"
51 }
52
53 #[derive(Copy, Clone)]
54 pub struct NonSendFieldInSendTy {
55     enable_raw_pointer_heuristic: bool,
56 }
57
58 impl NonSendFieldInSendTy {
59     pub fn new(enable_raw_pointer_heuristic: bool) -> Self {
60         Self {
61             enable_raw_pointer_heuristic,
62         }
63     }
64 }
65
66 impl_lint_pass!(NonSendFieldInSendTy => [NON_SEND_FIELDS_IN_SEND_TY]);
67
68 impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy {
69     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
70         let ty_allowed_in_send = if self.enable_raw_pointer_heuristic {
71             ty_allowed_with_raw_pointer_heuristic
72         } else {
73             ty_allowed_without_raw_pointer_heuristic
74         };
75
76         // Checks if we are in `Send` impl item.
77         // We start from `Send` impl instead of `check_field_def()` because
78         // single `AdtDef` may have multiple `Send` impls due to generic
79         // parameters, and the lint is much easier to implement in this way.
80         if_chain! {
81             if !in_external_macro(cx.tcx.sess, item.span);
82             if let Some(send_trait) = cx.tcx.get_diagnostic_item(sym::Send);
83             if let ItemKind::Impl(hir_impl) = &item.kind;
84             if let Some(trait_ref) = &hir_impl.of_trait;
85             if let Some(trait_id) = trait_ref.trait_def_id();
86             if send_trait == trait_id;
87             if hir_impl.polarity == ImplPolarity::Positive;
88             if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
89             if let self_ty = ty_trait_ref.self_ty();
90             if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind();
91             then {
92                 let mut non_send_fields = Vec::new();
93
94                 let hir_map = cx.tcx.hir();
95                 for variant in &adt_def.variants {
96                     for field in &variant.fields {
97                         if_chain! {
98                             if let Some(field_hir_id) = field
99                                 .did
100                                 .as_local()
101                                 .map(|local_def_id| hir_map.local_def_id_to_hir_id(local_def_id));
102                             if !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id);
103                             if let field_ty = field.ty(cx.tcx, impl_trait_substs);
104                             if !ty_allowed_in_send(cx, field_ty, send_trait);
105                             if let Node::Field(field_def) = hir_map.get(field_hir_id);
106                             then {
107                                 non_send_fields.push(NonSendField {
108                                     def: field_def,
109                                     ty: field_ty,
110                                     generic_params: collect_generic_params(cx, field_ty),
111                                 })
112                             }
113                         }
114                     }
115                 }
116
117                 if !non_send_fields.is_empty() {
118                     span_lint_and_then(
119                         cx,
120                         NON_SEND_FIELDS_IN_SEND_TY,
121                         item.span,
122                         &format!(
123                             "this implementation is unsound, as some fields in `{}` are `!Send`",
124                             snippet(cx, hir_impl.self_ty.span, "Unknown")
125                         ),
126                         |diag| {
127                             for field in non_send_fields {
128                                 diag.span_note(
129                                     field.def.span,
130                                     &format!("the type of field `{}` is `!Send`", field.def.ident.name),
131                                 );
132
133                                 match field.generic_params.len() {
134                                     0 => diag.help("use a thread-safe type that implements `Send`"),
135                                     1 if is_ty_param(field.ty) => diag.help(&format!("add `{}: Send` bound in `Send` impl", field.ty)),
136                                     _ => diag.help(&format!(
137                                         "add bounds on type parameter{} `{}` that satisfy `{}: Send`",
138                                         if field.generic_params.len() > 1 { "s" } else { "" },
139                                         field.generic_params_string(),
140                                         snippet(cx, field.def.ty.span, "Unknown"),
141                                     )),
142                                 };
143                             }
144                         },
145                     );
146                 }
147             }
148         }
149     }
150 }
151
152 struct NonSendField<'tcx> {
153     def: &'tcx FieldDef<'tcx>,
154     ty: Ty<'tcx>,
155     generic_params: Vec<Ty<'tcx>>,
156 }
157
158 impl<'tcx> NonSendField<'tcx> {
159     fn generic_params_string(&self) -> String {
160         self.generic_params
161             .iter()
162             .map(ToString::to_string)
163             .collect::<Vec<_>>()
164             .join(", ")
165     }
166 }
167
168 /// Given a type, collect all of its generic parameters.
169 /// Example: `MyStruct<P, Box<Q, R>>` => `vec![P, Q, R]`
170 fn collect_generic_params<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
171     ty.walk(cx.tcx)
172         .filter_map(|inner| match inner.unpack() {
173             GenericArgKind::Type(inner_ty) => Some(inner_ty),
174             _ => None,
175         })
176         .filter(|&inner_ty| is_ty_param(inner_ty))
177         .collect()
178 }
179
180 /// Be more strict when the heuristic is disabled
181 fn ty_allowed_without_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
182     if implements_trait(cx, ty, send_trait, &[]) {
183         return true;
184     }
185
186     if is_copy(cx, ty) && !contains_pointer_like(cx, ty) {
187         return true;
188     }
189
190     false
191 }
192
193 /// Heuristic to allow cases like `Vec<*const u8>`
194 fn ty_allowed_with_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, send_trait: DefId) -> bool {
195     if implements_trait(cx, ty, send_trait, &[]) || is_copy(cx, ty) {
196         return true;
197     }
198
199     // The type is known to be `!Send` and `!Copy`
200     match ty.kind() {
201         ty::Tuple(_) => ty
202             .tuple_fields()
203             .all(|ty| ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait)),
204         ty::Array(ty, _) | ty::Slice(ty) => ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait),
205         ty::Adt(_, substs) => {
206             if contains_pointer_like(cx, ty) {
207                 // descends only if ADT contains any raw pointers
208                 substs.iter().all(|generic_arg| match generic_arg.unpack() {
209                     GenericArgKind::Type(ty) => ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait),
210                     // Lifetimes and const generics are not solid part of ADT and ignored
211                     GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => true,
212                 })
213             } else {
214                 false
215             }
216         },
217         // Raw pointers are `!Send` but allowed by the heuristic
218         ty::RawPtr(_) => true,
219         _ => false,
220     }
221 }
222
223 /// Checks if the type contains any pointer-like types in substs (including nested ones)
224 fn contains_pointer_like<'tcx>(cx: &LateContext<'tcx>, target_ty: Ty<'tcx>) -> bool {
225     for ty_node in target_ty.walk(cx.tcx) {
226         if let GenericArgKind::Type(inner_ty) = ty_node.unpack() {
227             match inner_ty.kind() {
228                 ty::RawPtr(_) => {
229                     return true;
230                 },
231                 ty::Adt(adt_def, _) => {
232                     if match_def_path(cx, adt_def.did, &paths::PTR_NON_NULL) {
233                         return true;
234                     }
235                 },
236                 _ => (),
237             }
238         }
239     }
240
241     false
242 }
243
244 /// Returns `true` if the type is a type parameter such as `T`.
245 fn is_ty_param(target_ty: Ty<'_>) -> bool {
246     matches!(target_ty.kind(), ty::Param(_))
247 }