rustc_borrowck/region_infer/
mod.rs

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