]> git.proxmox.com Git - rustc.git/blame - src/librustc_traits/dropck_outlives.rs
New upstream version 1.42.0+dfsg1
[rustc.git] / src / librustc_traits / dropck_outlives.rs
CommitLineData
0bf4aa26 1use rustc::infer::canonical::{Canonical, QueryResponse};
60c5eb7d 2use rustc::traits::query::dropck_outlives::trivial_dropck_outlives;
dfeec247 3use rustc::traits::query::dropck_outlives::{DropckOutlivesResult, DtorckConstraint};
0531ce1d 4use rustc::traits::query::{CanonicalTyGoal, NoSolution};
dfeec247 5use rustc::traits::{Normalized, ObligationCause, TraitEngine, TraitEngineExt};
8faf50e0 6use rustc::ty::query::Providers;
dfeec247 7use rustc::ty::subst::{InternalSubsts, Subst};
8faf50e0 8use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt};
dfeec247
XL
9use rustc_data_structures::fx::FxHashSet;
10use rustc_hir::def_id::DefId;
11use rustc_span::source_map::{Span, DUMMY_SP};
0531ce1d 12
9fa01778 13crate fn provide(p: &mut Providers<'_>) {
dfeec247 14 *p = Providers { dropck_outlives, adt_dtorck_constraint, ..*p };
8faf50e0
XL
15}
16
17fn dropck_outlives<'tcx>(
dc9dc135 18 tcx: TyCtxt<'tcx>,
0bf4aa26 19 canonical_goal: CanonicalTyGoal<'tcx>,
48663c56 20) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
0bf4aa26
XL
21 debug!("dropck_outlives(goal={:#?})", canonical_goal);
22
23 tcx.infer_ctxt().enter_with_canonical(
24 DUMMY_SP,
25 &canonical_goal,
26 |ref infcx, goal, canonical_inference_vars| {
27 let tcx = infcx.tcx;
dfeec247 28 let ParamEnvAnd { param_env, value: for_ty } = goal;
0531ce1d 29
dfeec247 30 let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
0531ce1d 31
0bf4aa26
XL
32 // A stack of types left to process. Each round, we pop
33 // something from the stack and invoke
34 // `dtorck_constraint_for_ty`. This may produce new types that
35 // have to be pushed on the stack. This continues until we have explored
36 // all the reachable types from the type `for_ty`.
37 //
38 // Example: Imagine that we have the following code:
39 //
40 // ```rust
41 // struct A {
42 // value: B,
43 // children: Vec<A>,
44 // }
45 //
46 // struct B {
47 // value: u32
48 // }
49 //
50 // fn f() {
51 // let a: A = ...;
52 // ..
53 // } // here, `a` is dropped
54 // ```
55 //
56 // at the point where `a` is dropped, we need to figure out
57 // which types inside of `a` contain region data that may be
58 // accessed by any destructors in `a`. We begin by pushing `A`
59 // onto the stack, as that is the type of `a`. We will then
60 // invoke `dtorck_constraint_for_ty` which will expand `A`
61 // into the types of its fields `(B, Vec<A>)`. These will get
62 // pushed onto the stack. Eventually, expanding `Vec<A>` will
63 // lead to us trying to push `A` a second time -- to prevent
64 // infinite recursion, we notice that `A` was already pushed
65 // once and stop.
66 let mut ty_stack = vec![(for_ty, 0)];
67
68 // Set used to detect infinite recursion.
69 let mut ty_set = FxHashSet::default();
70
0731742a 71 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
0bf4aa26
XL
72
73 let cause = ObligationCause::dummy();
e74abb32 74 let mut constraints = DtorckConstraint::empty();
0bf4aa26 75 while let Some((ty, depth)) = ty_stack.pop() {
dfeec247
XL
76 info!(
77 "{} kinds, {} overflows, {} ty_stack",
78 result.kinds.len(),
79 result.overflows.len(),
80 ty_stack.len()
81 );
e74abb32 82 dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
0bf4aa26
XL
83
84 // "outlives" represent types/regions that may be touched
85 // by a destructor.
e74abb32
XL
86 result.kinds.extend(constraints.outlives.drain(..));
87 result.overflows.extend(constraints.overflows.drain(..));
88
89 // If we have even one overflow, we should stop trying to evaluate further --
90 // chances are, the subsequent overflows for this evaluation won't provide useful
91 // information and will just decrease the speed at which we can emit these errors
92 // (since we'll be printing for just that much longer for the often enormous types
93 // that result here).
94 if result.overflows.len() >= 1 {
95 break;
96 }
0bf4aa26
XL
97
98 // dtorck types are "types that will get dropped but which
99 // do not themselves define a destructor", more or less. We have
100 // to push them onto the stack to be expanded.
e74abb32 101 for ty in constraints.dtorck_types.drain(..) {
0bf4aa26 102 match infcx.at(&cause, param_env).normalize(&ty) {
dfeec247 103 Ok(Normalized { value: ty, obligations }) => {
0bf4aa26
XL
104 fulfill_cx.register_predicate_obligations(infcx, obligations);
105
106 debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
107
e74abb32 108 match ty.kind {
0bf4aa26
XL
109 // All parameters live for the duration of the
110 // function.
111 ty::Param(..) => {}
112
113 // A projection that we couldn't resolve - it
114 // might have a destructor.
115 ty::Projection(..) | ty::Opaque(..) => {
116 result.kinds.push(ty.into());
117 }
0531ce1d 118
0bf4aa26
XL
119 _ => {
120 if ty_set.insert(ty) {
121 ty_stack.push((ty, depth + 1));
122 }
0531ce1d
XL
123 }
124 }
125 }
0531ce1d 126
0bf4aa26
XL
127 // We don't actually expect to fail to normalize.
128 // That implies a WF error somewhere else.
129 Err(NoSolution) => {
130 return Err(NoSolution);
131 }
0531ce1d
XL
132 }
133 }
134 }
0531ce1d 135
0bf4aa26 136 debug!("dropck_outlives: result = {:#?}", result);
0531ce1d 137
0731742a
XL
138 infcx.make_canonicalized_query_response(
139 canonical_inference_vars,
140 result,
dfeec247 141 &mut *fulfill_cx,
0731742a 142 )
0bf4aa26
XL
143 },
144 )
0531ce1d
XL
145}
146
9fa01778 147/// Returns a set of constraints that needs to be satisfied in
0531ce1d 148/// order for `ty` to be valid for destruction.
dc9dc135
XL
149fn dtorck_constraint_for_ty<'tcx>(
150 tcx: TyCtxt<'tcx>,
0531ce1d
XL
151 span: Span,
152 for_ty: Ty<'tcx>,
153 depth: usize,
154 ty: Ty<'tcx>,
e74abb32
XL
155 constraints: &mut DtorckConstraint<'tcx>,
156) -> Result<(), NoSolution> {
dfeec247 157 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})", span, for_ty, depth, ty);
0531ce1d 158
83c7162d 159 if depth >= *tcx.sess.recursion_limit.get() {
e74abb32
XL
160 constraints.overflows.push(ty);
161 return Ok(());
0531ce1d
XL
162 }
163
60c5eb7d 164 if trivial_dropck_outlives(tcx, ty) {
e74abb32
XL
165 return Ok(());
166 }
167
168 match ty.kind {
b7449926
XL
169 ty::Bool
170 | ty::Char
171 | ty::Int(_)
172 | ty::Uint(_)
173 | ty::Float(_)
174 | ty::Str
175 | ty::Never
176 | ty::Foreign(..)
177 | ty::RawPtr(..)
178 | ty::Ref(..)
179 | ty::FnDef(..)
180 | ty::FnPtr(_)
181 | ty::GeneratorWitness(..) => {
0531ce1d 182 // these types never have a destructor
0531ce1d
XL
183 }
184
b7449926 185 ty::Array(ety, _) | ty::Slice(ety) => {
0531ce1d 186 // single-element containers, behave like their element
e74abb32 187 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ety, constraints)?;
0531ce1d
XL
188 }
189
dfeec247
XL
190 ty::Tuple(tys) => {
191 for ty in tys.iter() {
192 dtorck_constraint_for_ty(
193 tcx,
194 span,
195 for_ty,
196 depth + 1,
197 ty.expect_ty(),
198 constraints,
199 )?;
200 }
201 }
0531ce1d 202
dfeec247
XL
203 ty::Closure(def_id, substs) => {
204 for ty in substs.as_closure().upvar_tys(def_id, tcx) {
205 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty, constraints)?;
206 }
e74abb32 207 }
0531ce1d 208
b7449926 209 ty::Generator(def_id, substs, _movability) => {
83c7162d
XL
210 // rust-lang/rust#49918: types can be constructed, stored
211 // in the interior, and sit idle when generator yields
212 // (and is subsequently dropped).
213 //
214 // It would be nice to descend into interior of a
215 // generator to determine what effects dropping it might
216 // have (by looking at any drop effects associated with
217 // its interior).
218 //
219 // However, the interior's representation uses things like
b7449926 220 // GeneratorWitness that explicitly assume they are not
83c7162d
XL
221 // traversed in such a manner. So instead, we will
222 // simplify things for now by treating all generators as
223 // if they were like trait objects, where its upvars must
224 // all be alive for the generator's (potential)
225 // destructor.
226 //
227 // In particular, skipping over `_interior` is safe
228 // because any side-effects from dropping `_interior` can
229 // only take place through references with lifetimes
230 // derived from lifetimes attached to the upvars, and we
231 // *do* incorporate the upvars here.
232
dfeec247
XL
233 constraints.outlives.extend(
234 substs
235 .as_generator()
236 .upvar_tys(def_id, tcx)
237 .map(|t| -> ty::subst::GenericArg<'tcx> { t.into() }),
238 );
0531ce1d
XL
239 }
240
b7449926 241 ty::Adt(def, substs) => {
dfeec247
XL
242 let DtorckConstraint { dtorck_types, outlives, overflows } =
243 tcx.at(span).adt_dtorck_constraint(def.did)?;
e74abb32
XL
244 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
245 // there, but that needs some way to handle cycles.
246 constraints.dtorck_types.extend(dtorck_types.subst(tcx, substs));
247 constraints.outlives.extend(outlives.subst(tcx, substs));
248 constraints.overflows.extend(overflows.subst(tcx, substs));
0531ce1d
XL
249 }
250
251 // Objects must be alive in order for their destructor
252 // to be called.
e74abb32
XL
253 ty::Dynamic(..) => {
254 constraints.outlives.push(ty.into());
dfeec247 255 }
0531ce1d
XL
256
257 // Types that can't be resolved. Pass them forward.
e74abb32
XL
258 ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => {
259 constraints.dtorck_types.push(ty);
dfeec247 260 }
0531ce1d 261
0bf4aa26
XL
262 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
263
a1dfa0c6 264 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => {
0531ce1d
XL
265 // By the time this code runs, all type variables ought to
266 // be fully resolved.
dfeec247 267 return Err(NoSolution);
0531ce1d 268 }
e74abb32 269 }
0531ce1d 270
e74abb32 271 Ok(())
0531ce1d
XL
272}
273
274/// Calculates the dtorck constraint for a type.
416331ca
XL
275crate fn adt_dtorck_constraint(
276 tcx: TyCtxt<'_>,
0531ce1d 277 def_id: DefId,
416331ca 278) -> Result<DtorckConstraint<'_>, NoSolution> {
0531ce1d
XL
279 let def = tcx.adt_def(def_id);
280 let span = tcx.def_span(def_id);
281 debug!("dtorck_constraint: {:?}", def);
282
283 if def.is_phantom_data() {
94b46f34
XL
284 // The first generic parameter here is guaranteed to be a type because it's
285 // `PhantomData`.
532ac7d7 286 let substs = InternalSubsts::identity_for_item(tcx, def_id);
94b46f34 287 assert_eq!(substs.len(), 1);
0531ce1d
XL
288 let result = DtorckConstraint {
289 outlives: vec![],
94b46f34 290 dtorck_types: vec![substs.type_at(0)],
0531ce1d
XL
291 overflows: vec![],
292 };
293 debug!("dtorck_constraint: {:?} => {:?}", def, result);
294 return Ok(result);
295 }
296
e74abb32
XL
297 let mut result = DtorckConstraint::empty();
298 for field in def.all_fields() {
299 let fty = tcx.type_of(field.did);
300 dtorck_constraint_for_ty(tcx, span, fty, 0, fty, &mut result)?;
301 }
0531ce1d
XL
302 result.outlives.extend(tcx.destructor_constraints(def));
303 dedup_dtorck_constraint(&mut result);
304
305 debug!("dtorck_constraint: {:?} => {:?}", def, result);
306
307 Ok(result)
308}
309
416331ca 310fn dedup_dtorck_constraint(c: &mut DtorckConstraint<'_>) {
0bf4aa26
XL
311 let mut outlives = FxHashSet::default();
312 let mut dtorck_types = FxHashSet::default();
0531ce1d
XL
313
314 c.outlives.retain(|&val| outlives.replace(val).is_none());
dfeec247 315 c.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
0531ce1d 316}