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::OutlivesPredicate<'tcx, ty::GenericArg<'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            infer::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        std::mem::take(&mut self.inner.borrow_mut().region_obligations)
170    }
171
172    /// Process the region obligations that must be proven (during
173    /// `regionck`) for the given `body_id`, given information about
174    /// the region bounds in scope and so forth.
175    ///
176    /// See the `region_obligations` field of `InferCtxt` for some
177    /// comments about how this function fits into the overall expected
178    /// flow of the inferencer. The key point is that it is
179    /// invoked after all type-inference variables have been bound --
180    /// right before lexical region resolution.
181    #[instrument(level = "debug", skip(self, outlives_env, deeply_normalize_ty))]
182    pub fn process_registered_region_obligations(
183        &self,
184        outlives_env: &OutlivesEnvironment<'tcx>,
185        mut deeply_normalize_ty: impl FnMut(
186            PolyTypeOutlivesPredicate<'tcx>,
187            SubregionOrigin<'tcx>,
188        )
189            -> Result<PolyTypeOutlivesPredicate<'tcx>, NoSolution>,
190    ) -> Result<(), (PolyTypeOutlivesPredicate<'tcx>, SubregionOrigin<'tcx>)> {
191        assert!(!self.in_snapshot(), "cannot process registered region obligations in a snapshot");
192
193        // Must loop since the process of normalizing may itself register region obligations.
194        for iteration in 0.. {
195            let my_region_obligations = self.take_registered_region_obligations();
196            if my_region_obligations.is_empty() {
197                break;
198            }
199
200            if !self.tcx.recursion_limit().value_within_limit(iteration) {
201                bug!(
202                    "FIXME(-Znext-solver): Overflowed when processing region obligations: {my_region_obligations:#?}"
203                );
204            }
205
206            for TypeOutlivesConstraint { sup_type, sub_region, origin } in my_region_obligations {
207                let outlives = ty::Binder::dummy(ty::OutlivesPredicate(sup_type, sub_region));
208                let ty::OutlivesPredicate(sup_type, sub_region) =
209                    deeply_normalize_ty(outlives, origin.clone())
210                        .map_err(|NoSolution| (outlives, origin.clone()))?
211                        .no_bound_vars()
212                        .expect("started with no bound vars, should end with no bound vars");
213                // `TypeOutlives` is structural, so we should try to opportunistically resolve all
214                // region vids before processing regions, so we have a better chance to match clauses
215                // in our param-env.
216                let (sup_type, sub_region) =
217                    (sup_type, sub_region).fold_with(&mut OpportunisticRegionResolver::new(self));
218
219                debug!(?sup_type, ?sub_region, ?origin);
220
221                let outlives = &mut TypeOutlives::new(
222                    self,
223                    self.tcx,
224                    outlives_env.region_bound_pairs(),
225                    None,
226                    outlives_env.known_type_outlives(),
227                );
228                let category = origin.to_constraint_category();
229                outlives.type_must_outlive(origin, sup_type, sub_region, category);
230            }
231        }
232
233        Ok(())
234    }
235}
236
237/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
238/// obligation into a series of `'a: 'b` constraints and "verify"s, as
239/// described on the module comment. The final constraints are emitted
240/// via a "delegate" of type `D` -- this is usually the `infcx`, which
241/// accrues them into the `region_obligations` code, but for NLL we
242/// use something else.
243pub struct TypeOutlives<'cx, 'tcx, D>
244where
245    D: TypeOutlivesDelegate<'tcx>,
246{
247    // See the comments on `process_registered_region_obligations` for the meaning
248    // of these fields.
249    delegate: D,
250    tcx: TyCtxt<'tcx>,
251    verify_bound: VerifyBoundCx<'cx, 'tcx>,
252}
253
254pub trait TypeOutlivesDelegate<'tcx> {
255    fn push_sub_region_constraint(
256        &mut self,
257        origin: SubregionOrigin<'tcx>,
258        a: ty::Region<'tcx>,
259        b: ty::Region<'tcx>,
260        constraint_category: ConstraintCategory<'tcx>,
261    );
262
263    fn push_verify(
264        &mut self,
265        origin: SubregionOrigin<'tcx>,
266        kind: GenericKind<'tcx>,
267        a: ty::Region<'tcx>,
268        bound: VerifyBound<'tcx>,
269    );
270}
271
272impl<'cx, 'tcx, D> TypeOutlives<'cx, 'tcx, D>
273where
274    D: TypeOutlivesDelegate<'tcx>,
275{
276    pub fn new(
277        delegate: D,
278        tcx: TyCtxt<'tcx>,
279        region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
280        implicit_region_bound: Option<ty::Region<'tcx>>,
281        caller_bounds: &'cx [ty::PolyTypeOutlivesPredicate<'tcx>],
282    ) -> Self {
283        Self {
284            delegate,
285            tcx,
286            verify_bound: VerifyBoundCx::new(
287                tcx,
288                region_bound_pairs,
289                implicit_region_bound,
290                caller_bounds,
291            ),
292        }
293    }
294
295    /// Adds constraints to inference such that `T: 'a` holds (or
296    /// reports an error if it cannot).
297    ///
298    /// # Parameters
299    ///
300    /// - `origin`, the reason we need this constraint
301    /// - `ty`, the type `T`
302    /// - `region`, the region `'a`
303    #[instrument(level = "debug", skip(self))]
304    pub fn type_must_outlive(
305        &mut self,
306        origin: infer::SubregionOrigin<'tcx>,
307        ty: Ty<'tcx>,
308        region: ty::Region<'tcx>,
309        category: ConstraintCategory<'tcx>,
310    ) {
311        assert!(!ty.has_escaping_bound_vars());
312
313        let mut components = smallvec![];
314        push_outlives_components(self.tcx, ty, &mut components);
315        self.components_must_outlive(origin, &components, region, category);
316    }
317
318    fn components_must_outlive(
319        &mut self,
320        origin: infer::SubregionOrigin<'tcx>,
321        components: &[Component<TyCtxt<'tcx>>],
322        region: ty::Region<'tcx>,
323        category: ConstraintCategory<'tcx>,
324    ) {
325        for component in components.iter() {
326            let origin = origin.clone();
327            match component {
328                Component::Region(region1) => {
329                    self.delegate.push_sub_region_constraint(origin, region, *region1, category);
330                }
331                Component::Param(param_ty) => {
332                    self.param_ty_must_outlive(origin, region, *param_ty);
333                }
334                Component::Placeholder(placeholder_ty) => {
335                    self.placeholder_ty_must_outlive(origin, region, *placeholder_ty);
336                }
337                Component::Alias(alias_ty) => self.alias_ty_must_outlive(origin, region, *alias_ty),
338                Component::EscapingAlias(subcomponents) => {
339                    self.components_must_outlive(origin, subcomponents, region, category);
340                }
341                Component::UnresolvedInferenceVariable(v) => {
342                    // Ignore this, we presume it will yield an error later,
343                    // since if a type variable is not resolved by this point
344                    // it never will be.
345                    self.tcx.dcx().span_delayed_bug(
346                        origin.span(),
347                        format!("unresolved inference variable in outlives: {v:?}"),
348                    );
349                }
350            }
351        }
352    }
353
354    #[instrument(level = "debug", skip(self))]
355    fn param_ty_must_outlive(
356        &mut self,
357        origin: infer::SubregionOrigin<'tcx>,
358        region: ty::Region<'tcx>,
359        param_ty: ty::ParamTy,
360    ) {
361        let verify_bound = self.verify_bound.param_or_placeholder_bound(param_ty.to_ty(self.tcx));
362        self.delegate.push_verify(origin, GenericKind::Param(param_ty), region, verify_bound);
363    }
364
365    #[instrument(level = "debug", skip(self))]
366    fn placeholder_ty_must_outlive(
367        &mut self,
368        origin: infer::SubregionOrigin<'tcx>,
369        region: ty::Region<'tcx>,
370        placeholder_ty: ty::PlaceholderType,
371    ) {
372        let verify_bound = self
373            .verify_bound
374            .param_or_placeholder_bound(Ty::new_placeholder(self.tcx, placeholder_ty));
375        self.delegate.push_verify(
376            origin,
377            GenericKind::Placeholder(placeholder_ty),
378            region,
379            verify_bound,
380        );
381    }
382
383    #[instrument(level = "debug", skip(self))]
384    fn alias_ty_must_outlive(
385        &mut self,
386        origin: infer::SubregionOrigin<'tcx>,
387        region: ty::Region<'tcx>,
388        alias_ty: ty::AliasTy<'tcx>,
389    ) {
390        // An optimization for a common case with opaque types.
391        if alias_ty.args.is_empty() {
392            return;
393        }
394
395        if alias_ty.has_non_region_infer() {
396            self.tcx
397                .dcx()
398                .span_delayed_bug(origin.span(), "an alias has infers during region solving");
399            return;
400        }
401
402        // This case is thorny for inference. The fundamental problem is
403        // that there are many cases where we have choice, and inference
404        // doesn't like choice (the current region inference in
405        // particular). :) First off, we have to choose between using the
406        // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
407        // OutlivesProjectionComponent rules, any one of which is
408        // sufficient. If there are no inference variables involved, it's
409        // not hard to pick the right rule, but if there are, we're in a
410        // bit of a catch 22: if we picked which rule we were going to
411        // use, we could add constraints to the region inference graph
412        // that make it apply, but if we don't add those constraints, the
413        // rule might not apply (but another rule might). For now, we err
414        // on the side of adding too few edges into the graph.
415
416        // Compute the bounds we can derive from the trait definition.
417        // These are guaranteed to apply, no matter the inference
418        // results.
419        let trait_bounds: Vec<_> =
420            self.verify_bound.declared_bounds_from_definition(alias_ty).collect();
421
422        debug!(?trait_bounds);
423
424        // Compute the bounds we can derive from the environment. This
425        // is an "approximate" match -- in some cases, these bounds
426        // may not apply.
427        let approx_env_bounds = self.verify_bound.approx_declared_bounds_from_env(alias_ty);
428        debug!(?approx_env_bounds);
429
430        // If declared bounds list is empty, the only applicable rule is
431        // OutlivesProjectionComponent. If there are inference variables,
432        // then, we can break down the outlives into more primitive
433        // components without adding unnecessary edges.
434        //
435        // If there are *no* inference variables, however, we COULD do
436        // this, but we choose not to, because the error messages are less
437        // good. For example, a requirement like `T::Item: 'r` would be
438        // translated to a requirement that `T: 'r`; when this is reported
439        // to the user, it will thus say "T: 'r must hold so that T::Item:
440        // 'r holds". But that makes it sound like the only way to fix
441        // the problem is to add `T: 'r`, which isn't true. So, if there are no
442        // inference variables, we use a verify constraint instead of adding
443        // edges, which winds up enforcing the same condition.
444        let kind = alias_ty.kind(self.tcx);
445        if approx_env_bounds.is_empty()
446            && trait_bounds.is_empty()
447            && (alias_ty.has_infer_regions() || kind == ty::Opaque)
448        {
449            debug!("no declared bounds");
450            let opt_variances = self.tcx.opt_alias_variances(kind, alias_ty.def_id);
451            self.args_must_outlive(alias_ty.args, origin, region, opt_variances);
452            return;
453        }
454
455        // If we found a unique bound `'b` from the trait, and we
456        // found nothing else from the environment, then the best
457        // action is to require that `'b: 'r`, so do that.
458        //
459        // This is best no matter what rule we use:
460        //
461        // - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
462        // - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
463        // - OutlivesProjectionComponent: this would require `'b:'r`
464        //   in addition to other conditions
465        if !trait_bounds.is_empty()
466            && trait_bounds[1..]
467                .iter()
468                .map(|r| Some(*r))
469                .chain(
470                    // NB: The environment may contain `for<'a> T: 'a` style bounds.
471                    // In that case, we don't know if they are equal to the trait bound
472                    // or not (since we don't *know* whether the environment bound even applies),
473                    // so just map to `None` here if there are bound vars, ensuring that
474                    // the call to `all` will fail below.
475                    approx_env_bounds.iter().map(|b| b.map_bound(|b| b.1).no_bound_vars()),
476                )
477                .all(|b| b == Some(trait_bounds[0]))
478        {
479            let unique_bound = trait_bounds[0];
480            debug!(?unique_bound);
481            debug!("unique declared bound appears in trait ref");
482            let category = origin.to_constraint_category();
483            self.delegate.push_sub_region_constraint(origin, region, unique_bound, category);
484            return;
485        }
486
487        // Fallback to verifying after the fact that there exists a
488        // declared bound, or that all the components appearing in the
489        // projection outlive; in some cases, this may add insufficient
490        // edges into the inference graph, leading to inference failures
491        // even though a satisfactory solution exists.
492        let verify_bound = self.verify_bound.alias_bound(alias_ty);
493        debug!("alias_must_outlive: pushing {:?}", verify_bound);
494        self.delegate.push_verify(origin, GenericKind::Alias(alias_ty), region, verify_bound);
495    }
496
497    #[instrument(level = "debug", skip(self))]
498    fn args_must_outlive(
499        &mut self,
500        args: GenericArgsRef<'tcx>,
501        origin: infer::SubregionOrigin<'tcx>,
502        region: ty::Region<'tcx>,
503        opt_variances: Option<&[ty::Variance]>,
504    ) {
505        let constraint = origin.to_constraint_category();
506        for (index, arg) in args.iter().enumerate() {
507            match arg.kind() {
508                GenericArgKind::Lifetime(lt) => {
509                    let variance = if let Some(variances) = opt_variances {
510                        variances[index]
511                    } else {
512                        ty::Invariant
513                    };
514                    if variance == ty::Invariant {
515                        self.delegate.push_sub_region_constraint(
516                            origin.clone(),
517                            region,
518                            lt,
519                            constraint,
520                        );
521                    }
522                }
523                GenericArgKind::Type(ty) => {
524                    self.type_must_outlive(origin.clone(), ty, region, constraint);
525                }
526                GenericArgKind::Const(_) => {
527                    // Const parameters don't impose constraints.
528                }
529            }
530        }
531    }
532}
533
534impl<'cx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'tcx> {
535    fn push_sub_region_constraint(
536        &mut self,
537        origin: SubregionOrigin<'tcx>,
538        a: ty::Region<'tcx>,
539        b: ty::Region<'tcx>,
540        _constraint_category: ConstraintCategory<'tcx>,
541    ) {
542        self.sub_regions(origin, a, b)
543    }
544
545    fn push_verify(
546        &mut self,
547        origin: SubregionOrigin<'tcx>,
548        kind: GenericKind<'tcx>,
549        a: ty::Region<'tcx>,
550        bound: VerifyBound<'tcx>,
551    ) {
552        self.verify_generic_bound(origin, kind, a, bound)
553    }
554}