rustc_borrowck/region_infer/
mod.rs

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