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