rustc_infer/infer/outlives/obligations.rs
1//! Code that handles "type-outlives" constraints like `T: 'a`. This
2//! is based on the `push_outlives_components` function defined in rustc_infer,
3//! but it adds a bit of heuristics on top, in particular to deal with
4//! associated types and projections.
5//!
6//! When we process a given `T: 'a` obligation, we may produce two
7//! kinds of constraints for the region inferencer:
8//!
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.
20//!
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.**
24//!
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.
32//!
33//! Consider:
34//!
35//! ```
36//! fn bar<T>(a: T, b: impl for<'a> Fn(&'a T)) {}
37//! fn foo<T>(x: T) {
38//! bar(x, |y| { /* ... */})
39//! // ^ closure arg
40//! }
41//! ```
42//!
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`).
47//!
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
52//! to `foo`:
53//!
54//! ```
55//! fn foo<U, F: for<'a> FnMut(&'a U)>(_f: F) {}
56//! ```
57//!
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`.
61
62use rustc_data_structures::undo_log::UndoLogs;
63use rustc_middle::bug;
64use rustc_middle::mir::ConstraintCategory;
65use rustc_middle::traits::query::NoSolution;
66use rustc_middle::ty::outlives::{Component, push_outlives_components};
67use rustc_middle::ty::{
68 self, GenericArgKind, GenericArgsRef, PolyTypeOutlivesPredicate, Region, Ty, TyCtxt,
69 TypeFoldable as _, TypeVisitableExt,
70};
71use smallvec::smallvec;
72use tracing::{debug, instrument};
73
74use super::env::OutlivesEnvironment;
75use crate::infer::outlives::env::RegionBoundPairs;
76use crate::infer::outlives::verify::VerifyBoundCx;
77use crate::infer::resolve::OpportunisticRegionResolver;
78use crate::infer::snapshot::undo_log::UndoLog;
79use crate::infer::{
80 self, GenericKind, InferCtxt, SubregionOrigin, TypeOutlivesConstraint, VerifyBound,
81};
82use crate::traits::{ObligationCause, ObligationCauseCode};
83
84impl<'tcx> InferCtxt<'tcx> {
85 pub fn register_outlives_constraint(
86 &self,
87 ty::OutlivesPredicate(arg, r2): ty::ArgOutlivesPredicate<'tcx>,
88 cause: &ObligationCause<'tcx>,
89 ) {
90 match arg.kind() {
91 ty::GenericArgKind::Lifetime(r1) => {
92 self.register_region_outlives_constraint(ty::OutlivesPredicate(r1, r2), cause);
93 }
94 ty::GenericArgKind::Type(ty1) => {
95 self.register_type_outlives_constraint(ty1, r2, cause);
96 }
97 ty::GenericArgKind::Const(_) => unreachable!(),
98 }
99 }
100
101 pub fn register_region_outlives_constraint(
102 &self,
103 ty::OutlivesPredicate(r_a, r_b): ty::RegionOutlivesPredicate<'tcx>,
104 cause: &ObligationCause<'tcx>,
105 ) {
106 let origin = SubregionOrigin::from_obligation_cause(cause, || {
107 SubregionOrigin::RelateRegionParamBound(cause.span, None)
108 });
109 // `'a: 'b` ==> `'b <= 'a`
110 self.sub_regions(origin, r_b, r_a);
111 }
112
113 /// Registers that the given region obligation must be resolved
114 /// from within the scope of `body_id`. These regions are enqueued
115 /// and later processed by regionck, when full type information is
116 /// available (see `region_obligations` field for more
117 /// information).
118 #[instrument(level = "debug", skip(self))]
119 pub fn register_type_outlives_constraint_inner(
120 &self,
121 obligation: TypeOutlivesConstraint<'tcx>,
122 ) {
123 let mut inner = self.inner.borrow_mut();
124 inner.undo_log.push(UndoLog::PushTypeOutlivesConstraint);
125 inner.region_obligations.push(obligation);
126 }
127
128 pub fn register_type_outlives_constraint(
129 &self,
130 sup_type: Ty<'tcx>,
131 sub_region: Region<'tcx>,
132 cause: &ObligationCause<'tcx>,
133 ) {
134 // `is_global` means the type has no params, infer, placeholder, or non-`'static`
135 // free regions. If the type has none of these things, then we can skip registering
136 // this outlives obligation since it has no components which affect lifetime
137 // checking in an interesting way.
138 if sup_type.is_global() {
139 return;
140 }
141
142 debug!(?sup_type, ?sub_region, ?cause);
143 let origin = SubregionOrigin::from_obligation_cause(cause, || {
144 SubregionOrigin::RelateParamBound(
145 cause.span,
146 sup_type,
147 match cause.code().peel_derives() {
148 ObligationCauseCode::WhereClause(_, span)
149 | ObligationCauseCode::WhereClauseInExpr(_, span, ..)
150 | ObligationCauseCode::OpaqueTypeBound(span, _)
151 if !span.is_dummy() =>
152 {
153 Some(*span)
154 }
155 _ => None,
156 },
157 )
158 });
159
160 self.register_type_outlives_constraint_inner(TypeOutlivesConstraint {
161 sup_type,
162 sub_region,
163 origin,
164 });
165 }
166
167 /// Trait queries just want to pass back type obligations "as is"
168 pub fn take_registered_region_obligations(&self) -> Vec<TypeOutlivesConstraint<'tcx>> {
169 assert!(!self.in_snapshot(), "cannot take registered region obligations in a snapshot");
170 std::mem::take(&mut self.inner.borrow_mut().region_obligations)
171 }
172
173 pub fn clone_registered_region_obligations(&self) -> Vec<TypeOutlivesConstraint<'tcx>> {
174 self.inner.borrow().region_obligations.clone()
175 }
176
177 pub fn register_region_assumption(&self, assumption: ty::ArgOutlivesPredicate<'tcx>) {
178 let mut inner = self.inner.borrow_mut();
179 inner.undo_log.push(UndoLog::PushRegionAssumption);
180 inner.region_assumptions.push(assumption);
181 }
182
183 pub fn take_registered_region_assumptions(&self) -> Vec<ty::ArgOutlivesPredicate<'tcx>> {
184 assert!(!self.in_snapshot(), "cannot take registered region assumptions in a snapshot");
185 std::mem::take(&mut self.inner.borrow_mut().region_assumptions)
186 }
187
188 /// Process the region obligations that must be proven (during
189 /// `regionck`) for the given `body_id`, given information about
190 /// the region bounds in scope and so forth.
191 ///
192 /// See the `region_obligations` field of `InferCtxt` for some
193 /// comments about how this function fits into the overall expected
194 /// flow of the inferencer. The key point is that it is
195 /// invoked after all type-inference variables have been bound --
196 /// right before lexical region resolution.
197 #[instrument(level = "debug", skip(self, outlives_env, deeply_normalize_ty))]
198 pub fn process_registered_region_obligations(
199 &self,
200 outlives_env: &OutlivesEnvironment<'tcx>,
201 mut deeply_normalize_ty: impl FnMut(
202 PolyTypeOutlivesPredicate<'tcx>,
203 SubregionOrigin<'tcx>,
204 )
205 -> Result<PolyTypeOutlivesPredicate<'tcx>, NoSolution>,
206 ) -> Result<(), (PolyTypeOutlivesPredicate<'tcx>, SubregionOrigin<'tcx>)> {
207 assert!(!self.in_snapshot(), "cannot process registered region obligations in a snapshot");
208
209 // Must loop since the process of normalizing may itself register region obligations.
210 for iteration in 0.. {
211 let my_region_obligations = self.take_registered_region_obligations();
212 if my_region_obligations.is_empty() {
213 break;
214 }
215
216 if !self.tcx.recursion_limit().value_within_limit(iteration) {
217 // This may actually be reachable. If so, we should convert
218 // this to a proper error/consider whether we should detect
219 // this somewhere else.
220 bug!(
221 "unexpected overflowed when processing region obligations: {my_region_obligations:#?}"
222 );
223 }
224
225 for TypeOutlivesConstraint { sup_type, sub_region, origin } in my_region_obligations {
226 let outlives = ty::Binder::dummy(ty::OutlivesPredicate(sup_type, sub_region));
227 let ty::OutlivesPredicate(sup_type, sub_region) =
228 deeply_normalize_ty(outlives, origin.clone())
229 .map_err(|NoSolution| (outlives, origin.clone()))?
230 .no_bound_vars()
231 .expect("started with no bound vars, should end with no bound vars");
232 // `TypeOutlives` is structural, so we should try to opportunistically resolve all
233 // region vids before processing regions, so we have a better chance to match clauses
234 // in our param-env.
235 let (sup_type, sub_region) =
236 (sup_type, sub_region).fold_with(&mut OpportunisticRegionResolver::new(self));
237
238 if self.tcx.sess.opts.unstable_opts.higher_ranked_assumptions
239 && outlives_env
240 .higher_ranked_assumptions()
241 .contains(&ty::OutlivesPredicate(sup_type.into(), sub_region))
242 {
243 continue;
244 }
245
246 debug!(?sup_type, ?sub_region, ?origin);
247
248 let outlives = &mut TypeOutlives::new(
249 self,
250 self.tcx,
251 outlives_env.region_bound_pairs(),
252 None,
253 outlives_env.known_type_outlives(),
254 );
255 let category = origin.to_constraint_category();
256 outlives.type_must_outlive(origin, sup_type, sub_region, category);
257 }
258 }
259
260 Ok(())
261 }
262}
263
264/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
265/// obligation into a series of `'a: 'b` constraints and "verify"s, as
266/// described on the module comment. The final constraints are emitted
267/// via a "delegate" of type `D` -- this is usually the `infcx`, which
268/// accrues them into the `region_obligations` code, but for NLL we
269/// use something else.
270pub struct TypeOutlives<'cx, 'tcx, D>
271where
272 D: TypeOutlivesDelegate<'tcx>,
273{
274 // See the comments on `process_registered_region_obligations` for the meaning
275 // of these fields.
276 delegate: D,
277 tcx: TyCtxt<'tcx>,
278 verify_bound: VerifyBoundCx<'cx, 'tcx>,
279}
280
281pub trait TypeOutlivesDelegate<'tcx> {
282 fn push_sub_region_constraint(
283 &mut self,
284 origin: SubregionOrigin<'tcx>,
285 a: ty::Region<'tcx>,
286 b: ty::Region<'tcx>,
287 constraint_category: ConstraintCategory<'tcx>,
288 );
289
290 fn push_verify(
291 &mut self,
292 origin: SubregionOrigin<'tcx>,
293 kind: GenericKind<'tcx>,
294 a: ty::Region<'tcx>,
295 bound: VerifyBound<'tcx>,
296 );
297}
298
299impl<'cx, 'tcx, D> TypeOutlives<'cx, 'tcx, D>
300where
301 D: TypeOutlivesDelegate<'tcx>,
302{
303 pub fn new(
304 delegate: D,
305 tcx: TyCtxt<'tcx>,
306 region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
307 implicit_region_bound: Option<ty::Region<'tcx>>,
308 caller_bounds: &'cx [ty::PolyTypeOutlivesPredicate<'tcx>],
309 ) -> Self {
310 Self {
311 delegate,
312 tcx,
313 verify_bound: VerifyBoundCx::new(
314 tcx,
315 region_bound_pairs,
316 implicit_region_bound,
317 caller_bounds,
318 ),
319 }
320 }
321
322 /// Adds constraints to inference such that `T: 'a` holds (or
323 /// reports an error if it cannot).
324 ///
325 /// # Parameters
326 ///
327 /// - `origin`, the reason we need this constraint
328 /// - `ty`, the type `T`
329 /// - `region`, the region `'a`
330 #[instrument(level = "debug", skip(self))]
331 pub fn type_must_outlive(
332 &mut self,
333 origin: infer::SubregionOrigin<'tcx>,
334 ty: Ty<'tcx>,
335 region: ty::Region<'tcx>,
336 category: ConstraintCategory<'tcx>,
337 ) {
338 assert!(!ty.has_escaping_bound_vars());
339
340 let mut components = smallvec![];
341 push_outlives_components(self.tcx, ty, &mut components);
342 self.components_must_outlive(origin, &components, region, category);
343 }
344
345 fn components_must_outlive(
346 &mut self,
347 origin: infer::SubregionOrigin<'tcx>,
348 components: &[Component<TyCtxt<'tcx>>],
349 region: ty::Region<'tcx>,
350 category: ConstraintCategory<'tcx>,
351 ) {
352 for component in components.iter() {
353 let origin = origin.clone();
354 match component {
355 Component::Region(region1) => {
356 self.delegate.push_sub_region_constraint(origin, region, *region1, category);
357 }
358 Component::Param(param_ty) => {
359 self.param_ty_must_outlive(origin, region, *param_ty);
360 }
361 Component::Placeholder(placeholder_ty) => {
362 self.placeholder_ty_must_outlive(origin, region, *placeholder_ty);
363 }
364 Component::Alias(alias_ty) => self.alias_ty_must_outlive(origin, region, *alias_ty),
365 Component::EscapingAlias(subcomponents) => {
366 self.components_must_outlive(origin, subcomponents, region, category);
367 }
368 Component::UnresolvedInferenceVariable(v) => {
369 // Ignore this, we presume it will yield an error later,
370 // since if a type variable is not resolved by this point
371 // it never will be.
372 self.tcx.dcx().span_delayed_bug(
373 origin.span(),
374 format!("unresolved inference variable in outlives: {v:?}"),
375 );
376 }
377 }
378 }
379 }
380
381 #[instrument(level = "debug", skip(self))]
382 fn param_ty_must_outlive(
383 &mut self,
384 origin: infer::SubregionOrigin<'tcx>,
385 region: ty::Region<'tcx>,
386 param_ty: ty::ParamTy,
387 ) {
388 let verify_bound = self.verify_bound.param_or_placeholder_bound(param_ty.to_ty(self.tcx));
389 self.delegate.push_verify(origin, GenericKind::Param(param_ty), region, verify_bound);
390 }
391
392 #[instrument(level = "debug", skip(self))]
393 fn placeholder_ty_must_outlive(
394 &mut self,
395 origin: infer::SubregionOrigin<'tcx>,
396 region: ty::Region<'tcx>,
397 placeholder_ty: ty::PlaceholderType,
398 ) {
399 let verify_bound = self
400 .verify_bound
401 .param_or_placeholder_bound(Ty::new_placeholder(self.tcx, placeholder_ty));
402 self.delegate.push_verify(
403 origin,
404 GenericKind::Placeholder(placeholder_ty),
405 region,
406 verify_bound,
407 );
408 }
409
410 #[instrument(level = "debug", skip(self))]
411 fn alias_ty_must_outlive(
412 &mut self,
413 origin: infer::SubregionOrigin<'tcx>,
414 region: ty::Region<'tcx>,
415 alias_ty: ty::AliasTy<'tcx>,
416 ) {
417 // An optimization for a common case with opaque types.
418 if alias_ty.args.is_empty() {
419 return;
420 }
421
422 if alias_ty.has_non_region_infer() {
423 self.tcx
424 .dcx()
425 .span_delayed_bug(origin.span(), "an alias has infers during region solving");
426 return;
427 }
428
429 // This case is thorny for inference. The fundamental problem is
430 // that there are many cases where we have choice, and inference
431 // doesn't like choice (the current region inference in
432 // particular). :) First off, we have to choose between using the
433 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
434 // OutlivesProjectionComponent rules, any one of which is
435 // sufficient. If there are no inference variables involved, it's
436 // not hard to pick the right rule, but if there are, we're in a
437 // bit of a catch 22: if we picked which rule we were going to
438 // use, we could add constraints to the region inference graph
439 // that make it apply, but if we don't add those constraints, the
440 // rule might not apply (but another rule might). For now, we err
441 // on the side of adding too few edges into the graph.
442
443 // Compute the bounds we can derive from the trait definition.
444 // These are guaranteed to apply, no matter the inference
445 // results.
446 let trait_bounds: Vec<_> =
447 self.verify_bound.declared_bounds_from_definition(alias_ty).collect();
448
449 debug!(?trait_bounds);
450
451 // Compute the bounds we can derive from the environment. This
452 // is an "approximate" match -- in some cases, these bounds
453 // may not apply.
454 let approx_env_bounds = self.verify_bound.approx_declared_bounds_from_env(alias_ty);
455 debug!(?approx_env_bounds);
456
457 // If declared bounds list is empty, the only applicable rule is
458 // OutlivesProjectionComponent. If there are inference variables,
459 // then, we can break down the outlives into more primitive
460 // components without adding unnecessary edges.
461 //
462 // If there are *no* inference variables, however, we COULD do
463 // this, but we choose not to, because the error messages are less
464 // good. For example, a requirement like `T::Item: 'r` would be
465 // translated to a requirement that `T: 'r`; when this is reported
466 // to the user, it will thus say "T: 'r must hold so that T::Item:
467 // 'r holds". But that makes it sound like the only way to fix
468 // the problem is to add `T: 'r`, which isn't true. So, if there are no
469 // inference variables, we use a verify constraint instead of adding
470 // edges, which winds up enforcing the same condition.
471 let kind = alias_ty.kind(self.tcx);
472 if approx_env_bounds.is_empty()
473 && trait_bounds.is_empty()
474 && (alias_ty.has_infer_regions() || kind == ty::Opaque)
475 {
476 debug!("no declared bounds");
477 let opt_variances = self.tcx.opt_alias_variances(kind, alias_ty.def_id);
478 self.args_must_outlive(alias_ty.args, origin, region, opt_variances);
479 return;
480 }
481
482 // If we found a unique bound `'b` from the trait, and we
483 // found nothing else from the environment, then the best
484 // action is to require that `'b: 'r`, so do that.
485 //
486 // This is best no matter what rule we use:
487 //
488 // - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
489 // - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
490 // - OutlivesProjectionComponent: this would require `'b:'r`
491 // in addition to other conditions
492 if !trait_bounds.is_empty()
493 && trait_bounds[1..]
494 .iter()
495 .map(|r| Some(*r))
496 .chain(
497 // NB: The environment may contain `for<'a> T: 'a` style bounds.
498 // In that case, we don't know if they are equal to the trait bound
499 // or not (since we don't *know* whether the environment bound even applies),
500 // so just map to `None` here if there are bound vars, ensuring that
501 // the call to `all` will fail below.
502 approx_env_bounds.iter().map(|b| b.map_bound(|b| b.1).no_bound_vars()),
503 )
504 .all(|b| b == Some(trait_bounds[0]))
505 {
506 let unique_bound = trait_bounds[0];
507 debug!(?unique_bound);
508 debug!("unique declared bound appears in trait ref");
509 let category = origin.to_constraint_category();
510 self.delegate.push_sub_region_constraint(origin, region, unique_bound, category);
511 return;
512 }
513
514 // Fallback to verifying after the fact that there exists a
515 // declared bound, or that all the components appearing in the
516 // projection outlive; in some cases, this may add insufficient
517 // edges into the inference graph, leading to inference failures
518 // even though a satisfactory solution exists.
519 let verify_bound = self.verify_bound.alias_bound(alias_ty);
520 debug!("alias_must_outlive: pushing {:?}", verify_bound);
521 self.delegate.push_verify(origin, GenericKind::Alias(alias_ty), region, verify_bound);
522 }
523
524 #[instrument(level = "debug", skip(self))]
525 fn args_must_outlive(
526 &mut self,
527 args: GenericArgsRef<'tcx>,
528 origin: infer::SubregionOrigin<'tcx>,
529 region: ty::Region<'tcx>,
530 opt_variances: Option<&[ty::Variance]>,
531 ) {
532 let constraint = origin.to_constraint_category();
533 for (index, arg) in args.iter().enumerate() {
534 match arg.kind() {
535 GenericArgKind::Lifetime(lt) => {
536 let variance = if let Some(variances) = opt_variances {
537 variances[index]
538 } else {
539 ty::Invariant
540 };
541 if variance == ty::Invariant {
542 self.delegate.push_sub_region_constraint(
543 origin.clone(),
544 region,
545 lt,
546 constraint,
547 );
548 }
549 }
550 GenericArgKind::Type(ty) => {
551 self.type_must_outlive(origin.clone(), ty, region, constraint);
552 }
553 GenericArgKind::Const(_) => {
554 // Const parameters don't impose constraints.
555 }
556 }
557 }
558 }
559}
560
561impl<'cx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'tcx> {
562 fn push_sub_region_constraint(
563 &mut self,
564 origin: SubregionOrigin<'tcx>,
565 a: ty::Region<'tcx>,
566 b: ty::Region<'tcx>,
567 _constraint_category: ConstraintCategory<'tcx>,
568 ) {
569 self.sub_regions(origin, a, b)
570 }
571
572 fn push_verify(
573 &mut self,
574 origin: SubregionOrigin<'tcx>,
575 kind: GenericKind<'tcx>,
576 a: ty::Region<'tcx>,
577 bound: VerifyBound<'tcx>,
578 ) {
579 self.verify_generic_bound(origin, kind, a, bound)
580 }
581}