1 //! Check whether a type has (potentially) non-trivial drop glue.
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, Ty, TyCtxt};
9 use rustc_session::Limit;
10 use rustc_span::{sym, DUMMY_SP};
12 type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
14 fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
15 // If we don't know a type doesn't need drop, for example if it's a type
16 // parameter without a `Copy` bound, then we conservatively return that it
19 |adt_def: &ty::AdtDef| adt_def.destructor(tcx).map(|_| DtorType::Significant);
21 drop_tys_helper(tcx, query.value, query.param_env, adt_has_dtor, false).next().is_some();
23 debug!("needs_drop_raw({:?}) = {:?}", query, res);
27 fn has_significant_drop_raw<'tcx>(
29 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
31 let res = drop_tys_helper(
35 adt_consider_insignificant_dtor(tcx),
40 debug!("has_significant_drop_raw({:?}) = {:?}", query, res);
44 struct NeedsDropTypes<'tcx, F> {
46 param_env: ty::ParamEnv<'tcx>,
48 seen_tys: FxHashSet<Ty<'tcx>>,
49 /// A stack of types left to process, and the recursion depth when we
50 /// pushed that type. Each round, we pop something from the stack and check
51 /// if it needs drop. If the result depends on whether some other types
52 /// need drop we push them onto the stack.
53 unchecked_tys: Vec<(Ty<'tcx>, usize)>,
54 recursion_limit: Limit,
58 impl<'tcx, F> NeedsDropTypes<'tcx, F> {
61 param_env: ty::ParamEnv<'tcx>,
65 let mut seen_tys = FxHashSet::default();
72 unchecked_tys: vec![(ty, 0)],
73 recursion_limit: tcx.recursion_limit(),
79 impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F>
81 F: Fn(&ty::AdtDef, SubstsRef<'tcx>) -> NeedsDropResult<I>,
82 I: Iterator<Item = Ty<'tcx>>,
84 type Item = NeedsDropResult<Ty<'tcx>>;
86 fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
89 while let Some((ty, level)) = self.unchecked_tys.pop() {
90 if !self.recursion_limit.value_within_limit(level) {
91 // Not having a `Span` isn't great. But there's hopefully some other
92 // recursion limit error as well.
95 &format!("overflow while checking whether `{}` requires drop", self.query_ty),
97 return Some(Err(AlwaysRequiresDrop));
100 let components = match needs_drop_components(ty, &tcx.data_layout) {
101 Err(e) => return Some(Err(e)),
102 Ok(components) => components,
104 debug!("needs_drop_components({:?}) = {:?}", ty, components);
106 let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
107 if this.seen_tys.insert(component) {
108 this.unchecked_tys.push((component, level + 1));
112 for component in components {
113 match *component.kind() {
114 _ if component.is_copy_modulo_regions(tcx.at(DUMMY_SP), self.param_env) => (),
116 ty::Closure(_, substs) => {
117 queue_type(self, substs.as_closure().tupled_upvars_ty());
120 ty::Generator(def_id, substs, _) => {
121 let substs = substs.as_generator();
122 queue_type(self, substs.tupled_upvars_ty());
124 let witness = substs.witness();
125 let interior_tys = match witness.kind() {
126 &ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys),
128 tcx.sess.delay_span_bug(
129 tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP),
130 &format!("unexpected generator witness type {:?}", witness),
132 return Some(Err(AlwaysRequiresDrop));
136 for interior_ty in interior_tys {
137 queue_type(self, interior_ty);
141 // Check for a `Drop` impl and whether this is a union or
142 // `ManuallyDrop`. If it's a struct or enum without a `Drop`
143 // impl then check whether the field types need `Drop`.
144 ty::Adt(adt_def, substs) => {
145 let tys = match (self.adt_components)(adt_def, substs) {
146 Err(e) => return Some(Err(e)),
149 for required_ty in tys {
151 tcx.normalize_erasing_regions(self.param_env, required_ty);
152 queue_type(self, required);
155 ty::Array(..) | ty::Opaque(..) | ty::Projection(..) | ty::Param(_) => {
157 // Return the type to the caller: they may be able
158 // to normalize further than we can.
159 return Some(Ok(component));
161 // Store the type for later. We can't return here
162 // because we would then lose any other components
164 queue_type(self, component);
167 _ => return Some(Err(AlwaysRequiresDrop)),
177 /// Type has a `Drop` but it is considered insignificant.
178 /// Check the query `adt_significant_drop_tys` for understanding
179 /// "significant" / "insignificant".
182 /// Type has a `Drop` implentation.
186 // This is a helper function for `adt_drop_tys` and `adt_significant_drop_tys`.
187 // Depending on the implentation of `adt_has_dtor`, it is used to check if the
188 // ADT has a destructor or if the ADT only has a significant destructor. For
189 // understanding significant destructor look at `adt_significant_drop_tys`.
190 fn drop_tys_helper<'tcx>(
193 param_env: rustc_middle::ty::ParamEnv<'tcx>,
194 adt_has_dtor: impl Fn(&ty::AdtDef) -> Option<DtorType>,
195 only_significant: bool,
196 ) -> impl Iterator<Item = NeedsDropResult<Ty<'tcx>>> {
197 fn with_query_cache<'tcx>(
199 iter: impl IntoIterator<Item = Ty<'tcx>>,
200 only_significant: bool,
201 ) -> NeedsDropResult<Vec<Ty<'tcx>>> {
202 iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
204 ty::Adt(adt_id, subst) => {
205 for subty in if only_significant {
206 tcx.adt_significant_drop_tys(adt_id.did)?
208 tcx.adt_drop_tys(adt_id.did)?
210 vec.push(subty.subst(tcx, subst));
213 _ => vec.push(subty),
219 let adt_components = move |adt_def: &ty::AdtDef, substs: SubstsRef<'tcx>| {
220 if adt_def.is_manually_drop() {
221 debug!("drop_tys_helper: `{:?}` is manually drop", adt_def);
223 } else if let Some(dtor_info) = adt_has_dtor(adt_def) {
225 DtorType::Significant => {
226 debug!("drop_tys_helper: `{:?}` implements `Drop`", adt_def);
227 Err(AlwaysRequiresDrop)
229 DtorType::Insignificant => {
230 debug!("drop_tys_helper: `{:?}` drop is insignificant", adt_def);
232 // Since the destructor is insignificant, we just want to make sure all of
233 // the passed in type parameters are also insignificant.
234 // Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex.
235 with_query_cache(tcx, substs.types(), only_significant)
238 } else if adt_def.is_union() {
239 debug!("drop_tys_helper: `{:?}` is a union", adt_def);
244 adt_def.all_fields().map(|field| {
245 let r = tcx.type_of(field.did).subst(tcx, substs);
247 "drop_tys_helper: Subst into {:?} with {:?} gettng {:?}",
255 .map(|v| v.into_iter())
258 NeedsDropTypes::new(tcx, param_env, ty, adt_components)
261 fn adt_consider_insignificant_dtor<'tcx>(
263 ) -> impl Fn(&ty::AdtDef) -> Option<DtorType> + 'tcx {
264 move |adt_def: &ty::AdtDef| {
265 let is_marked_insig = tcx.has_attr(adt_def.did, sym::rustc_insignificant_dtor);
267 // In some cases like `std::collections::HashMap` where the struct is a wrapper around
268 // a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies
269 // outside stdlib, we might choose to still annotate the the wrapper (std HashMap) with
270 // `rustc_insignificant_dtor`, even if the type itself doesn't have a `Drop` impl.
271 Some(DtorType::Insignificant)
272 } else if adt_def.destructor(tcx).is_some() {
273 // There is a Drop impl and the type isn't marked insignificant, therefore Drop must be
275 Some(DtorType::Significant)
277 // No destructor found nor the type is annotated with `rustc_insignificant_dtor`, we
278 // treat this as the simple case of Drop impl for type.
284 fn adt_drop_tys(tcx: TyCtxt<'_>, def_id: DefId) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
285 // This is for the "adt_drop_tys" query, that considers all `Drop` impls, therefore all dtors are
288 |adt_def: &ty::AdtDef| adt_def.destructor(tcx).map(|_| DtorType::Significant);
289 // `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_substs)`
290 drop_tys_helper(tcx, tcx.type_of(def_id), tcx.param_env(def_id), adt_has_dtor, false)
291 .collect::<Result<Vec<_>, _>>()
292 .map(|components| tcx.intern_type_list(&components))
294 // If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed
295 // a `tcx.make_ty(def, identity_substs)` and as such it is legal to substitue the generic parameters
296 // of the ADT into the outputted `ty`s.
297 fn adt_significant_drop_tys(
300 ) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
303 tcx.type_of(def_id), // identical to `tcx.make_adt(def, identity_substs)`
304 tcx.param_env(def_id),
305 adt_consider_insignificant_dtor(tcx),
308 .collect::<Result<Vec<_>, _>>()
309 .map(|components| tcx.intern_type_list(&components))
312 pub(crate) fn provide(providers: &mut ty::query::Providers) {
313 *providers = ty::query::Providers {
315 has_significant_drop_raw,
317 adt_significant_drop_tys,