]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/needs_drop.rs
64f82817d3944e4636237b96c744f4d9d38e3bd3
[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::util::{needs_drop_components, AlwaysRequiresDrop};
7 use rustc_middle::ty::{self, Ty, TyCtxt};
8 use rustc_session::Limit;
9 use rustc_span::DUMMY_SP;
10
11 type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
12
13 fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
14     let adt_fields =
15         move |adt_def: &ty::AdtDef| tcx.adt_drop_tys(adt_def.did).map(|tys| tys.iter());
16     // If we don't know a type doesn't need drop, for example if it's a type
17     // parameter without a `Copy` bound, then we conservatively return that it
18     // needs drop.
19     let res = NeedsDropTypes::new(tcx, query.param_env, query.value, adt_fields).next().is_some();
20     debug!("needs_drop_raw({:?}) = {:?}", query, res);
21     res
22 }
23
24 struct NeedsDropTypes<'tcx, F> {
25     tcx: TyCtxt<'tcx>,
26     param_env: ty::ParamEnv<'tcx>,
27     query_ty: Ty<'tcx>,
28     seen_tys: FxHashSet<Ty<'tcx>>,
29     /// A stack of types left to process, and the recursion depth when we
30     /// pushed that type. Each round, we pop something from the stack and check
31     /// if it needs drop. If the result depends on whether some other types
32     /// need drop we push them onto the stack.
33     unchecked_tys: Vec<(Ty<'tcx>, usize)>,
34     recursion_limit: Limit,
35     adt_components: F,
36 }
37
38 impl<'tcx, F> NeedsDropTypes<'tcx, F> {
39     fn new(
40         tcx: TyCtxt<'tcx>,
41         param_env: ty::ParamEnv<'tcx>,
42         ty: Ty<'tcx>,
43         adt_components: F,
44     ) -> Self {
45         let mut seen_tys = FxHashSet::default();
46         seen_tys.insert(ty);
47         Self {
48             tcx,
49             param_env,
50             seen_tys,
51             query_ty: ty,
52             unchecked_tys: vec![(ty, 0)],
53             recursion_limit: tcx.sess.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 !self.recursion_limit.value_within_limit(level) {
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.at(DUMMY_SP), self.param_env) => (),
95
96                     ty::Closure(_, substs) => {
97                         queue_type(self, substs.as_closure().tupled_upvars_ty());
98                     }
99
100                     ty::Generator(def_id, substs, _) => {
101                         let substs = substs.as_generator();
102                         queue_type(self, substs.tupled_upvars_ty());
103
104                         let witness = substs.witness();
105                         let interior_tys = match witness.kind() {
106                             &ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys),
107                             _ => {
108                                 tcx.sess.delay_span_bug(
109                                     tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP),
110                                     &format!("unexpected generator witness type {:?}", witness),
111                                 );
112                                 return Some(Err(AlwaysRequiresDrop));
113                             }
114                         };
115
116                         for interior_ty in interior_tys {
117                             queue_type(self, interior_ty);
118                         }
119                     }
120
121                     // Check for a `Drop` impl and whether this is a union or
122                     // `ManuallyDrop`. If it's a struct or enum without a `Drop`
123                     // impl then check whether the field types need `Drop`.
124                     ty::Adt(adt_def, substs) => {
125                         let tys = match (self.adt_components)(adt_def) {
126                             Err(e) => return Some(Err(e)),
127                             Ok(tys) => tys,
128                         };
129                         for required_ty in tys {
130                             let subst_ty = tcx.normalize_erasing_regions(
131                                 self.param_env,
132                                 required_ty.subst(tcx, substs),
133                             );
134                             queue_type(self, subst_ty);
135                         }
136                     }
137                     ty::Array(..) | ty::Opaque(..) | ty::Projection(..) | ty::Param(_) => {
138                         if ty == component {
139                             // Return the type to the caller: they may be able
140                             // to normalize further than we can.
141                             return Some(Ok(component));
142                         } else {
143                             // Store the type for later. We can't return here
144                             // because we would then lose any other components
145                             // of the type.
146                             queue_type(self, component);
147                         }
148                     }
149                     _ => return Some(Err(AlwaysRequiresDrop)),
150                 }
151             }
152         }
153
154         None
155     }
156 }
157
158 fn adt_drop_tys(tcx: TyCtxt<'_>, def_id: DefId) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
159     let adt_components = move |adt_def: &ty::AdtDef| {
160         if adt_def.is_manually_drop() {
161             debug!("adt_drop_tys: `{:?}` is manually drop", adt_def);
162             return Ok(Vec::new().into_iter());
163         } else if adt_def.destructor(tcx).is_some() {
164             debug!("adt_drop_tys: `{:?}` implements `Drop`", adt_def);
165             return Err(AlwaysRequiresDrop);
166         } else if adt_def.is_union() {
167             debug!("adt_drop_tys: `{:?}` is a union", adt_def);
168             return Ok(Vec::new().into_iter());
169         }
170         Ok(adt_def.all_fields().map(|field| tcx.type_of(field.did)).collect::<Vec<_>>().into_iter())
171     };
172
173     let adt_ty = tcx.type_of(def_id);
174     let param_env = tcx.param_env(def_id);
175     let res: Result<Vec<_>, _> =
176         NeedsDropTypes::new(tcx, param_env, adt_ty, adt_components).collect();
177
178     debug!("adt_drop_tys(`{}`) = `{:?}`", tcx.def_path_str(def_id), res);
179     res.map(|components| tcx.intern_type_list(&components))
180 }
181
182 pub(crate) fn provide(providers: &mut ty::query::Providers) {
183     *providers = ty::query::Providers { needs_drop_raw, adt_drop_tys, ..*providers };
184 }