rustc_borrowck/region_infer/
mod.rs

1use std::collections::VecDeque;
2use std::rc::Rc;
3
4use rustc_data_structures::frozen::Frozen;
5use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
6use rustc_data_structures::graph::scc::Sccs;
7use rustc_errors::Diag;
8use rustc_hir::def_id::CRATE_DEF_ID;
9use rustc_index::IndexVec;
10use rustc_infer::infer::outlives::test_type_match;
11use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound, VerifyIfEq};
12use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
13use rustc_middle::bug;
14use rustc_middle::mir::{
15    AnnotationSource, BasicBlock, Body, ConstraintCategory, Local, Location, ReturnConstraint,
16    TerminatorKind,
17};
18use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
19use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, fold_regions};
20use rustc_mir_dataflow::points::DenseLocationMap;
21use rustc_span::hygiene::DesugaringKind;
22use rustc_span::{DUMMY_SP, Span};
23use tracing::{Level, debug, enabled, instrument, trace};
24
25use crate::constraints::graph::NormalConstraintGraph;
26use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet};
27use crate::dataflow::BorrowIndex;
28use crate::diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo};
29use crate::handle_placeholders::{LoweredConstraints, RegionTracker};
30use crate::polonius::LiveLoans;
31use crate::polonius::legacy::PoloniusOutput;
32use crate::region_infer::values::{LivenessValues, RegionElement, RegionValues, ToElementIndex};
33use crate::type_check::Locations;
34use crate::type_check::free_region_relations::UniversalRegionRelations;
35use crate::universal_regions::UniversalRegions;
36use crate::{
37    BorrowckInferCtxt, ClosureOutlivesRequirement, ClosureOutlivesSubject,
38    ClosureOutlivesSubjectTy, ClosureRegionRequirements,
39};
40
41mod dump_mir;
42mod graphviz;
43pub(crate) mod opaque_types;
44mod reverse_sccs;
45
46pub(crate) mod values;
47
48/// The representative region variable for an SCC, tagged by its origin.
49/// We prefer placeholders over existentially quantified variables, otherwise
50/// it's the one with the smallest Region Variable ID. In other words,
51/// the order of this enumeration really matters!
52#[derive(Copy, Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
53pub(crate) enum Representative {
54    FreeRegion(RegionVid),
55    Placeholder(RegionVid),
56    Existential(RegionVid),
57}
58
59impl Representative {
60    pub(crate) fn rvid(self) -> RegionVid {
61        match self {
62            Representative::FreeRegion(region_vid)
63            | Representative::Placeholder(region_vid)
64            | Representative::Existential(region_vid) => region_vid,
65        }
66    }
67
68    pub(crate) fn new(r: RegionVid, definition: &RegionDefinition<'_>) -> Self {
69        match definition.origin {
70            NllRegionVariableOrigin::FreeRegion => Representative::FreeRegion(r),
71            NllRegionVariableOrigin::Placeholder(_) => Representative::Placeholder(r),
72            NllRegionVariableOrigin::Existential { .. } => Representative::Existential(r),
73        }
74    }
75}
76
77pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex>;
78
79pub struct RegionInferenceContext<'tcx> {
80    /// Contains the definition for every region variable. Region
81    /// variables are identified by their index (`RegionVid`). The
82    /// definition contains information about where the region came
83    /// from as well as its final inferred value.
84    pub(crate) definitions: Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>,
85
86    /// The liveness constraints added to each region. For most
87    /// regions, these start out empty and steadily grow, though for
88    /// each universally quantified region R they start out containing
89    /// the entire CFG and `end(R)`.
90    liveness_constraints: LivenessValues,
91
92    /// The outlives constraints computed by the type-check.
93    constraints: Frozen<OutlivesConstraintSet<'tcx>>,
94
95    /// The constraint-set, but in graph form, making it easy to traverse
96    /// the constraints adjacent to a particular region. Used to construct
97    /// the SCC (see `constraint_sccs`) and for error reporting.
98    constraint_graph: Frozen<NormalConstraintGraph>,
99
100    /// The SCC computed from `constraints` and the constraint
101    /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
102    /// compute the values of each region.
103    constraint_sccs: ConstraintSccs,
104
105    scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,
106
107    /// Map universe indexes to information on why we created it.
108    universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
109
110    /// The final inferred values of the region variables; we compute
111    /// one value per SCC. To get the value for any given *region*,
112    /// you first find which scc it is a part of.
113    scc_values: RegionValues<ConstraintSccIndex>,
114
115    /// Type constraints that we check after solving.
116    type_tests: Vec<TypeTest<'tcx>>,
117
118    /// Information about how the universally quantified regions in
119    /// scope on this function relate to one another.
120    universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
121}
122
123#[derive(Debug)]
124pub(crate) struct RegionDefinition<'tcx> {
125    /// What kind of variable is this -- a free region? existential
126    /// variable? etc. (See the `NllRegionVariableOrigin` for more
127    /// info.)
128    pub(crate) origin: NllRegionVariableOrigin,
129
130    /// Which universe is this region variable defined in? This is
131    /// most often `ty::UniverseIndex::ROOT`, but when we encounter
132    /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
133    /// the variable for `'a` in a fresh universe that extends ROOT.
134    pub(crate) universe: ty::UniverseIndex,
135
136    /// If this is 'static or an early-bound region, then this is
137    /// `Some(X)` where `X` is the name of the region.
138    pub(crate) external_name: Option<ty::Region<'tcx>>,
139}
140
141/// N.B., the variants in `Cause` are intentionally ordered. Lower
142/// values are preferred when it comes to error messages. Do not
143/// reorder willy nilly.
144#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
145pub(crate) enum Cause {
146    /// point inserted because Local was live at the given Location
147    LiveVar(Local, Location),
148
149    /// point inserted because Local was dropped at the given Location
150    DropVar(Local, Location),
151}
152
153/// A "type test" corresponds to an outlives constraint between a type
154/// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
155/// translated from the `Verify` region constraints in the ordinary
156/// inference context.
157///
158/// These sorts of constraints are handled differently than ordinary
159/// constraints, at least at present. During type checking, the
160/// `InferCtxt::process_registered_region_obligations` method will
161/// attempt to convert a type test like `T: 'x` into an ordinary
162/// outlives constraint when possible (for example, `&'a T: 'b` will
163/// be converted into `'a: 'b` and registered as a `Constraint`).
164///
165/// In some cases, however, there are outlives relationships that are
166/// not converted into a region constraint, but rather into one of
167/// these "type tests". The distinction is that a type test does not
168/// influence the inference result, but instead just examines the
169/// values that we ultimately inferred for each region variable and
170/// checks that they meet certain extra criteria. If not, an error
171/// can be issued.
172///
173/// One reason for this is that these type tests typically boil down
174/// to a check like `'a: 'x` where `'a` is a universally quantified
175/// region -- and therefore not one whose value is really meant to be
176/// *inferred*, precisely (this is not always the case: one can have a
177/// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
178/// inference variable). Another reason is that these type tests can
179/// involve *disjunction* -- that is, they can be satisfied in more
180/// than one way.
181///
182/// For more information about this translation, see
183/// `InferCtxt::process_registered_region_obligations` and
184/// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
185#[derive(Clone, Debug)]
186pub(crate) struct TypeTest<'tcx> {
187    /// The type `T` that must outlive the region.
188    pub generic_kind: GenericKind<'tcx>,
189
190    /// The region `'x` that the type must outlive.
191    pub lower_bound: RegionVid,
192
193    /// The span to blame.
194    pub span: Span,
195
196    /// A test which, if met by the region `'x`, proves that this type
197    /// constraint is satisfied.
198    pub verify_bound: VerifyBound<'tcx>,
199}
200
201/// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
202/// environment). If we can't, it is an error.
203#[derive(Clone, Copy, Debug, Eq, PartialEq)]
204enum RegionRelationCheckResult {
205    Ok,
206    Propagated,
207    Error,
208}
209
210#[derive(Clone, PartialEq, Eq, Debug)]
211enum Trace<'a, 'tcx> {
212    StartRegion,
213    FromGraph(&'a OutlivesConstraint<'tcx>),
214    FromStatic(RegionVid),
215    NotVisited,
216}
217
218#[instrument(skip(infcx, sccs), level = "debug")]
219fn sccs_info<'tcx>(infcx: &BorrowckInferCtxt<'tcx>, sccs: &ConstraintSccs) {
220    use crate::renumber::RegionCtxt;
221
222    let var_to_origin = infcx.reg_var_to_origin.borrow();
223
224    let mut var_to_origin_sorted = var_to_origin.clone().into_iter().collect::<Vec<_>>();
225    var_to_origin_sorted.sort_by_key(|vto| vto.0);
226
227    if enabled!(Level::DEBUG) {
228        let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string();
229        for (reg_var, origin) in var_to_origin_sorted.into_iter() {
230            reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n"));
231        }
232        debug!("{}", reg_vars_to_origins_str);
233    }
234
235    let num_components = sccs.num_sccs();
236    let mut components = vec![FxIndexSet::default(); num_components];
237
238    for (reg_var, scc_idx) in sccs.scc_indices().iter_enumerated() {
239        let origin = var_to_origin.get(&reg_var).unwrap_or(&RegionCtxt::Unknown);
240        components[scc_idx.as_usize()].insert((reg_var, *origin));
241    }
242
243    if enabled!(Level::DEBUG) {
244        let mut components_str = "strongly connected components:".to_string();
245        for (scc_idx, reg_vars_origins) in components.iter().enumerate() {
246            let regions_info = reg_vars_origins.clone().into_iter().collect::<Vec<_>>();
247            components_str.push_str(&format!(
248                "{:?}: {:?},\n)",
249                ConstraintSccIndex::from_usize(scc_idx),
250                regions_info,
251            ))
252        }
253        debug!("{}", components_str);
254    }
255
256    // calculate the best representative for each component
257    let components_representatives = components
258        .into_iter()
259        .enumerate()
260        .map(|(scc_idx, region_ctxts)| {
261            let repr = region_ctxts
262                .into_iter()
263                .map(|reg_var_origin| reg_var_origin.1)
264                .max_by(|x, y| x.preference_value().cmp(&y.preference_value()))
265                .unwrap();
266
267            (ConstraintSccIndex::from_usize(scc_idx), repr)
268        })
269        .collect::<FxIndexMap<_, _>>();
270
271    let mut scc_node_to_edges = FxIndexMap::default();
272    for (scc_idx, repr) in components_representatives.iter() {
273        let edge_representatives = sccs
274            .successors(*scc_idx)
275            .iter()
276            .map(|scc_idx| components_representatives[scc_idx])
277            .collect::<Vec<_>>();
278        scc_node_to_edges.insert((scc_idx, repr), edge_representatives);
279    }
280
281    debug!("SCC edges {:#?}", scc_node_to_edges);
282}
283
284impl<'tcx> RegionInferenceContext<'tcx> {
285    /// Creates a new region inference context with a total of
286    /// `num_region_variables` valid inference variables; the first N
287    /// of those will be constant regions representing the free
288    /// regions defined in `universal_regions`.
289    ///
290    /// The `outlives_constraints` and `type_tests` are an initial set
291    /// of constraints produced by the MIR type check.
292    pub(crate) fn new(
293        infcx: &BorrowckInferCtxt<'tcx>,
294        lowered_constraints: LoweredConstraints<'tcx>,
295        universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
296        location_map: Rc<DenseLocationMap>,
297    ) -> Self {
298        let universal_regions = &universal_region_relations.universal_regions;
299
300        let LoweredConstraints {
301            constraint_sccs,
302            definitions,
303            outlives_constraints,
304            scc_annotations,
305            type_tests,
306            liveness_constraints,
307            universe_causes,
308            placeholder_indices,
309        } = lowered_constraints;
310
311        debug!("universal_regions: {:#?}", universal_region_relations.universal_regions);
312        debug!("outlives constraints: {:#?}", outlives_constraints);
313        debug!("placeholder_indices: {:#?}", placeholder_indices);
314        debug!("type tests: {:#?}", type_tests);
315
316        let constraint_graph = Frozen::freeze(outlives_constraints.graph(definitions.len()));
317
318        if cfg!(debug_assertions) {
319            sccs_info(infcx, &constraint_sccs);
320        }
321
322        let mut scc_values =
323            RegionValues::new(location_map, universal_regions.len(), placeholder_indices);
324
325        for region in liveness_constraints.regions() {
326            let scc = constraint_sccs.scc(region);
327            scc_values.merge_liveness(scc, region, &liveness_constraints);
328        }
329
330        let mut result = Self {
331            definitions,
332            liveness_constraints,
333            constraints: outlives_constraints,
334            constraint_graph,
335            constraint_sccs,
336            scc_annotations,
337            universe_causes,
338            scc_values,
339            type_tests,
340            universal_region_relations,
341        };
342
343        result.init_free_and_bound_regions();
344
345        result
346    }
347
348    /// Initializes the region variables for each universally
349    /// quantified region (lifetime parameter). The first N variables
350    /// always correspond to the regions appearing in the function
351    /// signature (both named and anonymous) and where-clauses. This
352    /// function iterates over those regions and initializes them with
353    /// minimum values.
354    ///
355    /// For example:
356    /// ```ignore (illustrative)
357    /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
358    /// ```
359    /// would initialize two variables like so:
360    /// ```ignore (illustrative)
361    /// R0 = { CFG, R0 } // 'a
362    /// R1 = { CFG, R0, R1 } // 'b
363    /// ```
364    /// Here, R0 represents `'a`, and it contains (a) the entire CFG
365    /// and (b) any universally quantified regions that it outlives,
366    /// which in this case is just itself. R1 (`'b`) in contrast also
367    /// outlives `'a` and hence contains R0 and R1.
368    ///
369    /// This bit of logic also handles invalid universe relations
370    /// for higher-kinded types.
371    ///
372    /// We Walk each SCC `A` and `B` such that `A: B`
373    /// and ensure that universe(A) can see universe(B).
374    ///
375    /// This serves to enforce the 'empty/placeholder' hierarchy
376    /// (described in more detail on `RegionKind`):
377    ///
378    /// ```ignore (illustrative)
379    /// static -----+
380    ///   |         |
381    /// empty(U0) placeholder(U1)
382    ///   |      /
383    /// empty(U1)
384    /// ```
385    ///
386    /// In particular, imagine we have variables R0 in U0 and R1
387    /// created in U1, and constraints like this;
388    ///
389    /// ```ignore (illustrative)
390    /// R1: !1 // R1 outlives the placeholder in U1
391    /// R1: R0 // R1 outlives R0
392    /// ```
393    ///
394    /// Here, we wish for R1 to be `'static`, because it
395    /// cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
396    ///
397    /// Thanks to this loop, what happens is that the `R1: R0`
398    /// constraint has lowered the universe of `R1` to `U0`, which in turn
399    /// means that the `R1: !1` constraint here will cause
400    /// `R1` to become `'static`.
401    fn init_free_and_bound_regions(&mut self) {
402        for variable in self.definitions.indices() {
403            let scc = self.constraint_sccs.scc(variable);
404
405            match self.definitions[variable].origin {
406                NllRegionVariableOrigin::FreeRegion => {
407                    // For each free, universally quantified region X:
408
409                    // Add all nodes in the CFG to liveness constraints
410                    self.liveness_constraints.add_all_points(variable);
411                    self.scc_values.add_all_points(scc);
412
413                    // Add `end(X)` into the set for X.
414                    self.scc_values.add_element(scc, variable);
415                }
416
417                NllRegionVariableOrigin::Placeholder(placeholder) => {
418                    self.scc_values.add_element(scc, placeholder);
419                }
420
421                NllRegionVariableOrigin::Existential { .. } => {
422                    // For existential, regions, nothing to do.
423                }
424            }
425        }
426    }
427
428    /// Returns an iterator over all the region indices.
429    pub(crate) fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
430        self.definitions.indices()
431    }
432
433    /// Given a universal region in scope on the MIR, returns the
434    /// corresponding index.
435    ///
436    /// Panics if `r` is not a registered universal region, most notably
437    /// if it is a placeholder. Handling placeholders requires access to the
438    /// `MirTypeckRegionConstraints`.
439    pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
440        self.universal_regions().to_region_vid(r)
441    }
442
443    /// Returns an iterator over all the outlives constraints.
444    pub(crate) fn outlives_constraints(&self) -> impl Iterator<Item = OutlivesConstraint<'tcx>> {
445        self.constraints.outlives().iter().copied()
446    }
447
448    /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
449    pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
450        self.universal_regions().annotate(tcx, err)
451    }
452
453    /// Returns `true` if the region `r` contains the point `p`.
454    ///
455    /// Panics if called before `solve()` executes,
456    pub(crate) fn region_contains(&self, r: RegionVid, p: impl ToElementIndex) -> bool {
457        let scc = self.constraint_sccs.scc(r);
458        self.scc_values.contains(scc, p)
459    }
460
461    /// Returns the lowest statement index in `start..=end` which is not contained by `r`.
462    ///
463    /// Panics if called before `solve()` executes.
464    pub(crate) fn first_non_contained_inclusive(
465        &self,
466        r: RegionVid,
467        block: BasicBlock,
468        start: usize,
469        end: usize,
470    ) -> Option<usize> {
471        let scc = self.constraint_sccs.scc(r);
472        self.scc_values.first_non_contained_inclusive(scc, block, start, end)
473    }
474
475    /// Returns access to the value of `r` for debugging purposes.
476    pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
477        let scc = self.constraint_sccs.scc(r);
478        self.scc_values.region_value_str(scc)
479    }
480
481    pub(crate) fn placeholders_contained_in(
482        &self,
483        r: RegionVid,
484    ) -> impl Iterator<Item = ty::PlaceholderRegion> {
485        let scc = self.constraint_sccs.scc(r);
486        self.scc_values.placeholders_contained_in(scc)
487    }
488
489    /// Performs region inference and report errors if we see any
490    /// unsatisfiable constraints. If this is a closure, returns the
491    /// region requirements to propagate to our creator, if any.
492    #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
493    pub(super) fn solve(
494        &mut self,
495        infcx: &InferCtxt<'tcx>,
496        body: &Body<'tcx>,
497        polonius_output: Option<Box<PoloniusOutput>>,
498    ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
499        let mir_def_id = body.source.def_id();
500        self.propagate_constraints();
501
502        let mut errors_buffer = RegionErrors::new(infcx.tcx);
503
504        // If this is a closure, we can propagate unsatisfied
505        // `outlives_requirements` to our creator, so create a vector
506        // to store those. Otherwise, we'll pass in `None` to the
507        // functions below, which will trigger them to report errors
508        // eagerly.
509        let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
510
511        self.check_type_tests(infcx, outlives_requirements.as_mut(), &mut errors_buffer);
512
513        debug!(?errors_buffer);
514        debug!(?outlives_requirements);
515
516        // In Polonius mode, the errors about missing universal region relations are in the output
517        // and need to be emitted or propagated. Otherwise, we need to check whether the
518        // constraints were too strong, and if so, emit or propagate those errors.
519        if infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled() {
520            self.check_polonius_subset_errors(
521                outlives_requirements.as_mut(),
522                &mut errors_buffer,
523                polonius_output
524                    .as_ref()
525                    .expect("Polonius output is unavailable despite `-Z polonius`"),
526            );
527        } else {
528            self.check_universal_regions(outlives_requirements.as_mut(), &mut errors_buffer);
529        }
530
531        debug!(?errors_buffer);
532
533        let outlives_requirements = outlives_requirements.unwrap_or_default();
534
535        if outlives_requirements.is_empty() {
536            (None, errors_buffer)
537        } else {
538            let num_external_vids = self.universal_regions().num_global_and_external_regions();
539            (
540                Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
541                errors_buffer,
542            )
543        }
544    }
545
546    /// Propagate the region constraints: this will grow the values
547    /// for each region variable until all the constraints are
548    /// satisfied. Note that some values may grow **too** large to be
549    /// feasible, but we check this later.
550    #[instrument(skip(self), level = "debug")]
551    fn propagate_constraints(&mut self) {
552        debug!("constraints={:#?}", {
553            let mut constraints: Vec<_> = self.outlives_constraints().collect();
554            constraints.sort_by_key(|c| (c.sup, c.sub));
555            constraints
556                .into_iter()
557                .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
558                .collect::<Vec<_>>()
559        });
560
561        // To propagate constraints, we walk the DAG induced by the
562        // SCC. For each SCC `A`, we visit its successors and compute
563        // their values, then we union all those values to get our
564        // own.
565        for scc_a in self.constraint_sccs.all_sccs() {
566            // Walk each SCC `B` such that `A: B`...
567            for &scc_b in self.constraint_sccs.successors(scc_a) {
568                debug!(?scc_b);
569                self.scc_values.add_region(scc_a, scc_b);
570            }
571        }
572    }
573
574    /// Returns `true` if all the elements in the value of `scc_b` are nameable
575    /// in `scc_a`. Used during constraint propagation, and only once
576    /// the value of `scc_b` has been computed.
577    fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
578        self.scc_annotations[scc_a].universe_compatible_with(self.scc_annotations[scc_b])
579    }
580
581    /// Once regions have been propagated, this method is used to see
582    /// whether the "type tests" produced by typeck were satisfied;
583    /// type tests encode type-outlives relationships like `T:
584    /// 'a`. See `TypeTest` for more details.
585    fn check_type_tests(
586        &self,
587        infcx: &InferCtxt<'tcx>,
588        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
589        errors_buffer: &mut RegionErrors<'tcx>,
590    ) {
591        let tcx = infcx.tcx;
592
593        // Sometimes we register equivalent type-tests that would
594        // result in basically the exact same error being reported to
595        // the user. Avoid that.
596        let mut deduplicate_errors = FxIndexSet::default();
597
598        for type_test in &self.type_tests {
599            debug!("check_type_test: {:?}", type_test);
600
601            let generic_ty = type_test.generic_kind.to_ty(tcx);
602            if self.eval_verify_bound(
603                infcx,
604                generic_ty,
605                type_test.lower_bound,
606                &type_test.verify_bound,
607            ) {
608                continue;
609            }
610
611            if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements
612                && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements)
613            {
614                continue;
615            }
616
617            // Type-test failed. Report the error.
618            let erased_generic_kind = infcx.tcx.erase_and_anonymize_regions(type_test.generic_kind);
619
620            // Skip duplicate-ish errors.
621            if deduplicate_errors.insert((
622                erased_generic_kind,
623                type_test.lower_bound,
624                type_test.span,
625            )) {
626                debug!(
627                    "check_type_test: reporting error for erased_generic_kind={:?}, \
628                     lower_bound_region={:?}, \
629                     type_test.span={:?}",
630                    erased_generic_kind, type_test.lower_bound, type_test.span,
631                );
632
633                errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
634            }
635        }
636    }
637
638    /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
639    /// prove to be satisfied. If this is a closure, we will attempt to
640    /// "promote" this type-test into our `ClosureRegionRequirements` and
641    /// hence pass it up the creator. To do this, we have to phrase the
642    /// type-test in terms of external free regions, as local free
643    /// regions are not nameable by the closure's creator.
644    ///
645    /// Promotion works as follows: we first check that the type `T`
646    /// contains only regions that the creator knows about. If this is
647    /// true, then -- as a consequence -- we know that all regions in
648    /// the type `T` are free regions that outlive the closure body. If
649    /// false, then promotion fails.
650    ///
651    /// Once we've promoted T, we have to "promote" `'X` to some region
652    /// that is "external" to the closure. Generally speaking, a region
653    /// may be the union of some points in the closure body as well as
654    /// various free lifetimes. We can ignore the points in the closure
655    /// body: if the type T can be expressed in terms of external regions,
656    /// we know it outlives the points in the closure body. That
657    /// just leaves the free regions.
658    ///
659    /// The idea then is to lower the `T: 'X` constraint into multiple
660    /// bounds -- e.g., if `'X` is the union of two free lifetimes,
661    /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
662    #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]
663    fn try_promote_type_test(
664        &self,
665        infcx: &InferCtxt<'tcx>,
666        type_test: &TypeTest<'tcx>,
667        propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
668    ) -> bool {
669        let tcx = infcx.tcx;
670        let TypeTest { generic_kind, lower_bound, span: blame_span, verify_bound: _ } = *type_test;
671
672        let generic_ty = generic_kind.to_ty(tcx);
673        let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
674            return false;
675        };
676
677        let r_scc = self.constraint_sccs.scc(lower_bound);
678        debug!(
679            "lower_bound = {:?} r_scc={:?} universe={:?}",
680            lower_bound,
681            r_scc,
682            self.max_nameable_universe(r_scc)
683        );
684        // If the type test requires that `T: 'a` where `'a` is a
685        // placeholder from another universe, that effectively requires
686        // `T: 'static`, so we have to propagate that requirement.
687        //
688        // It doesn't matter *what* universe because the promoted `T` will
689        // always be in the root universe.
690        if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
691            debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
692            let static_r = self.universal_regions().fr_static;
693            propagated_outlives_requirements.push(ClosureOutlivesRequirement {
694                subject,
695                outlived_free_region: static_r,
696                blame_span,
697                category: ConstraintCategory::Boring,
698            });
699
700            // we can return here -- the code below might push add'l constraints
701            // but they would all be weaker than this one.
702            return true;
703        }
704
705        // For each region outlived by lower_bound find a non-local,
706        // universal region (it may be the same region) and add it to
707        // `ClosureOutlivesRequirement`.
708        let mut found_outlived_universal_region = false;
709        for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
710            found_outlived_universal_region = true;
711            debug!("universal_region_outlived_by ur={:?}", ur);
712            let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
713            debug!(?non_local_ub);
714
715            // This is slightly too conservative. To show T: '1, given `'2: '1`
716            // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
717            // avoid potential non-determinism we approximate this by requiring
718            // T: '1 and T: '2.
719            for upper_bound in non_local_ub {
720                debug_assert!(self.universal_regions().is_universal_region(upper_bound));
721                debug_assert!(!self.universal_regions().is_local_free_region(upper_bound));
722
723                let requirement = ClosureOutlivesRequirement {
724                    subject,
725                    outlived_free_region: upper_bound,
726                    blame_span,
727                    category: ConstraintCategory::Boring,
728                };
729                debug!(?requirement, "adding closure requirement");
730                propagated_outlives_requirements.push(requirement);
731            }
732        }
733        // If we succeed to promote the subject, i.e. it only contains non-local regions,
734        // and fail to prove the type test inside of the closure, the `lower_bound` has to
735        // also be at least as large as some universal region, as the type test is otherwise
736        // trivial.
737        assert!(found_outlived_universal_region);
738        true
739    }
740
741    /// When we promote a type test `T: 'r`, we have to replace all region
742    /// variables in the type `T` with an equal universal region from the
743    /// closure signature.
744    /// This is not always possible, so this is a fallible process.
745    #[instrument(level = "debug", skip(self, infcx), ret)]
746    fn try_promote_type_test_subject(
747        &self,
748        infcx: &InferCtxt<'tcx>,
749        ty: Ty<'tcx>,
750    ) -> Option<ClosureOutlivesSubject<'tcx>> {
751        let tcx = infcx.tcx;
752        let mut failed = false;
753        let ty = fold_regions(tcx, ty, |r, _depth| {
754            let r_vid = self.to_region_vid(r);
755            let r_scc = self.constraint_sccs.scc(r_vid);
756
757            // The challenge is this. We have some region variable `r`
758            // whose value is a set of CFG points and universal
759            // regions. We want to find if that set is *equivalent* to
760            // any of the named regions found in the closure.
761            // To do so, we simply check every candidate `u_r` for equality.
762            self.scc_values
763                .universal_regions_outlived_by(r_scc)
764                .filter(|&u_r| !self.universal_regions().is_local_free_region(u_r))
765                .find(|&u_r| self.eval_equal(u_r, r_vid))
766                .map(|u_r| ty::Region::new_var(tcx, u_r))
767                // In case we could not find a named region to map to,
768                // we will return `None` below.
769                .unwrap_or_else(|| {
770                    failed = true;
771                    r
772                })
773        });
774
775        debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
776
777        // This will be true if we failed to promote some region.
778        if failed {
779            return None;
780        }
781
782        Some(ClosureOutlivesSubject::Ty(ClosureOutlivesSubjectTy::bind(tcx, ty)))
783    }
784
785    /// Like `universal_upper_bound`, but returns an approximation more suitable
786    /// for diagnostics. If `r` contains multiple disjoint universal regions
787    /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
788    /// This corresponds to picking named regions over unnamed regions
789    /// (e.g. picking early-bound regions over a closure late-bound region).
790    ///
791    /// This means that the returned value may not be a true upper bound, since
792    /// only 'static is known to outlive disjoint universal regions.
793    /// Therefore, this method should only be used in diagnostic code,
794    /// where displaying *some* named universal region is better than
795    /// falling back to 'static.
796    #[instrument(level = "debug", skip(self))]
797    pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
798        debug!("{}", self.region_value_str(r));
799
800        // Find the smallest universal region that contains all other
801        // universal regions within `region`.
802        let mut lub = self.universal_regions().fr_fn_body;
803        let r_scc = self.constraint_sccs.scc(r);
804        let static_r = self.universal_regions().fr_static;
805        for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
806            let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
807            debug!(?ur, ?lub, ?new_lub);
808            // The upper bound of two non-static regions is static: this
809            // means we know nothing about the relationship between these
810            // two regions. Pick a 'better' one to use when constructing
811            // a diagnostic
812            if ur != static_r && lub != static_r && new_lub == static_r {
813                // Prefer the region with an `external_name` - this
814                // indicates that the region is early-bound, so working with
815                // it can produce a nicer error.
816                if self.region_definition(ur).external_name.is_some() {
817                    lub = ur;
818                } else if self.region_definition(lub).external_name.is_some() {
819                    // Leave lub unchanged
820                } else {
821                    // If we get here, we don't have any reason to prefer
822                    // one region over the other. Just pick the
823                    // one with the lower index for now.
824                    lub = std::cmp::min(ur, lub);
825                }
826            } else {
827                lub = new_lub;
828            }
829        }
830
831        debug!(?r, ?lub);
832
833        lub
834    }
835
836    /// Tests if `test` is true when applied to `lower_bound` at
837    /// `point`.
838    fn eval_verify_bound(
839        &self,
840        infcx: &InferCtxt<'tcx>,
841        generic_ty: Ty<'tcx>,
842        lower_bound: RegionVid,
843        verify_bound: &VerifyBound<'tcx>,
844    ) -> bool {
845        debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
846
847        match verify_bound {
848            VerifyBound::IfEq(verify_if_eq_b) => {
849                self.eval_if_eq(infcx, generic_ty, lower_bound, *verify_if_eq_b)
850            }
851
852            VerifyBound::IsEmpty => {
853                let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
854                self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
855            }
856
857            VerifyBound::OutlivedBy(r) => {
858                let r_vid = self.to_region_vid(*r);
859                self.eval_outlives(r_vid, lower_bound)
860            }
861
862            VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
863                self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)
864            }),
865
866            VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
867                self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)
868            }),
869        }
870    }
871
872    fn eval_if_eq(
873        &self,
874        infcx: &InferCtxt<'tcx>,
875        generic_ty: Ty<'tcx>,
876        lower_bound: RegionVid,
877        verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
878    ) -> bool {
879        let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
880        let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
881        match test_type_match::extract_verify_if_eq(infcx.tcx, &verify_if_eq_b, generic_ty) {
882            Some(r) => {
883                let r_vid = self.to_region_vid(r);
884                self.eval_outlives(r_vid, lower_bound)
885            }
886            None => false,
887        }
888    }
889
890    /// This is a conservative normalization procedure. It takes every
891    /// free region in `value` and replaces it with the
892    /// "representative" of its SCC (see `scc_representatives` field).
893    /// We are guaranteed that if two values normalize to the same
894    /// thing, then they are equal; this is a conservative check in
895    /// that they could still be equal even if they normalize to
896    /// different results. (For example, there might be two regions
897    /// with the same value that are not in the same SCC).
898    ///
899    /// N.B., this is not an ideal approach and I would like to revisit
900    /// it. However, it works pretty well in practice. In particular,
901    /// this is needed to deal with projection outlives bounds like
902    ///
903    /// ```text
904    /// <T as Foo<'0>>::Item: '1
905    /// ```
906    ///
907    /// In particular, this routine winds up being important when
908    /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
909    /// environment. In this case, if we can show that `'0 == 'a`,
910    /// and that `'b: '1`, then we know that the clause is
911    /// satisfied. In such cases, particularly due to limitations of
912    /// the trait solver =), we usually wind up with a where-clause like
913    /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
914    /// a constraint, and thus ensures that they are in the same SCC.
915    ///
916    /// So why can't we do a more correct routine? Well, we could
917    /// *almost* use the `relate_tys` code, but the way it is
918    /// currently setup it creates inference variables to deal with
919    /// higher-ranked things and so forth, and right now the inference
920    /// context is not permitted to make more inference variables. So
921    /// we use this kind of hacky solution.
922    fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
923    where
924        T: TypeFoldable<TyCtxt<'tcx>>,
925    {
926        fold_regions(tcx, value, |r, _db| {
927            let vid = self.to_region_vid(r);
928            let scc = self.constraint_sccs.scc(vid);
929            let repr = self.scc_representative(scc);
930            ty::Region::new_var(tcx, repr)
931        })
932    }
933
934    /// Evaluate whether `sup_region == sub_region`.
935    ///
936    /// Panics if called before `solve()` executes,
937    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
938    pub fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
939        self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
940    }
941
942    /// Evaluate whether `sup_region: sub_region`.
943    ///
944    /// Panics if called before `solve()` executes,
945    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
946    #[instrument(skip(self), level = "debug", ret)]
947    pub fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
948        debug!(
949            "sup_region's value = {:?} universal={:?}",
950            self.region_value_str(sup_region),
951            self.universal_regions().is_universal_region(sup_region),
952        );
953        debug!(
954            "sub_region's value = {:?} universal={:?}",
955            self.region_value_str(sub_region),
956            self.universal_regions().is_universal_region(sub_region),
957        );
958
959        let sub_region_scc = self.constraint_sccs.scc(sub_region);
960        let sup_region_scc = self.constraint_sccs.scc(sup_region);
961
962        if sub_region_scc == sup_region_scc {
963            debug!("{sup_region:?}: {sub_region:?} holds trivially; they are in the same SCC");
964            return true;
965        }
966
967        // If we are checking that `'sup: 'sub`, and `'sub` contains
968        // some placeholder that `'sup` cannot name, then this is only
969        // true if `'sup` outlives static.
970        if !self.universe_compatible(sub_region_scc, sup_region_scc) {
971            debug!(
972                "sub universe `{sub_region_scc:?}` is not nameable \
973                by super `{sup_region_scc:?}`, promoting to static",
974            );
975
976            return self.eval_outlives(sup_region, self.universal_regions().fr_static);
977        }
978
979        // Both the `sub_region` and `sup_region` consist of the union
980        // of some number of universal regions (along with the union
981        // of various points in the CFG; ignore those points for
982        // now). Therefore, the sup-region outlives the sub-region if,
983        // for each universal region R1 in the sub-region, there
984        // exists some region R2 in the sup-region that outlives R1.
985        let universal_outlives =
986            self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
987                self.scc_values
988                    .universal_regions_outlived_by(sup_region_scc)
989                    .any(|r2| self.universal_region_relations.outlives(r2, r1))
990            });
991
992        if !universal_outlives {
993            debug!("sub region contains a universal region not present in super");
994            return false;
995        }
996
997        // Now we have to compare all the points in the sub region and make
998        // sure they exist in the sup region.
999
1000        if self.universal_regions().is_universal_region(sup_region) {
1001            // Micro-opt: universal regions contain all points.
1002            debug!("super is universal and hence contains all points");
1003            return true;
1004        }
1005
1006        debug!("comparison between points in sup/sub");
1007
1008        self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1009    }
1010
1011    /// Once regions have been propagated, this method is used to see
1012    /// whether any of the constraints were too strong. In particular,
1013    /// we want to check for a case where a universally quantified
1014    /// region exceeded its bounds. Consider:
1015    /// ```compile_fail
1016    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1017    /// ```
1018    /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1019    /// and hence we establish (transitively) a constraint that
1020    /// `'a: 'b`. The `propagate_constraints` code above will
1021    /// therefore add `end('a)` into the region for `'b` -- but we
1022    /// have no evidence that `'b` outlives `'a`, so we want to report
1023    /// an error.
1024    ///
1025    /// If `propagated_outlives_requirements` is `Some`, then we will
1026    /// push unsatisfied obligations into there. Otherwise, we'll
1027    /// report them as errors.
1028    fn check_universal_regions(
1029        &self,
1030        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1031        errors_buffer: &mut RegionErrors<'tcx>,
1032    ) {
1033        for (fr, fr_definition) in self.definitions.iter_enumerated() {
1034            debug!(?fr, ?fr_definition);
1035            match fr_definition.origin {
1036                NllRegionVariableOrigin::FreeRegion => {
1037                    // Go through each of the universal regions `fr` and check that
1038                    // they did not grow too large, accumulating any requirements
1039                    // for our caller into the `outlives_requirements` vector.
1040                    self.check_universal_region(
1041                        fr,
1042                        &mut propagated_outlives_requirements,
1043                        errors_buffer,
1044                    );
1045                }
1046
1047                NllRegionVariableOrigin::Placeholder(placeholder) => {
1048                    self.check_bound_universal_region(fr, placeholder, errors_buffer);
1049                }
1050
1051                NllRegionVariableOrigin::Existential { .. } => {
1052                    // nothing to check here
1053                }
1054            }
1055        }
1056    }
1057
1058    /// Checks if Polonius has found any unexpected free region relations.
1059    ///
1060    /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1061    /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1062    /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1063    /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1064    ///
1065    /// More details can be found in this blog post by Niko:
1066    /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1067    ///
1068    /// In the canonical example
1069    /// ```compile_fail
1070    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1071    /// ```
1072    /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1073    /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1074    /// constraint holds.
1075    ///
1076    /// If `propagated_outlives_requirements` is `Some`, then we will
1077    /// push unsatisfied obligations into there. Otherwise, we'll
1078    /// report them as errors.
1079    fn check_polonius_subset_errors(
1080        &self,
1081        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1082        errors_buffer: &mut RegionErrors<'tcx>,
1083        polonius_output: &PoloniusOutput,
1084    ) {
1085        debug!(
1086            "check_polonius_subset_errors: {} subset_errors",
1087            polonius_output.subset_errors.len()
1088        );
1089
1090        // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1091        // declared ("known") was found by Polonius, so emit an error, or propagate the
1092        // requirements for our caller into the `propagated_outlives_requirements` vector.
1093        //
1094        // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1095        // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1096        // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1097        // and the "superset origin" is the outlived "shorter free region".
1098        //
1099        // Note: Polonius will produce a subset error at every point where the unexpected
1100        // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1101        // for diagnostics in the future, e.g. to point more precisely at the key locations
1102        // requiring this constraint to hold. However, the error and diagnostics code downstream
1103        // expects that these errors are not duplicated (and that they are in a certain order).
1104        // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1105        // anonymous lifetimes for example, could give these names differently, while others like
1106        // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1107        // duplicated. The polonius subset errors are deduplicated here, while keeping the
1108        // CFG-location ordering.
1109        // We can iterate the HashMap here because the result is sorted afterwards.
1110        #[allow(rustc::potential_query_instability)]
1111        let mut subset_errors: Vec<_> = polonius_output
1112            .subset_errors
1113            .iter()
1114            .flat_map(|(_location, subset_errors)| subset_errors.iter())
1115            .collect();
1116        subset_errors.sort();
1117        subset_errors.dedup();
1118
1119        for &(longer_fr, shorter_fr) in subset_errors.into_iter() {
1120            debug!(
1121                "check_polonius_subset_errors: subset_error longer_fr={:?},\
1122                 shorter_fr={:?}",
1123                longer_fr, shorter_fr
1124            );
1125
1126            let propagated = self.try_propagate_universal_region_error(
1127                longer_fr.into(),
1128                shorter_fr.into(),
1129                &mut propagated_outlives_requirements,
1130            );
1131            if propagated == RegionRelationCheckResult::Error {
1132                errors_buffer.push(RegionErrorKind::RegionError {
1133                    longer_fr: longer_fr.into(),
1134                    shorter_fr: shorter_fr.into(),
1135                    fr_origin: NllRegionVariableOrigin::FreeRegion,
1136                    is_reported: true,
1137                });
1138            }
1139        }
1140
1141        // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1142        // a more complete picture on how to separate this responsibility.
1143        for (fr, fr_definition) in self.definitions.iter_enumerated() {
1144            match fr_definition.origin {
1145                NllRegionVariableOrigin::FreeRegion => {
1146                    // handled by polonius above
1147                }
1148
1149                NllRegionVariableOrigin::Placeholder(placeholder) => {
1150                    self.check_bound_universal_region(fr, placeholder, errors_buffer);
1151                }
1152
1153                NllRegionVariableOrigin::Existential { .. } => {
1154                    // nothing to check here
1155                }
1156            }
1157        }
1158    }
1159
1160    /// The largest universe of any region nameable from this SCC.
1161    fn max_nameable_universe(&self, scc: ConstraintSccIndex) -> UniverseIndex {
1162        self.scc_annotations[scc].max_nameable_universe()
1163    }
1164
1165    /// Checks the final value for the free region `fr` to see if it
1166    /// grew too large. In particular, examine what `end(X)` points
1167    /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1168    /// fr`, we want to check that `fr: X`. If not, that's either an
1169    /// error, or something we have to propagate to our creator.
1170    ///
1171    /// Things that are to be propagated are accumulated into the
1172    /// `outlives_requirements` vector.
1173    #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]
1174    fn check_universal_region(
1175        &self,
1176        longer_fr: RegionVid,
1177        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1178        errors_buffer: &mut RegionErrors<'tcx>,
1179    ) {
1180        let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1181
1182        // Because this free region must be in the ROOT universe, we
1183        // know it cannot contain any bound universes.
1184        assert!(self.max_nameable_universe(longer_fr_scc).is_root());
1185
1186        // Only check all of the relations for the main representative of each
1187        // SCC, otherwise just check that we outlive said representative. This
1188        // reduces the number of redundant relations propagated out of
1189        // closures.
1190        // Note that the representative will be a universal region if there is
1191        // one in this SCC, so we will always check the representative here.
1192        let representative = self.scc_representative(longer_fr_scc);
1193        if representative != longer_fr {
1194            if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1195                longer_fr,
1196                representative,
1197                propagated_outlives_requirements,
1198            ) {
1199                errors_buffer.push(RegionErrorKind::RegionError {
1200                    longer_fr,
1201                    shorter_fr: representative,
1202                    fr_origin: NllRegionVariableOrigin::FreeRegion,
1203                    is_reported: true,
1204                });
1205            }
1206            return;
1207        }
1208
1209        // Find every region `o` such that `fr: o`
1210        // (because `fr` includes `end(o)`).
1211        let mut error_reported = false;
1212        for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1213            if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1214                longer_fr,
1215                shorter_fr,
1216                propagated_outlives_requirements,
1217            ) {
1218                // We only report the first region error. Subsequent errors are hidden so as
1219                // not to overwhelm the user, but we do record them so as to potentially print
1220                // better diagnostics elsewhere...
1221                errors_buffer.push(RegionErrorKind::RegionError {
1222                    longer_fr,
1223                    shorter_fr,
1224                    fr_origin: NllRegionVariableOrigin::FreeRegion,
1225                    is_reported: !error_reported,
1226                });
1227
1228                error_reported = true;
1229            }
1230        }
1231    }
1232
1233    /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1234    /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1235    /// error.
1236    fn check_universal_region_relation(
1237        &self,
1238        longer_fr: RegionVid,
1239        shorter_fr: RegionVid,
1240        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1241    ) -> RegionRelationCheckResult {
1242        // If it is known that `fr: o`, carry on.
1243        if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1244            RegionRelationCheckResult::Ok
1245        } else {
1246            // If we are not in a context where we can't propagate errors, or we
1247            // could not shrink `fr` to something smaller, then just report an
1248            // error.
1249            //
1250            // Note: in this case, we use the unapproximated regions to report the
1251            // error. This gives better error messages in some cases.
1252            self.try_propagate_universal_region_error(
1253                longer_fr,
1254                shorter_fr,
1255                propagated_outlives_requirements,
1256            )
1257        }
1258    }
1259
1260    /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1261    /// creator. If we cannot, then the caller should report an error to the user.
1262    fn try_propagate_universal_region_error(
1263        &self,
1264        longer_fr: RegionVid,
1265        shorter_fr: RegionVid,
1266        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1267    ) -> RegionRelationCheckResult {
1268        if let Some(propagated_outlives_requirements) = propagated_outlives_requirements
1269            // Shrink `longer_fr` until we find a non-local region (if we do).
1270            // We'll call it `fr-` -- it's ever so slightly smaller than
1271            // `longer_fr`.
1272            && let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1273        {
1274            debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1275
1276            let blame_constraint = self
1277                .best_blame_constraint(longer_fr, NllRegionVariableOrigin::FreeRegion, shorter_fr)
1278                .0;
1279
1280            // Grow `shorter_fr` until we find some non-local regions. (We
1281            // always will.)  We'll call them `shorter_fr+` -- they're ever
1282            // so slightly larger than `shorter_fr`.
1283            let shorter_fr_plus =
1284                self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1285            debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus);
1286            for fr in shorter_fr_plus {
1287                // Push the constraint `fr-: shorter_fr+`
1288                propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1289                    subject: ClosureOutlivesSubject::Region(fr_minus),
1290                    outlived_free_region: fr,
1291                    blame_span: blame_constraint.cause.span,
1292                    category: blame_constraint.category,
1293                });
1294            }
1295            return RegionRelationCheckResult::Propagated;
1296        }
1297
1298        RegionRelationCheckResult::Error
1299    }
1300
1301    fn check_bound_universal_region(
1302        &self,
1303        longer_fr: RegionVid,
1304        placeholder: ty::PlaceholderRegion,
1305        errors_buffer: &mut RegionErrors<'tcx>,
1306    ) {
1307        debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1308
1309        let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1310        debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1311
1312        // If we have some bound universal region `'a`, then the only
1313        // elements it can contain is itself -- we don't know anything
1314        // else about it!
1315        if let Some(error_element) = self
1316            .scc_values
1317            .elements_contained_in(longer_fr_scc)
1318            .find(|e| *e != RegionElement::PlaceholderRegion(placeholder))
1319        {
1320            // Stop after the first error, it gets too noisy otherwise, and does not provide more information.
1321            errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1322                longer_fr,
1323                error_element,
1324                placeholder,
1325            });
1326        } else {
1327            debug!("check_bound_universal_region: all bounds satisfied");
1328        }
1329    }
1330
1331    pub(crate) fn constraint_path_between_regions(
1332        &self,
1333        from_region: RegionVid,
1334        to_region: RegionVid,
1335    ) -> Option<Vec<OutlivesConstraint<'tcx>>> {
1336        if from_region == to_region {
1337            bug!("Tried to find a path between {from_region:?} and itself!");
1338        }
1339        self.constraint_path_to(from_region, |to| to == to_region, true).map(|o| o.0)
1340    }
1341
1342    /// Walks the graph of constraints (where `'a: 'b` is considered
1343    /// an edge `'a -> 'b`) to find a path from `from_region` to
1344    /// `to_region`.
1345    ///
1346    /// Returns: a series of constraints as well as the region `R`
1347    /// that passed the target test.
1348    /// If `include_static_outlives_all` is `true`, then the synthetic
1349    /// outlives constraints `'static -> a` for every region `a` are
1350    /// considered in the search, otherwise they are ignored.
1351    #[instrument(skip(self, target_test), ret)]
1352    pub(crate) fn constraint_path_to(
1353        &self,
1354        from_region: RegionVid,
1355        target_test: impl Fn(RegionVid) -> bool,
1356        include_placeholder_static: bool,
1357    ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1358        self.find_constraint_path_between_regions_inner(
1359            true,
1360            from_region,
1361            &target_test,
1362            include_placeholder_static,
1363        )
1364        .or_else(|| {
1365            self.find_constraint_path_between_regions_inner(
1366                false,
1367                from_region,
1368                &target_test,
1369                include_placeholder_static,
1370            )
1371        })
1372    }
1373
1374    /// The constraints we get from equating the hidden type of each use of an opaque
1375    /// with its final concrete type may end up getting preferred over other, potentially
1376    /// longer constraint paths.
1377    ///
1378    /// Given that we compute the final concrete type by relying on this existing constraint
1379    /// path, this can easily end up hiding the actual reason for why we require these regions
1380    /// to be equal.
1381    ///
1382    /// To handle this, we first look at the path while ignoring these constraints and then
1383    /// retry while considering them. This is not perfect, as the `from_region` may have already
1384    /// been partially related to its argument region, so while we rely on a member constraint
1385    /// to get a complete path, the most relevant step of that path already existed before then.
1386    fn find_constraint_path_between_regions_inner(
1387        &self,
1388        ignore_opaque_type_constraints: bool,
1389        from_region: RegionVid,
1390        target_test: impl Fn(RegionVid) -> bool,
1391        include_placeholder_static: bool,
1392    ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1393        let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1394        context[from_region] = Trace::StartRegion;
1395
1396        let fr_static = self.universal_regions().fr_static;
1397
1398        // Use a deque so that we do a breadth-first search. We will
1399        // stop at the first match, which ought to be the shortest
1400        // path (fewest constraints).
1401        let mut deque = VecDeque::new();
1402        deque.push_back(from_region);
1403
1404        while let Some(r) = deque.pop_front() {
1405            debug!(
1406                "constraint_path_to: from_region={:?} r={:?} value={}",
1407                from_region,
1408                r,
1409                self.region_value_str(r),
1410            );
1411
1412            // Check if we reached the region we were looking for. If so,
1413            // we can reconstruct the path that led to it and return it.
1414            if target_test(r) {
1415                let mut result = vec![];
1416                let mut p = r;
1417                // This loop is cold and runs at the end, which is why we delay
1418                // `OutlivesConstraint` construction until now.
1419                loop {
1420                    match context[p] {
1421                        Trace::FromGraph(c) => {
1422                            p = c.sup;
1423                            result.push(*c);
1424                        }
1425
1426                        Trace::FromStatic(sub) => {
1427                            let c = OutlivesConstraint {
1428                                sup: fr_static,
1429                                sub,
1430                                locations: Locations::All(DUMMY_SP),
1431                                span: DUMMY_SP,
1432                                category: ConstraintCategory::Internal,
1433                                variance_info: ty::VarianceDiagInfo::default(),
1434                                from_closure: false,
1435                            };
1436                            p = c.sup;
1437                            result.push(c);
1438                        }
1439
1440                        Trace::StartRegion => {
1441                            result.reverse();
1442                            return Some((result, r));
1443                        }
1444
1445                        Trace::NotVisited => {
1446                            bug!("found unvisited region {:?} on path to {:?}", p, r)
1447                        }
1448                    }
1449                }
1450            }
1451
1452            // Otherwise, walk over the outgoing constraints and
1453            // enqueue any regions we find, keeping track of how we
1454            // reached them.
1455
1456            // A constraint like `'r: 'x` can come from our constraint
1457            // graph.
1458
1459            // Always inline this closure because it can be hot.
1460            let mut handle_trace = #[inline(always)]
1461            |sub, trace| {
1462                if let Trace::NotVisited = context[sub] {
1463                    context[sub] = trace;
1464                    deque.push_back(sub);
1465                }
1466            };
1467
1468            // If this is the `'static` region and the graph's direction is normal, then set up the
1469            // Edges iterator to return all regions (#53178).
1470            if r == fr_static && self.constraint_graph.is_normal() {
1471                for sub in self.constraint_graph.outgoing_edges_from_static() {
1472                    handle_trace(sub, Trace::FromStatic(sub));
1473                }
1474            } else {
1475                let edges = self.constraint_graph.outgoing_edges_from_graph(r, &self.constraints);
1476                // This loop can be hot.
1477                for constraint in edges {
1478                    match constraint.category {
1479                        ConstraintCategory::OutlivesUnnameablePlaceholder(_)
1480                            if !include_placeholder_static =>
1481                        {
1482                            debug!("Ignoring illegal placeholder constraint: {constraint:?}");
1483                            continue;
1484                        }
1485                        ConstraintCategory::OpaqueType if ignore_opaque_type_constraints => {
1486                            debug!("Ignoring member constraint: {constraint:?}");
1487                            continue;
1488                        }
1489                        _ => {}
1490                    }
1491
1492                    debug_assert_eq!(constraint.sup, r);
1493                    handle_trace(constraint.sub, Trace::FromGraph(constraint));
1494                }
1495            }
1496        }
1497
1498        None
1499    }
1500
1501    /// Finds some region R such that `fr1: R` and `R` is live at `location`.
1502    #[instrument(skip(self), level = "trace", ret)]
1503    pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, location: Location) -> RegionVid {
1504        trace!(scc = ?self.constraint_sccs.scc(fr1));
1505        trace!(universe = ?self.max_nameable_universe(self.constraint_sccs.scc(fr1)));
1506        self.constraint_path_to(fr1, |r| {
1507            trace!(?r, liveness_constraints=?self.liveness_constraints.pretty_print_live_points(r));
1508            self.liveness_constraints.is_live_at(r, location)
1509        }, true).unwrap().1
1510    }
1511
1512    /// Get the region outlived by `longer_fr` and live at `element`.
1513    pub(crate) fn region_from_element(
1514        &self,
1515        longer_fr: RegionVid,
1516        element: &RegionElement,
1517    ) -> RegionVid {
1518        match *element {
1519            RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1520            RegionElement::RootUniversalRegion(r) => r,
1521            RegionElement::PlaceholderRegion(error_placeholder) => self
1522                .definitions
1523                .iter_enumerated()
1524                .find_map(|(r, definition)| match definition.origin {
1525                    NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1526                    _ => None,
1527                })
1528                .unwrap(),
1529        }
1530    }
1531
1532    /// Get the region definition of `r`.
1533    pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1534        &self.definitions[r]
1535    }
1536
1537    /// Check if the SCC of `r` contains `upper`.
1538    pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1539        let r_scc = self.constraint_sccs.scc(r);
1540        self.scc_values.contains(r_scc, upper)
1541    }
1542
1543    pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
1544        &self.universal_region_relations.universal_regions
1545    }
1546
1547    /// Tries to find the best constraint to blame for the fact that
1548    /// `R: from_region`, where `R` is some region that meets
1549    /// `target_test`. This works by following the constraint graph,
1550    /// creating a constraint path that forces `R` to outlive
1551    /// `from_region`, and then finding the best choices within that
1552    /// path to blame.
1553    #[instrument(level = "debug", skip(self))]
1554    pub(crate) fn best_blame_constraint(
1555        &self,
1556        from_region: RegionVid,
1557        from_region_origin: NllRegionVariableOrigin,
1558        to_region: RegionVid,
1559    ) -> (BlameConstraint<'tcx>, Vec<OutlivesConstraint<'tcx>>) {
1560        assert!(from_region != to_region, "Trying to blame a region for itself!");
1561
1562        let path = self.constraint_path_between_regions(from_region, to_region).unwrap();
1563
1564        // If we are passing through a constraint added because we reached an unnameable placeholder `'unnameable`,
1565        // redirect search towards `'unnameable`.
1566        let due_to_placeholder_outlives = path.iter().find_map(|c| {
1567            if let ConstraintCategory::OutlivesUnnameablePlaceholder(unnameable) = c.category {
1568                Some(unnameable)
1569            } else {
1570                None
1571            }
1572        });
1573
1574        // Edge case: it's possible that `'from_region` is an unnameable placeholder.
1575        let path = if let Some(unnameable) = due_to_placeholder_outlives
1576            && unnameable != from_region
1577        {
1578            // We ignore the extra edges due to unnameable placeholders to get
1579            // an explanation that was present in the original constraint graph.
1580            self.constraint_path_to(from_region, |r| r == unnameable, false).unwrap().0
1581        } else {
1582            path
1583        };
1584
1585        debug!(
1586            "path={:#?}",
1587            path.iter()
1588                .map(|c| format!(
1589                    "{:?} ({:?}: {:?})",
1590                    c,
1591                    self.constraint_sccs.scc(c.sup),
1592                    self.constraint_sccs.scc(c.sub),
1593                ))
1594                .collect::<Vec<_>>()
1595        );
1596
1597        // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
1598        // Instead, we use it to produce an improved `ObligationCauseCode`.
1599        // FIXME - determine what we should do if we encounter multiple
1600        // `ConstraintCategory::Predicate` constraints. Currently, we just pick the first one.
1601        let cause_code = path
1602            .iter()
1603            .find_map(|constraint| {
1604                if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
1605                    // We currently do not store the `DefId` in the `ConstraintCategory`
1606                    // for performances reasons. The error reporting code used by NLL only
1607                    // uses the span, so this doesn't cause any problems at the moment.
1608                    Some(ObligationCauseCode::WhereClause(CRATE_DEF_ID.to_def_id(), predicate_span))
1609                } else {
1610                    None
1611                }
1612            })
1613            .unwrap_or_else(|| ObligationCauseCode::Misc);
1614
1615        // When reporting an error, there is typically a chain of constraints leading from some
1616        // "source" region which must outlive some "target" region.
1617        // In most cases, we prefer to "blame" the constraints closer to the target --
1618        // but there is one exception. When constraints arise from higher-ranked subtyping,
1619        // we generally prefer to blame the source value,
1620        // as the "target" in this case tends to be some type annotation that the user gave.
1621        // Therefore, if we find that the region origin is some instantiation
1622        // of a higher-ranked region, we start our search from the "source" point
1623        // rather than the "target", and we also tweak a few other things.
1624        //
1625        // An example might be this bit of Rust code:
1626        //
1627        // ```rust
1628        // let x: fn(&'static ()) = |_| {};
1629        // let y: for<'a> fn(&'a ()) = x;
1630        // ```
1631        //
1632        // In MIR, this will be converted into a combination of assignments and type ascriptions.
1633        // In particular, the 'static is imposed through a type ascription:
1634        //
1635        // ```rust
1636        // x = ...;
1637        // AscribeUserType(x, fn(&'static ())
1638        // y = x;
1639        // ```
1640        //
1641        // We wind up ultimately with constraints like
1642        //
1643        // ```rust
1644        // !a: 'temp1 // from the `y = x` statement
1645        // 'temp1: 'temp2
1646        // 'temp2: 'static // from the AscribeUserType
1647        // ```
1648        //
1649        // and here we prefer to blame the source (the y = x statement).
1650        let blame_source = match from_region_origin {
1651            NllRegionVariableOrigin::FreeRegion => true,
1652            NllRegionVariableOrigin::Placeholder(_) => false,
1653            // `'existential: 'whatever` never results in a region error by itself.
1654            // We may always infer it to `'static` afterall. This means while an error
1655            // path may go through an existential, these existentials are never the
1656            // `from_region`.
1657            NllRegionVariableOrigin::Existential { name: _ } => {
1658                unreachable!("existentials can outlive everything")
1659            }
1660        };
1661
1662        // To pick a constraint to blame, we organize constraints by how interesting we expect them
1663        // to be in diagnostics, then pick the most interesting one closest to either the source or
1664        // the target on our constraint path.
1665        let constraint_interest = |constraint: &OutlivesConstraint<'tcx>| {
1666            // Try to avoid blaming constraints from desugarings, since they may not clearly match
1667            // match what users have written. As an exception, allow blaming returns generated by
1668            // `?` desugaring, since the correspondence is fairly clear.
1669            let category = if let Some(kind) = constraint.span.desugaring_kind()
1670                && (kind != DesugaringKind::QuestionMark
1671                    || !matches!(constraint.category, ConstraintCategory::Return(_)))
1672            {
1673                ConstraintCategory::Boring
1674            } else {
1675                constraint.category
1676            };
1677
1678            let interest = match category {
1679                // Returns usually provide a type to blame and have specially written diagnostics,
1680                // so prioritize them.
1681                ConstraintCategory::Return(_) => 0,
1682                // Unsizing coercions are interesting, since we have a note for that:
1683                // `BorrowExplanation::add_object_lifetime_default_note`.
1684                // FIXME(dianne): That note shouldn't depend on a coercion being blamed; see issue
1685                // #131008 for an example of where we currently don't emit it but should.
1686                // Once the note is handled properly, this case should be removed. Until then, it
1687                // should be as limited as possible; the note is prone to false positives and this
1688                // constraint usually isn't best to blame.
1689                ConstraintCategory::Cast {
1690                    unsize_to: Some(unsize_ty),
1691                    is_implicit_coercion: true,
1692                } if to_region == self.universal_regions().fr_static
1693                    // Mirror the note's condition, to minimize how often this diverts blame.
1694                    && let ty::Adt(_, args) = unsize_ty.kind()
1695                    && args.iter().any(|arg| arg.as_type().is_some_and(|ty| ty.is_trait()))
1696                    // Mimic old logic for this, to minimize false positives in tests.
1697                    && !path
1698                        .iter()
1699                        .any(|c| matches!(c.category, ConstraintCategory::TypeAnnotation(_))) =>
1700                {
1701                    1
1702                }
1703                // Between other interesting constraints, order by their position on the `path`.
1704                ConstraintCategory::Yield
1705                | ConstraintCategory::UseAsConst
1706                | ConstraintCategory::UseAsStatic
1707                | ConstraintCategory::TypeAnnotation(
1708                    AnnotationSource::Ascription
1709                    | AnnotationSource::Declaration
1710                    | AnnotationSource::OpaqueCast,
1711                )
1712                | ConstraintCategory::Cast { .. }
1713                | ConstraintCategory::CallArgument(_)
1714                | ConstraintCategory::CopyBound
1715                | ConstraintCategory::SizedBound
1716                | ConstraintCategory::Assignment
1717                | ConstraintCategory::Usage
1718                | ConstraintCategory::ClosureUpvar(_) => 2,
1719                // Generic arguments are unlikely to be what relates regions together
1720                ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => 3,
1721                // We handle predicates and opaque types specially; don't prioritize them here.
1722                ConstraintCategory::Predicate(_) | ConstraintCategory::OpaqueType => 4,
1723                // `Boring` constraints can correspond to user-written code and have useful spans,
1724                // but don't provide any other useful information for diagnostics.
1725                ConstraintCategory::Boring => 5,
1726                // `BoringNoLocation` constraints can point to user-written code, but are less
1727                // specific, and are not used for relations that would make sense to blame.
1728                ConstraintCategory::BoringNoLocation => 6,
1729                // Do not blame internal constraints.
1730                ConstraintCategory::OutlivesUnnameablePlaceholder(_) => 7,
1731                ConstraintCategory::Internal => 8,
1732            };
1733
1734            debug!("constraint {constraint:?} category: {category:?}, interest: {interest:?}");
1735
1736            interest
1737        };
1738
1739        let best_choice = if blame_source {
1740            path.iter().enumerate().rev().min_by_key(|(_, c)| constraint_interest(c)).unwrap().0
1741        } else {
1742            path.iter().enumerate().min_by_key(|(_, c)| constraint_interest(c)).unwrap().0
1743        };
1744
1745        debug!(?best_choice, ?blame_source);
1746
1747        let best_constraint = if let Some(next) = path.get(best_choice + 1)
1748            && matches!(path[best_choice].category, ConstraintCategory::Return(_))
1749            && next.category == ConstraintCategory::OpaqueType
1750        {
1751            // The return expression is being influenced by the return type being
1752            // impl Trait, point at the return type and not the return expr.
1753            *next
1754        } else if path[best_choice].category == ConstraintCategory::Return(ReturnConstraint::Normal)
1755            && let Some(field) = path.iter().find_map(|p| {
1756                if let ConstraintCategory::ClosureUpvar(f) = p.category { Some(f) } else { None }
1757            })
1758        {
1759            OutlivesConstraint {
1760                category: ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field)),
1761                ..path[best_choice]
1762            }
1763        } else {
1764            path[best_choice]
1765        };
1766
1767        assert!(
1768            !matches!(
1769                best_constraint.category,
1770                ConstraintCategory::OutlivesUnnameablePlaceholder(_)
1771            ),
1772            "Illegal placeholder constraint blamed; should have redirected to other region relation"
1773        );
1774
1775        let blame_constraint = BlameConstraint {
1776            category: best_constraint.category,
1777            from_closure: best_constraint.from_closure,
1778            cause: ObligationCause::new(best_constraint.span, CRATE_DEF_ID, cause_code.clone()),
1779            variance_info: best_constraint.variance_info,
1780        };
1781        (blame_constraint, path)
1782    }
1783
1784    pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
1785        // Query canonicalization can create local superuniverses (for example in
1786        // `InferCtx::query_response_instantiation_guess`), but they don't have an associated
1787        // `UniverseInfo` explaining why they were created.
1788        // This can cause ICEs if these causes are accessed in diagnostics, for example in issue
1789        // #114907 where this happens via liveness and dropck outlives results.
1790        // Therefore, we return a default value in case that happens, which should at worst emit a
1791        // suboptimal error, instead of the ICE.
1792        self.universe_causes.get(&universe).cloned().unwrap_or_else(UniverseInfo::other)
1793    }
1794
1795    /// Tries to find the terminator of the loop in which the region 'r' resides.
1796    /// Returns the location of the terminator if found.
1797    pub(crate) fn find_loop_terminator_location(
1798        &self,
1799        r: RegionVid,
1800        body: &Body<'_>,
1801    ) -> Option<Location> {
1802        let scc = self.constraint_sccs.scc(r);
1803        let locations = self.scc_values.locations_outlived_by(scc);
1804        for location in locations {
1805            let bb = &body[location.block];
1806            if let Some(terminator) = &bb.terminator
1807                // terminator of a loop should be TerminatorKind::FalseUnwind
1808                && let TerminatorKind::FalseUnwind { .. } = terminator.kind
1809            {
1810                return Some(location);
1811            }
1812        }
1813        None
1814    }
1815
1816    /// Access to the SCC constraint graph.
1817    /// This can be used to quickly under-approximate the regions which are equal to each other
1818    /// and their relative orderings.
1819    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.
1820    pub fn constraint_sccs(&self) -> &ConstraintSccs {
1821        &self.constraint_sccs
1822    }
1823
1824    /// Returns the representative `RegionVid` for a given SCC.
1825    /// See `RegionTracker` for how a region variable ID is chosen.
1826    ///
1827    /// It is a hacky way to manage checking regions for equality,
1828    /// since we can 'canonicalize' each region to the representative
1829    /// of its SCC and be sure that -- if they have the same repr --
1830    /// they *must* be equal (though not having the same repr does not
1831    /// mean they are unequal).
1832    fn scc_representative(&self, scc: ConstraintSccIndex) -> RegionVid {
1833        self.scc_annotations[scc].representative.rvid()
1834    }
1835
1836    pub(crate) fn liveness_constraints(&self) -> &LivenessValues {
1837        &self.liveness_constraints
1838    }
1839
1840    /// When using `-Zpolonius=next`, records the given live loans for the loan scopes and active
1841    /// loans dataflow computations.
1842    pub(crate) fn record_live_loans(&mut self, live_loans: LiveLoans) {
1843        self.liveness_constraints.record_live_loans(live_loans);
1844    }
1845
1846    /// Returns whether the `loan_idx` is live at the given `location`: whether its issuing
1847    /// region is contained within the type of a variable that is live at this point.
1848    /// Note: for now, the sets of live loans is only available when using `-Zpolonius=next`.
1849    pub(crate) fn is_loan_live_at(&self, loan_idx: BorrowIndex, location: Location) -> bool {
1850        let point = self.liveness_constraints.point_from_location(location);
1851        self.liveness_constraints.is_loan_live_at(loan_idx, point)
1852    }
1853}
1854
1855#[derive(Clone, Debug)]
1856pub(crate) struct BlameConstraint<'tcx> {
1857    pub category: ConstraintCategory<'tcx>,
1858    pub from_closure: bool,
1859    pub cause: ObligationCause<'tcx>,
1860    pub variance_info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
1861}