]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/needs_drop.rs
Rollup merge of #101740 - andrewpollack:add-ignore-fuchsia-ui-tests, r=tmandry
[rust.git] / compiler / rustc_ty_utils / src / needs_drop.rs
1 //! Check whether a type has (potentially) non-trivial drop glue.
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir::def_id::DefId;
5 use rustc_middle::ty::subst::Subst;
6 use rustc_middle::ty::subst::SubstsRef;
7 use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop};
8 use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt};
9 use rustc_session::Limit;
10 use rustc_span::{sym, DUMMY_SP};
11
12 use crate::errors::NeedsDropOverflow;
13
14 type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
15
16 fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
17     // If we don't know a type doesn't need drop, for example if it's a type
18     // parameter without a `Copy` bound, then we conservatively return that it
19     // needs drop.
20     let adt_has_dtor =
21         |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
22     let res =
23         drop_tys_helper(tcx, query.value, query.param_env, adt_has_dtor, false).next().is_some();
24
25     debug!("needs_drop_raw({:?}) = {:?}", query, res);
26     res
27 }
28
29 fn has_significant_drop_raw<'tcx>(
30     tcx: TyCtxt<'tcx>,
31     query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
32 ) -> bool {
33     let res = drop_tys_helper(
34         tcx,
35         query.value,
36         query.param_env,
37         adt_consider_insignificant_dtor(tcx),
38         true,
39     )
40     .next()
41     .is_some();
42     debug!("has_significant_drop_raw({:?}) = {:?}", query, res);
43     res
44 }
45
46 struct NeedsDropTypes<'tcx, F> {
47     tcx: TyCtxt<'tcx>,
48     param_env: ty::ParamEnv<'tcx>,
49     query_ty: Ty<'tcx>,
50     seen_tys: FxHashSet<Ty<'tcx>>,
51     /// A stack of types left to process, and the recursion depth when we
52     /// pushed that type. Each round, we pop something from the stack and check
53     /// if it needs drop. If the result depends on whether some other types
54     /// need drop we push them onto the stack.
55     unchecked_tys: Vec<(Ty<'tcx>, usize)>,
56     recursion_limit: Limit,
57     adt_components: F,
58 }
59
60 impl<'tcx, F> NeedsDropTypes<'tcx, F> {
61     fn new(
62         tcx: TyCtxt<'tcx>,
63         param_env: ty::ParamEnv<'tcx>,
64         ty: Ty<'tcx>,
65         adt_components: F,
66     ) -> Self {
67         let mut seen_tys = FxHashSet::default();
68         seen_tys.insert(ty);
69         Self {
70             tcx,
71             param_env,
72             seen_tys,
73             query_ty: ty,
74             unchecked_tys: vec![(ty, 0)],
75             recursion_limit: tcx.recursion_limit(),
76             adt_components,
77         }
78     }
79 }
80
81 impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F>
82 where
83     F: Fn(ty::AdtDef<'tcx>, SubstsRef<'tcx>) -> NeedsDropResult<I>,
84     I: Iterator<Item = Ty<'tcx>>,
85 {
86     type Item = NeedsDropResult<Ty<'tcx>>;
87
88     fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
89         let tcx = self.tcx;
90
91         while let Some((ty, level)) = self.unchecked_tys.pop() {
92             if !self.recursion_limit.value_within_limit(level) {
93                 // Not having a `Span` isn't great. But there's hopefully some other
94                 // recursion limit error as well.
95                 tcx.sess.emit_err(NeedsDropOverflow { query_ty: self.query_ty });
96                 return Some(Err(AlwaysRequiresDrop));
97             }
98
99             let components = match needs_drop_components(ty, &tcx.data_layout) {
100                 Err(e) => return Some(Err(e)),
101                 Ok(components) => components,
102             };
103             debug!("needs_drop_components({:?}) = {:?}", ty, components);
104
105             let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
106                 if this.seen_tys.insert(component) {
107                     this.unchecked_tys.push((component, level + 1));
108                 }
109             };
110
111             for component in components {
112                 match *component.kind() {
113                     _ if component.is_copy_modulo_regions(tcx.at(DUMMY_SP), self.param_env) => (),
114
115                     ty::Closure(_, substs) => {
116                         queue_type(self, substs.as_closure().tupled_upvars_ty());
117                     }
118
119                     ty::Generator(def_id, substs, _) => {
120                         let substs = substs.as_generator();
121                         queue_type(self, substs.tupled_upvars_ty());
122
123                         let witness = substs.witness();
124                         let interior_tys = match witness.kind() {
125                             &ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys),
126                             _ => {
127                                 tcx.sess.delay_span_bug(
128                                     tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP),
129                                     &format!("unexpected generator witness type {:?}", witness),
130                                 );
131                                 return Some(Err(AlwaysRequiresDrop));
132                             }
133                         };
134
135                         for interior_ty in interior_tys {
136                             queue_type(self, interior_ty);
137                         }
138                     }
139
140                     // Check for a `Drop` impl and whether this is a union or
141                     // `ManuallyDrop`. If it's a struct or enum without a `Drop`
142                     // impl then check whether the field types need `Drop`.
143                     ty::Adt(adt_def, substs) => {
144                         let tys = match (self.adt_components)(adt_def, substs) {
145                             Err(e) => return Some(Err(e)),
146                             Ok(tys) => tys,
147                         };
148                         for required_ty in tys {
149                             let required = tcx
150                                 .try_normalize_erasing_regions(self.param_env, required_ty)
151                                 .unwrap_or(required_ty);
152
153                             queue_type(self, required);
154                         }
155                     }
156                     ty::Array(..) | ty::Opaque(..) | ty::Projection(..) | ty::Param(_) => {
157                         if ty == component {
158                             // Return the type to the caller: they may be able
159                             // to normalize further than we can.
160                             return Some(Ok(component));
161                         } else {
162                             // Store the type for later. We can't return here
163                             // because we would then lose any other components
164                             // of the type.
165                             queue_type(self, component);
166                         }
167                     }
168                     _ => return Some(Err(AlwaysRequiresDrop)),
169                 }
170             }
171         }
172
173         None
174     }
175 }
176
177 enum DtorType {
178     /// Type has a `Drop` but it is considered insignificant.
179     /// Check the query `adt_significant_drop_tys` for understanding
180     /// "significant" / "insignificant".
181     Insignificant,
182
183     /// Type has a `Drop` implantation.
184     Significant,
185 }
186
187 // This is a helper function for `adt_drop_tys` and `adt_significant_drop_tys`.
188 // Depending on the implantation of `adt_has_dtor`, it is used to check if the
189 // ADT has a destructor or if the ADT only has a significant destructor. For
190 // understanding significant destructor look at `adt_significant_drop_tys`.
191 fn drop_tys_helper<'tcx>(
192     tcx: TyCtxt<'tcx>,
193     ty: Ty<'tcx>,
194     param_env: rustc_middle::ty::ParamEnv<'tcx>,
195     adt_has_dtor: impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType>,
196     only_significant: bool,
197 ) -> impl Iterator<Item = NeedsDropResult<Ty<'tcx>>> {
198     fn with_query_cache<'tcx>(
199         tcx: TyCtxt<'tcx>,
200         iter: impl IntoIterator<Item = Ty<'tcx>>,
201     ) -> NeedsDropResult<Vec<Ty<'tcx>>> {
202         iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
203             match subty.kind() {
204                 ty::Adt(adt_id, subst) => {
205                     for subty in tcx.adt_drop_tys(adt_id.did())? {
206                         vec.push(EarlyBinder(subty).subst(tcx, subst));
207                     }
208                 }
209                 _ => vec.push(subty),
210             };
211             Ok(vec)
212         })
213     }
214
215     let adt_components = move |adt_def: ty::AdtDef<'tcx>, substs: SubstsRef<'tcx>| {
216         if adt_def.is_manually_drop() {
217             debug!("drop_tys_helper: `{:?}` is manually drop", adt_def);
218             Ok(Vec::new())
219         } else if let Some(dtor_info) = adt_has_dtor(adt_def) {
220             match dtor_info {
221                 DtorType::Significant => {
222                     debug!("drop_tys_helper: `{:?}` implements `Drop`", adt_def);
223                     Err(AlwaysRequiresDrop)
224                 }
225                 DtorType::Insignificant => {
226                     debug!("drop_tys_helper: `{:?}` drop is insignificant", adt_def);
227
228                     // Since the destructor is insignificant, we just want to make sure all of
229                     // the passed in type parameters are also insignificant.
230                     // Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex.
231                     Ok(substs.types().collect())
232                 }
233             }
234         } else if adt_def.is_union() {
235             debug!("drop_tys_helper: `{:?}` is a union", adt_def);
236             Ok(Vec::new())
237         } else {
238             let field_tys = adt_def.all_fields().map(|field| {
239                 let r = tcx.bound_type_of(field.did).subst(tcx, substs);
240                 debug!("drop_tys_helper: Subst into {:?} with {:?} gettng {:?}", field, substs, r);
241                 r
242             });
243             if only_significant {
244                 // We can't recurse through the query system here because we might induce a cycle
245                 Ok(field_tys.collect())
246             } else {
247                 // We can use the query system if we consider all drops significant. In that case,
248                 // ADTs are `needs_drop` exactly if they `impl Drop` or if any of their "transitive"
249                 // fields do. There can be no cycles here, because ADTs cannot contain themselves as
250                 // fields.
251                 with_query_cache(tcx, field_tys)
252             }
253         }
254         .map(|v| v.into_iter())
255     };
256
257     NeedsDropTypes::new(tcx, param_env, ty, adt_components)
258 }
259
260 fn adt_consider_insignificant_dtor<'tcx>(
261     tcx: TyCtxt<'tcx>,
262 ) -> impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType> + 'tcx {
263     move |adt_def: ty::AdtDef<'tcx>| {
264         let is_marked_insig = tcx.has_attr(adt_def.did(), sym::rustc_insignificant_dtor);
265         if is_marked_insig {
266             // In some cases like `std::collections::HashMap` where the struct is a wrapper around
267             // a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies
268             // outside stdlib, we might choose to still annotate the the wrapper (std HashMap) with
269             // `rustc_insignificant_dtor`, even if the type itself doesn't have a `Drop` impl.
270             Some(DtorType::Insignificant)
271         } else if adt_def.destructor(tcx).is_some() {
272             // There is a Drop impl and the type isn't marked insignificant, therefore Drop must be
273             // significant.
274             Some(DtorType::Significant)
275         } else {
276             // No destructor found nor the type is annotated with `rustc_insignificant_dtor`, we
277             // treat this as the simple case of Drop impl for type.
278             None
279         }
280     }
281 }
282
283 fn adt_drop_tys<'tcx>(
284     tcx: TyCtxt<'tcx>,
285     def_id: DefId,
286 ) -> Result<&ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
287     // This is for the "adt_drop_tys" query, that considers all `Drop` impls, therefore all dtors are
288     // significant.
289     let adt_has_dtor =
290         |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
291     // `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_substs)`
292     drop_tys_helper(tcx, tcx.type_of(def_id), tcx.param_env(def_id), adt_has_dtor, false)
293         .collect::<Result<Vec<_>, _>>()
294         .map(|components| tcx.intern_type_list(&components))
295 }
296 // If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed
297 // a `tcx.make_ty(def, identity_substs)` and as such it is legal to substitute the generic parameters
298 // of the ADT into the outputted `ty`s.
299 fn adt_significant_drop_tys(
300     tcx: TyCtxt<'_>,
301     def_id: DefId,
302 ) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
303     drop_tys_helper(
304         tcx,
305         tcx.type_of(def_id), // identical to `tcx.make_adt(def, identity_substs)`
306         tcx.param_env(def_id),
307         adt_consider_insignificant_dtor(tcx),
308         true,
309     )
310     .collect::<Result<Vec<_>, _>>()
311     .map(|components| tcx.intern_type_list(&components))
312 }
313
314 pub(crate) fn provide(providers: &mut ty::query::Providers) {
315     *providers = ty::query::Providers {
316         needs_drop_raw,
317         has_significant_drop_raw,
318         adt_drop_tys,
319         adt_significant_drop_tys,
320         ..*providers
321     };
322 }