1 //! Code that handles "type-outlives" constraints like `T: 'a`. This
2 //! is based on the `push_outlives_components` function defined on the tcx,
3 //! but it adds a bit of heuristics on top, in particular to deal with
4 //! associated types and projections.
6 //! When we process a given `T: 'a` obligation, we may produce two
7 //! kinds of constraints for the region inferencer:
9 //! - Relationships between inference variables and other regions.
10 //! For example, if we have `&'?0 u32: 'a`, then we would produce
11 //! a constraint that `'a <= '?0`.
12 //! - "Verifys" that must be checked after inferencing is done.
13 //! For example, if we know that, for some type parameter `T`,
14 //! `T: 'a + 'b`, and we have a requirement that `T: '?1`,
15 //! then we add a "verify" that checks that `'?1 <= 'a || '?1 <= 'b`.
16 //! - Note the difference with the previous case: here, the region
17 //! variable must be less than something else, so this doesn't
18 //! affect how inference works (it finds the smallest region that
19 //! will do); it's just a post-condition that we have to check.
21 //! **The key point is that once this function is done, we have
22 //! reduced all of our "type-region outlives" obligations into relationships
23 //! between individual regions.**
25 //! One key input to this function is the set of "region-bound pairs".
26 //! These are basically the relationships between type parameters and
27 //! regions that are in scope at the point where the outlives
28 //! obligation was incurred. **When type-checking a function,
29 //! particularly in the face of closures, this is not known until
30 //! regionck runs!** This is because some of those bounds come
31 //! from things we have yet to infer.
36 //! fn bar<T>(a: T, b: impl for<'a> Fn(&'a T));
38 //! bar(x, |y| { ... })
43 //! Here, the type of `y` may involve inference variables and the
44 //! like, and it may also contain implied bounds that are needed to
45 //! type-check the closure body (e.g., here it informs us that `T`
46 //! outlives the late-bound region `'a`).
48 //! Note that by delaying the gathering of implied bounds until all
49 //! inference information is known, we may find relationships between
50 //! bound regions and other regions in the environment. For example,
51 //! when we first check a closure like the one expected as argument
55 //! fn foo<U, F: for<'a> FnMut(&'a U)>(_f: F) {}
58 //! the type of the closure's first argument would be `&'a ?U`. We
59 //! might later infer `?U` to something like `&'b u32`, which would
60 //! imply that `'b: 'a`.
62 use crate::infer::outlives::env::RegionBoundPairs;
63 use crate::infer::outlives::verify::VerifyBoundCx;
64 use crate::infer::{self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, VerifyBound};
65 use rustc_data_structures::fx::FxHashMap;
67 use crate::traits::ObligationCause;
68 use crate::ty::outlives::Component;
69 use crate::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
71 impl<'cx, 'gcx, 'tcx> InferCtxt<'cx, 'gcx, 'tcx> {
72 /// Registers that the given region obligation must be resolved
73 /// from within the scope of `body_id`. These regions are enqueued
74 /// and later processed by regionck, when full type information is
75 /// available (see `region_obligations` field for more
77 pub fn register_region_obligation(
80 obligation: RegionObligation<'tcx>,
83 "register_region_obligation(body_id={:?}, obligation={:?})",
87 self.region_obligations
89 .push((body_id, obligation));
92 pub fn register_region_obligation_with_cause(
95 sub_region: Region<'tcx>,
96 cause: &ObligationCause<'tcx>,
98 let origin = SubregionOrigin::from_obligation_cause(cause, || {
99 infer::RelateParamBound(cause.span, sup_type)
102 self.register_region_obligation(
112 /// Trait queries just want to pass back type obligations "as is"
113 pub fn take_registered_region_obligations(&self) -> Vec<(ast::NodeId, RegionObligation<'tcx>)> {
114 ::std::mem::replace(&mut *self.region_obligations.borrow_mut(), vec![])
117 /// Process the region obligations that must be proven (during
118 /// `regionck`) for the given `body_id`, given information about
119 /// the region bounds in scope and so forth. This function must be
120 /// invoked for all relevant body-ids before region inference is
121 /// done (or else an assert will fire).
123 /// See the `region_obligations` field of `InferCtxt` for some
124 /// comments about how this function fits into the overall expected
125 /// flow of the inferencer. The key point is that it is
126 /// invoked after all type-inference variables have been bound --
127 /// towards the end of regionck. This also ensures that the
128 /// region-bound-pairs are available (see comments above regarding
133 /// - `region_bound_pairs`: the set of region bounds implied by
134 /// the parameters and where-clauses. In particular, each pair
135 /// `('a, K)` in this list tells us that the bounds in scope
136 /// indicate that `K: 'a`, where `K` is either a generic
137 /// parameter like `T` or a projection like `T::Item`.
138 /// - `implicit_region_bound`: if some, this is a region bound
139 /// that is considered to hold for all type parameters (the
141 /// - `param_env` is the parameter environment for the enclosing function.
142 /// - `body_id` is the body-id whose region obligations are being
147 /// This function may have to perform normalizations, and hence it
148 /// returns an `InferOk` with subobligations that must be
150 pub fn process_registered_region_obligations(
152 region_bound_pairs_map: &FxHashMap<ast::NodeId, RegionBoundPairs<'tcx>>,
153 implicit_region_bound: Option<ty::Region<'tcx>>,
154 param_env: ty::ParamEnv<'tcx>,
157 !self.in_snapshot.get(),
158 "cannot process registered region obligations in a snapshot"
161 debug!("process_registered_region_obligations()");
163 let my_region_obligations = self.take_registered_region_obligations();
172 ) in my_region_obligations
175 "process_registered_region_obligations: sup_type={:?} sub_region={:?} origin={:?}",
176 sup_type, sub_region, origin
179 let sup_type = self.resolve_type_vars_if_possible(&sup_type);
181 if let Some(region_bound_pairs) = region_bound_pairs_map.get(&body_id) {
182 let outlives = &mut TypeOutlives::new(
186 implicit_region_bound,
189 outlives.type_must_outlive(origin, sup_type, sub_region);
191 self.tcx.sess.delay_span_bug(
193 &format!("no region-bound-pairs for {:?}", body_id),
199 /// Processes a single ad-hoc region obligation that was not
200 /// registered in advance.
201 pub fn type_must_outlive(
203 region_bound_pairs: &RegionBoundPairs<'tcx>,
204 implicit_region_bound: Option<ty::Region<'tcx>>,
205 param_env: ty::ParamEnv<'tcx>,
206 origin: infer::SubregionOrigin<'tcx>,
208 region: ty::Region<'tcx>,
210 let outlives = &mut TypeOutlives::new(
214 implicit_region_bound,
217 let ty = self.resolve_type_vars_if_possible(&ty);
218 outlives.type_must_outlive(origin, ty, region);
222 /// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
223 /// obligation into a series of `'a: 'b` constraints and "verifys", as
224 /// described on the module comment. The final constraints are emitted
225 /// via a "delegate" of type `D` -- this is usually the `infcx`, which
226 /// accrues them into the `region_obligations` code, but for NLL we
227 /// use something else.
228 pub struct TypeOutlives<'cx, 'gcx: 'tcx, 'tcx: 'cx, D>
230 D: TypeOutlivesDelegate<'tcx>,
232 // See the comments on `process_registered_region_obligations` for the meaning
235 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
236 verify_bound: VerifyBoundCx<'cx, 'gcx, 'tcx>,
239 pub trait TypeOutlivesDelegate<'tcx> {
240 fn push_sub_region_constraint(
242 origin: SubregionOrigin<'tcx>,
249 origin: SubregionOrigin<'tcx>,
250 kind: GenericKind<'tcx>,
252 bound: VerifyBound<'tcx>,
256 impl<'cx, 'gcx, 'tcx, D> TypeOutlives<'cx, 'gcx, 'tcx, D>
258 D: TypeOutlivesDelegate<'tcx>,
262 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
263 region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
264 implicit_region_bound: Option<ty::Region<'tcx>>,
265 param_env: ty::ParamEnv<'tcx>,
270 verify_bound: VerifyBoundCx::new(
273 implicit_region_bound,
279 /// Adds constraints to inference such that `T: 'a` holds (or
280 /// reports an error if it cannot).
284 /// - `origin`, the reason we need this constraint
285 /// - `ty`, the type `T`
286 /// - `region`, the region `'a`
287 pub fn type_must_outlive(
289 origin: infer::SubregionOrigin<'tcx>,
291 region: ty::Region<'tcx>,
294 "type_must_outlive(ty={:?}, region={:?}, origin={:?})",
298 assert!(!ty.has_escaping_bound_vars());
300 let mut components = smallvec![];
301 self.tcx.push_outlives_components(ty, &mut components);
302 self.components_must_outlive(origin, &components, region);
305 fn components_must_outlive(
307 origin: infer::SubregionOrigin<'tcx>,
308 components: &[Component<'tcx>],
309 region: ty::Region<'tcx>,
311 for component in components.iter() {
312 let origin = origin.clone();
314 Component::Region(region1) => {
316 .push_sub_region_constraint(origin, region, region1);
318 Component::Param(param_ty) => {
319 self.param_ty_must_outlive(origin, region, *param_ty);
321 Component::Projection(projection_ty) => {
322 self.projection_must_outlive(origin, region, *projection_ty);
324 Component::EscapingProjection(subcomponents) => {
325 self.components_must_outlive(origin, &subcomponents, region);
327 Component::UnresolvedInferenceVariable(v) => {
328 // ignore this, we presume it will yield an error
329 // later, since if a type variable is not resolved by
330 // this point it never will be
331 self.tcx.sess.delay_span_bug(
333 &format!("unresolved inference variable in outlives: {:?}", v),
340 fn param_ty_must_outlive(
342 origin: infer::SubregionOrigin<'tcx>,
343 region: ty::Region<'tcx>,
344 param_ty: ty::ParamTy,
347 "param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
348 region, param_ty, origin
351 let generic = GenericKind::Param(param_ty);
352 let verify_bound = self.verify_bound.generic_bound(generic);
354 .push_verify(origin, generic, region, verify_bound);
357 fn projection_must_outlive(
359 origin: infer::SubregionOrigin<'tcx>,
360 region: ty::Region<'tcx>,
361 projection_ty: ty::ProjectionTy<'tcx>,
364 "projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
365 region, projection_ty, origin
368 // This case is thorny for inference. The fundamental problem is
369 // that there are many cases where we have choice, and inference
370 // doesn't like choice (the current region inference in
371 // particular). :) First off, we have to choose between using the
372 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
373 // OutlivesProjectionComponent rules, any one of which is
374 // sufficient. If there are no inference variables involved, it's
375 // not hard to pick the right rule, but if there are, we're in a
376 // bit of a catch 22: if we picked which rule we were going to
377 // use, we could add constraints to the region inference graph
378 // that make it apply, but if we don't add those constraints, the
379 // rule might not apply (but another rule might). For now, we err
380 // on the side of adding too few edges into the graph.
382 // Compute the bounds we can derive from the trait definition.
383 // These are guaranteed to apply, no matter the inference
385 let trait_bounds: Vec<_> = self.verify_bound
386 .projection_declared_bounds_from_trait(projection_ty)
389 // Compute the bounds we can derive from the environment. This
390 // is an "approximate" match -- in some cases, these bounds
392 let mut approx_env_bounds = self.verify_bound
393 .projection_approx_declared_bounds_from_env(projection_ty);
395 "projection_must_outlive: approx_env_bounds={:?}",
399 // Remove outlives bounds that we get from the environment but
400 // which are also deducable from the trait. This arises (cc
401 // #55756) in cases where you have e.g., `<T as Foo<'a>>::Item:
402 // 'a` in the environment but `trait Foo<'b> { type Item: 'b
403 // }` in the trait definition.
404 approx_env_bounds.retain(|bound| {
406 ty::Projection(projection_ty) => {
407 self.verify_bound.projection_declared_bounds_from_trait(projection_ty)
408 .all(|r| r != bound.1)
411 _ => panic!("expected only projection types from env, not {:?}", bound.0),
415 // If declared bounds list is empty, the only applicable rule is
416 // OutlivesProjectionComponent. If there are inference variables,
417 // then, we can break down the outlives into more primitive
418 // components without adding unnecessary edges.
420 // If there are *no* inference variables, however, we COULD do
421 // this, but we choose not to, because the error messages are less
422 // good. For example, a requirement like `T::Item: 'r` would be
423 // translated to a requirement that `T: 'r`; when this is reported
424 // to the user, it will thus say "T: 'r must hold so that T::Item:
425 // 'r holds". But that makes it sound like the only way to fix
426 // the problem is to add `T: 'r`, which isn't true. So, if there are no
427 // inference variables, we use a verify constraint instead of adding
428 // edges, which winds up enforcing the same condition.
429 let needs_infer = projection_ty.needs_infer();
430 if approx_env_bounds.is_empty() && trait_bounds.is_empty() && needs_infer {
431 debug!("projection_must_outlive: no declared bounds");
433 for component_ty in projection_ty.substs.types() {
434 self.type_must_outlive(origin.clone(), component_ty, region);
437 for r in projection_ty.substs.regions() {
439 .push_sub_region_constraint(origin.clone(), region, r);
445 // If we found a unique bound `'b` from the trait, and we
446 // found nothing else from the environment, then the best
447 // action is to require that `'b: 'r`, so do that.
449 // This is best no matter what rule we use:
451 // - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
452 // - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
453 // - OutlivesProjectionComponent: this would require `'b:'r`
454 // in addition to other conditions
455 if !trait_bounds.is_empty()
458 .chain(approx_env_bounds.iter().map(|b| &b.1))
459 .all(|b| *b == trait_bounds[0])
461 let unique_bound = trait_bounds[0];
463 "projection_must_outlive: unique trait bound = {:?}",
466 debug!("projection_must_outlive: unique declared bound appears in trait ref");
468 .push_sub_region_constraint(origin, region, unique_bound);
472 // Fallback to verifying after the fact that there exists a
473 // declared bound, or that all the components appearing in the
474 // projection outlive; in some cases, this may add insufficient
475 // edges into the inference graph, leading to inference failures
476 // even though a satisfactory solution exists.
477 let generic = GenericKind::Projection(projection_ty);
478 let verify_bound = self.verify_bound.generic_bound(generic);
480 .push_verify(origin, generic.clone(), region, verify_bound);
484 impl<'cx, 'gcx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'cx, 'gcx, 'tcx> {
485 fn push_sub_region_constraint(
487 origin: SubregionOrigin<'tcx>,
491 self.sub_regions(origin, a, b)
496 origin: SubregionOrigin<'tcx>,
497 kind: GenericKind<'tcx>,
499 bound: VerifyBound<'tcx>,
501 self.verify_generic_bound(origin, kind, a, bound)