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