1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_hir::def_id::DefId;
3 use rustc_infer::infer::canonical::{Canonical, QueryResponse};
4 use rustc_infer::infer::TyCtxtInferExt;
5 use rustc_infer::traits::TraitEngineExt as _;
6 use rustc_middle::ty::query::Providers;
7 use rustc_middle::ty::subst::{InternalSubsts, Subst};
8 use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt};
9 use rustc_span::source_map::{Span, DUMMY_SP};
10 use rustc_trait_selection::traits::query::dropck_outlives::trivial_dropck_outlives;
11 use rustc_trait_selection::traits::query::dropck_outlives::{
12 DropckOutlivesResult, DtorckConstraint,
14 use rustc_trait_selection::traits::query::normalize::AtExt;
15 use rustc_trait_selection::traits::query::{CanonicalTyGoal, NoSolution};
16 use rustc_trait_selection::traits::{
17 Normalized, ObligationCause, TraitEngine, TraitEngineExt as _,
20 crate fn provide(p: &mut Providers) {
21 *p = Providers { dropck_outlives, adt_dtorck_constraint, ..*p };
24 fn dropck_outlives<'tcx>(
26 canonical_goal: CanonicalTyGoal<'tcx>,
27 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
28 debug!("dropck_outlives(goal={:#?})", canonical_goal);
30 tcx.infer_ctxt().enter_with_canonical(
33 |ref infcx, goal, canonical_inference_vars| {
35 let ParamEnvAnd { param_env, value: for_ty } = goal;
37 let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
39 // A stack of types left to process. Each round, we pop
40 // something from the stack and invoke
41 // `dtorck_constraint_for_ty`. This may produce new types that
42 // have to be pushed on the stack. This continues until we have explored
43 // all the reachable types from the type `for_ty`.
45 // Example: Imagine that we have the following code:
60 // } // here, `a` is dropped
63 // at the point where `a` is dropped, we need to figure out
64 // which types inside of `a` contain region data that may be
65 // accessed by any destructors in `a`. We begin by pushing `A`
66 // onto the stack, as that is the type of `a`. We will then
67 // invoke `dtorck_constraint_for_ty` which will expand `A`
68 // into the types of its fields `(B, Vec<A>)`. These will get
69 // pushed onto the stack. Eventually, expanding `Vec<A>` will
70 // lead to us trying to push `A` a second time -- to prevent
71 // infinite recursion, we notice that `A` was already pushed
73 let mut ty_stack = vec![(for_ty, 0)];
75 // Set used to detect infinite recursion.
76 let mut ty_set = FxHashSet::default();
78 let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
80 let cause = ObligationCause::dummy();
81 let mut constraints = DtorckConstraint::empty();
82 while let Some((ty, depth)) = ty_stack.pop() {
84 "{} kinds, {} overflows, {} ty_stack",
86 result.overflows.len(),
89 dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
91 // "outlives" represent types/regions that may be touched
93 result.kinds.append(&mut constraints.outlives);
94 result.overflows.append(&mut constraints.overflows);
96 // If we have even one overflow, we should stop trying to evaluate further --
97 // chances are, the subsequent overflows for this evaluation won't provide useful
98 // information and will just decrease the speed at which we can emit these errors
99 // (since we'll be printing for just that much longer for the often enormous types
100 // that result here).
101 if !result.overflows.is_empty() {
105 // dtorck types are "types that will get dropped but which
106 // do not themselves define a destructor", more or less. We have
107 // to push them onto the stack to be expanded.
108 for ty in constraints.dtorck_types.drain(..) {
109 match infcx.at(&cause, param_env).normalize(ty) {
110 Ok(Normalized { value: ty, obligations }) => {
111 fulfill_cx.register_predicate_obligations(infcx, obligations);
113 debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
116 // All parameters live for the duration of the
120 // A projection that we couldn't resolve - it
121 // might have a destructor.
122 ty::Projection(..) | ty::Opaque(..) => {
123 result.kinds.push(ty.into());
127 if ty_set.insert(ty) {
128 ty_stack.push((ty, depth + 1));
134 // We don't actually expect to fail to normalize.
135 // That implies a WF error somewhere else.
137 return Err(NoSolution);
143 debug!("dropck_outlives: result = {:#?}", result);
145 infcx.make_canonicalized_query_response(
146 canonical_inference_vars,
154 /// Returns a set of constraints that needs to be satisfied in
155 /// order for `ty` to be valid for destruction.
156 fn dtorck_constraint_for_ty<'tcx>(
162 constraints: &mut DtorckConstraint<'tcx>,
163 ) -> Result<(), NoSolution> {
164 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})", span, for_ty, depth, ty);
166 if !tcx.recursion_limit().value_within_limit(depth) {
167 constraints.overflows.push(ty);
171 if trivial_dropck_outlives(tcx, ty) {
188 | ty::GeneratorWitness(..) => {
189 // these types never have a destructor
192 ty::Array(ety, _) | ty::Slice(ety) => {
193 // single-element containers, behave like their element
194 rustc_data_structures::stack::ensure_sufficient_stack(|| {
195 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, *ety, constraints)
199 ty::Tuple(tys) => rustc_data_structures::stack::ensure_sufficient_stack(|| {
200 for ty in tys.iter() {
201 dtorck_constraint_for_ty(
210 Ok::<_, NoSolution>(())
213 ty::Closure(_, substs) => {
214 if !substs.as_closure().is_valid() {
215 // By the time this code runs, all type variables ought to
216 // be fully resolved.
218 tcx.sess.delay_span_bug(
220 &format!("upvar_tys for closure not found. Expected capture information for closure {}", ty,),
222 return Err(NoSolution);
225 rustc_data_structures::stack::ensure_sufficient_stack(|| {
226 for ty in substs.as_closure().upvar_tys() {
227 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty, constraints)?;
229 Ok::<_, NoSolution>(())
233 ty::Generator(_, substs, _movability) => {
234 // rust-lang/rust#49918: types can be constructed, stored
235 // in the interior, and sit idle when generator yields
236 // (and is subsequently dropped).
238 // It would be nice to descend into interior of a
239 // generator to determine what effects dropping it might
240 // have (by looking at any drop effects associated with
243 // However, the interior's representation uses things like
244 // GeneratorWitness that explicitly assume they are not
245 // traversed in such a manner. So instead, we will
246 // simplify things for now by treating all generators as
247 // if they were like trait objects, where its upvars must
248 // all be alive for the generator's (potential)
251 // In particular, skipping over `_interior` is safe
252 // because any side-effects from dropping `_interior` can
253 // only take place through references with lifetimes
254 // derived from lifetimes attached to the upvars and resume
255 // argument, and we *do* incorporate those here.
257 if !substs.as_generator().is_valid() {
258 // By the time this code runs, all type variables ought to
259 // be fully resolved.
260 tcx.sess.delay_span_bug(
262 &format!("upvar_tys for generator not found. Expected capture information for generator {}", ty,),
264 return Err(NoSolution);
267 constraints.outlives.extend(
271 .map(|t| -> ty::subst::GenericArg<'tcx> { t.into() }),
273 constraints.outlives.push(substs.as_generator().resume_ty().into());
276 ty::Adt(def, substs) => {
277 let DtorckConstraint { dtorck_types, outlives, overflows } =
278 tcx.at(span).adt_dtorck_constraint(def.did)?;
279 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
280 // there, but that needs some way to handle cycles.
281 constraints.dtorck_types.extend(dtorck_types.iter().map(|t| t.subst(tcx, substs)));
282 constraints.outlives.extend(outlives.iter().map(|t| t.subst(tcx, substs)));
283 constraints.overflows.extend(overflows.iter().map(|t| t.subst(tcx, substs)));
286 // Objects must be alive in order for their destructor
289 constraints.outlives.push(ty.into());
292 // Types that can't be resolved. Pass them forward.
293 ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => {
294 constraints.dtorck_types.push(ty);
297 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => {
298 // By the time this code runs, all type variables ought to
299 // be fully resolved.
300 return Err(NoSolution);
307 /// Calculates the dtorck constraint for a type.
308 crate fn adt_dtorck_constraint(
311 ) -> Result<&DtorckConstraint<'_>, NoSolution> {
312 let def = tcx.adt_def(def_id);
313 let span = tcx.def_span(def_id);
314 debug!("dtorck_constraint: {:?}", def);
316 if def.is_phantom_data() {
317 // The first generic parameter here is guaranteed to be a type because it's
319 let substs = InternalSubsts::identity_for_item(tcx, def_id);
320 assert_eq!(substs.len(), 1);
321 let result = DtorckConstraint {
323 dtorck_types: vec![substs.type_at(0)],
326 debug!("dtorck_constraint: {:?} => {:?}", def, result);
327 return Ok(tcx.arena.alloc(result));
330 let mut result = DtorckConstraint::empty();
331 for field in def.all_fields() {
332 let fty = tcx.type_of(field.did);
333 dtorck_constraint_for_ty(tcx, span, fty, 0, fty, &mut result)?;
335 result.outlives.extend(tcx.destructor_constraints(def));
336 dedup_dtorck_constraint(&mut result);
338 debug!("dtorck_constraint: {:?} => {:?}", def, result);
340 Ok(tcx.arena.alloc(result))
343 fn dedup_dtorck_constraint(c: &mut DtorckConstraint<'_>) {
344 let mut outlives = FxHashSet::default();
345 let mut dtorck_types = FxHashSet::default();
347 c.outlives.retain(|&val| outlives.replace(val).is_none());
348 c.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());