]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/needs_drop.rs
Rollup merge of #71165 - lcnr:patch-2, r=Amanieu
[rust.git] / src / librustc_ty / 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::util::{needs_drop_components, AlwaysRequiresDrop};
7 use rustc_middle::ty::{self, Ty, TyCtxt};
8 use rustc_span::DUMMY_SP;
9
10 type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
11
12 fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
13     let adt_fields =
14         move |adt_def: &ty::AdtDef| tcx.adt_drop_tys(adt_def.did).map(|tys| tys.iter().copied());
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
17     // needs drop.
18     let res = NeedsDropTypes::new(tcx, query.param_env, query.value, adt_fields).next().is_some();
19     debug!("needs_drop_raw({:?}) = {:?}", query, res);
20     res
21 }
22
23 struct NeedsDropTypes<'tcx, F> {
24     tcx: TyCtxt<'tcx>,
25     param_env: ty::ParamEnv<'tcx>,
26     query_ty: Ty<'tcx>,
27     seen_tys: FxHashSet<Ty<'tcx>>,
28     /// A stack of types left to process, and the recursion depth when we
29     /// pushed that type. Each round, we pop something from the stack and check
30     /// if it needs drop. If the result depends on whether some other types
31     /// need drop we push them onto the stack.
32     unchecked_tys: Vec<(Ty<'tcx>, usize)>,
33     recursion_limit: usize,
34     adt_components: F,
35 }
36
37 impl<'tcx, F> NeedsDropTypes<'tcx, F> {
38     fn new(
39         tcx: TyCtxt<'tcx>,
40         param_env: ty::ParamEnv<'tcx>,
41         ty: Ty<'tcx>,
42         adt_components: F,
43     ) -> Self {
44         let mut seen_tys = FxHashSet::default();
45         seen_tys.insert(ty);
46         let recursion_limit = *tcx.sess.recursion_limit.get();
47         Self {
48             tcx,
49             param_env,
50             seen_tys,
51             query_ty: ty,
52             unchecked_tys: vec![(ty, 0)],
53             recursion_limit,
54             adt_components,
55         }
56     }
57 }
58
59 impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F>
60 where
61     F: Fn(&ty::AdtDef) -> NeedsDropResult<I>,
62     I: Iterator<Item = Ty<'tcx>>,
63 {
64     type Item = NeedsDropResult<Ty<'tcx>>;
65
66     fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
67         let tcx = self.tcx;
68
69         while let Some((ty, level)) = self.unchecked_tys.pop() {
70             if level > self.recursion_limit {
71                 // Not having a `Span` isn't great. But there's hopefully some other
72                 // recursion limit error as well.
73                 tcx.sess.span_err(
74                     DUMMY_SP,
75                     &format!("overflow while checking whether `{}` requires drop", self.query_ty),
76                 );
77                 return Some(Err(AlwaysRequiresDrop));
78             }
79
80             let components = match needs_drop_components(ty, &tcx.data_layout) {
81                 Err(e) => return Some(Err(e)),
82                 Ok(components) => components,
83             };
84             debug!("needs_drop_components({:?}) = {:?}", ty, components);
85
86             let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
87                 if this.seen_tys.insert(component) {
88                     this.unchecked_tys.push((component, level + 1));
89                 }
90             };
91
92             for component in components {
93                 match component.kind {
94                     _ if component.is_copy_modulo_regions(tcx, self.param_env, DUMMY_SP) => (),
95
96                     ty::Closure(_, substs) => {
97                         for upvar_ty in substs.as_closure().upvar_tys() {
98                             queue_type(self, upvar_ty);
99                         }
100                     }
101
102                     ty::Generator(_, substs, _) => {
103                         let substs = substs.as_generator();
104                         for upvar_ty in substs.upvar_tys() {
105                             queue_type(self, upvar_ty);
106                         }
107
108                         let witness = substs.witness();
109                         let interior_tys = match &witness.kind {
110                             ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys),
111                             _ => bug!(),
112                         };
113
114                         for interior_ty in interior_tys {
115                             queue_type(self, interior_ty);
116                         }
117                     }
118
119                     // Check for a `Drop` impl and whether this is a union or
120                     // `ManuallyDrop`. If it's a struct or enum without a `Drop`
121                     // impl then check whether the field types need `Drop`.
122                     ty::Adt(adt_def, substs) => {
123                         let tys = match (self.adt_components)(adt_def) {
124                             Err(e) => return Some(Err(e)),
125                             Ok(tys) => tys,
126                         };
127                         for required_ty in tys {
128                             let subst_ty = tcx.normalize_erasing_regions(
129                                 self.param_env,
130                                 required_ty.subst(tcx, substs),
131                             );
132                             queue_type(self, subst_ty);
133                         }
134                     }
135                     ty::Array(..) | ty::Opaque(..) | ty::Projection(..) | ty::Param(_) => {
136                         if ty == component {
137                             // Return the type to the caller: they may be able
138                             // to normalize further than we can.
139                             return Some(Ok(component));
140                         } else {
141                             // Store the type for later. We can't return here
142                             // because we would then lose any other components
143                             // of the type.
144                             queue_type(self, component);
145                         }
146                     }
147                     _ => return Some(Err(AlwaysRequiresDrop)),
148                 }
149             }
150         }
151
152         None
153     }
154 }
155
156 fn adt_drop_tys(tcx: TyCtxt<'_>, def_id: DefId) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
157     let adt_components = move |adt_def: &ty::AdtDef| {
158         if adt_def.is_manually_drop() {
159             debug!("adt_drop_tys: `{:?}` is manually drop", adt_def);
160             return Ok(Vec::new().into_iter());
161         } else if adt_def.destructor(tcx).is_some() {
162             debug!("adt_drop_tys: `{:?}` implements `Drop`", adt_def);
163             return Err(AlwaysRequiresDrop);
164         } else if adt_def.is_union() {
165             debug!("adt_drop_tys: `{:?}` is a union", adt_def);
166             return Ok(Vec::new().into_iter());
167         }
168         Ok(adt_def.all_fields().map(|field| tcx.type_of(field.did)).collect::<Vec<_>>().into_iter())
169     };
170
171     let adt_ty = tcx.type_of(def_id);
172     let param_env = tcx.param_env(def_id);
173     let res: Result<Vec<_>, _> =
174         NeedsDropTypes::new(tcx, param_env, adt_ty, adt_components).collect();
175
176     debug!("adt_drop_tys(`{}`) = `{:?}`", tcx.def_path_str(def_id), res);
177     res.map(|components| tcx.intern_type_list(&components))
178 }
179
180 pub(crate) fn provide(providers: &mut ty::query::Providers<'_>) {
181     *providers = ty::query::Providers { needs_drop_raw, adt_drop_tys, ..*providers };
182 }