compiler/rustc_borrowck/src/region_infer/mod.rs RUST 1,934 lines View on github.com → Search inside
1use std::collections::VecDeque;2use std::fmt;3use std::rc::Rc;45use rustc_data_structures::frozen::Frozen;6use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};7use rustc_data_structures::graph::scc::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, VerifyBound, VerifyIfEq};13use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};14use rustc_middle::bug;15use rustc_middle::mir::{16    AnnotationSource, BasicBlock, Body, ConstraintCategory, Local, Location, ReturnConstraint,17    TerminatorKind,18};19use rustc_middle::traits::{ObligationCause, ObligationCauseCode};20use rustc_middle::ty::{21    self, RegionExt, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, fold_regions,22};23use rustc_mir_dataflow::points::DenseLocationMap;24use rustc_span::hygiene::DesugaringKind;25use rustc_span::{DUMMY_SP, Span};26use tracing::{Level, debug, enabled, instrument, trace};2728use crate::constraints::graph::NormalConstraintGraph;29use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet};30use crate::dataflow::BorrowIndex;31use crate::diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo};32use crate::handle_placeholders::{LoweredConstraints, RegionTracker};33use crate::polonius::LiveLoans;34use crate::polonius::legacy::PoloniusOutput;35use crate::region_infer::values::{LivenessValues, RegionElement, RegionValues};36use crate::type_check::Locations;37use crate::type_check::free_region_relations::UniversalRegionRelations;38use crate::universal_regions::UniversalRegions;39use crate::{40    BorrowckInferCtxt, ClosureOutlivesRequirement, ClosureOutlivesSubject,41    ClosureOutlivesSubjectTy, ClosureRegionRequirements,42};4344mod dump_mir;45mod graphviz;46pub(crate) mod opaque_types;47mod reverse_sccs;4849pub(crate) mod values;5051/// The representative region variable for an SCC, tagged by its origin.52/// We prefer placeholders over existentially quantified variables, otherwise53/// it's the one with the smallest Region Variable ID. In other words,54/// the order of this enumeration really matters!55#[derive(Copy, Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]56pub(crate) enum Representative {57    FreeRegion(RegionVid),58    Placeholder(RegionVid),59    Existential(RegionVid),60}6162impl Representative {63    pub(crate) fn rvid(self) -> RegionVid {64        match self {65            Representative::FreeRegion(region_vid)66            | Representative::Placeholder(region_vid)67            | Representative::Existential(region_vid) => region_vid,68        }69    }7071    pub(crate) fn new(r: RegionVid, definition: &RegionDefinition<'_>) -> Self {72        match definition.origin {73            NllRegionVariableOrigin::FreeRegion => Representative::FreeRegion(r),74            NllRegionVariableOrigin::Placeholder(_) => Representative::Placeholder(r),75            NllRegionVariableOrigin::Existential { .. } => Representative::Existential(r),76        }77    }78}7980pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex>;8182pub struct RegionInferenceContext<'tcx> {83    /// Contains the definition for every region variable. Region84    /// variables are identified by their index (`RegionVid`). The85    /// definition contains information about where the region came86    /// from as well as its final inferred value.87    pub(crate) definitions: Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>,8889    /// The liveness constraints added to each region. For most90    /// regions, these start out empty and steadily grow, though for91    /// each universally quantified region R they start out containing92    /// the entire CFG and `end(R)`.93    liveness_constraints: LivenessValues,9495    /// The outlives constraints computed by the type-check.96    constraints: Frozen<OutlivesConstraintSet<'tcx>>,9798    /// The constraint-set, but in graph form, making it easy to traverse99    /// the constraints adjacent to a particular region. Used to construct100    /// the SCC (see `constraint_sccs`) and for error reporting.101    constraint_graph: Frozen<NormalConstraintGraph>,102103    /// The SCC computed from `constraints` and the constraint104    /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to105    /// compute the values of each region.106    constraint_sccs: ConstraintSccs,107108    scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,109110    /// Map universe indexes to information on why we created it.111    universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,112113    /// The final inferred values of the region variables; we compute114    /// one value per SCC. To get the value for any given *region*,115    /// you first find which scc it is a part of.116    scc_values: RegionValues<'tcx, ConstraintSccIndex>,117118    /// Type constraints that we check after solving.119    type_tests: Vec<TypeTest<'tcx>>,120121    /// Information about how the universally quantified regions in122    /// scope on this function relate to one another.123    universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,124}125126#[derive(Debug)]127pub(crate) struct RegionDefinition<'tcx> {128    /// What kind of variable is this -- a free region? existential129    /// variable? etc. (See the `NllRegionVariableOrigin` for more130    /// info.)131    pub(crate) origin: NllRegionVariableOrigin<'tcx>,132133    /// Which universe is this region variable defined in? This is134    /// most often `ty::UniverseIndex::ROOT`, but when we encounter135    /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create136    /// the variable for `'a` in a fresh universe that extends ROOT.137    pub(crate) universe: ty::UniverseIndex,138139    /// If this is 'static or an early-bound region, then this is140    /// `Some(X)` where `X` is the name of the region.141    pub(crate) external_name: Option<ty::Region<'tcx>>,142}143144/// N.B., the variants in `Cause` are intentionally ordered. Lower145/// values are preferred when it comes to error messages. Do not146/// reorder willy nilly.147#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]148pub(crate) enum Cause {149    /// point inserted because Local was live at the given Location150    LiveVar(Local, Location),151152    /// point inserted because Local was dropped at the given Location153    DropVar(Local, Location),154}155156/// A "type test" corresponds to an outlives constraint between a type157/// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are158/// translated from the `Verify` region constraints in the ordinary159/// inference context.160///161/// These sorts of constraints are handled differently than ordinary162/// constraints, at least at present. During type checking, the163/// `InferCtxt::process_registered_region_obligations` method will164/// attempt to convert a type test like `T: 'x` into an ordinary165/// outlives constraint when possible (for example, `&'a T: 'b` will166/// be converted into `'a: 'b` and registered as a `Constraint`).167///168/// In some cases, however, there are outlives relationships that are169/// not converted into a region constraint, but rather into one of170/// these "type tests". The distinction is that a type test does not171/// influence the inference result, but instead just examines the172/// values that we ultimately inferred for each region variable and173/// checks that they meet certain extra criteria. If not, an error174/// can be issued.175///176/// One reason for this is that these type tests typically boil down177/// to a check like `'a: 'x` where `'a` is a universally quantified178/// region -- and therefore not one whose value is really meant to be179/// *inferred*, precisely (this is not always the case: one can have a180/// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an181/// inference variable). Another reason is that these type tests can182/// involve *disjunction* -- that is, they can be satisfied in more183/// than one way.184///185/// For more information about this translation, see186/// `InferCtxt::process_registered_region_obligations` and187/// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.188#[derive(Clone)]189pub(crate) struct TypeTest<'tcx> {190    /// The type `T` that must outlive the region.191    pub generic_kind: GenericKind<'tcx>,192193    /// The region `'x` that the type must outlive.194    pub lower_bound: RegionVid,195196    /// The span to blame.197    pub span: Span,198199    /// A test which, if met by the region `'x`, proves that this type200    /// constraint is satisfied.201    pub verify_bound: VerifyBound<'tcx>,202}203204impl fmt::Debug for TypeTest<'_> {205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {206        fn fmt_bound(207            f: &mut fmt::Formatter<'_>,208            generic_kind: GenericKind<'_>,209            lower: RegionVid,210            bound: &VerifyBound<'_>,211        ) -> fmt::Result {212            let fmt_bounds =213                |f: &mut fmt::Formatter<'_>, bounds: &[VerifyBound<'_>]| -> fmt::Result {214                    let mut it = bounds.iter().peekable();215                    while let Some(bound) = it.next() {216                        fmt_bound(f, generic_kind, lower, bound)?;217                        if it.peek().is_some() {218                            write!(f, ", ")?219                        }220                    }221                    Ok(())222                };223            match bound {224                VerifyBound::IfEq(binder) => write!(f, "{:?} == {:?}", generic_kind, binder),225                VerifyBound::OutlivedBy(region) => write!(f, "{region:?}: {lower:?}"),226                VerifyBound::AnyBound(verify_bounds) => {227                    write!(f, "Any[")?;228                    fmt_bounds(f, verify_bounds)?;229                    write!(f, "]")230                }231                VerifyBound::AllBounds(verify_bounds) => {232                    write!(f, "All[")?;233                    fmt_bounds(f, verify_bounds)?;234                    write!(f, "]")235                }236                VerifyBound::IsEmpty => write!(f, "Empty({lower:?})"),237            }238        }239        write!(f, "TypeTest from {:?}[", self.span)?;240        fmt_bound(f, self.generic_kind, self.lower_bound, &self.verify_bound)?;241        write!(f, "] ⊢ {:?}: {:?}", self.generic_kind, self.lower_bound)242    }243}244245/// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure246/// environment). If we can't, it is an error.247#[derive(Clone, Copy, Debug, Eq, PartialEq)]248enum RegionRelationCheckResult {249    Ok,250    Propagated,251    Error,252}253254#[derive(Clone, PartialEq, Eq, Debug)]255enum Trace<'a, 'tcx> {256    StartRegion,257    FromGraph(&'a OutlivesConstraint<'tcx>),258    FromStatic(RegionVid),259    NotVisited,260}261262#[instrument(skip(infcx, sccs), level = "debug")]263fn sccs_info<'tcx>(infcx: &BorrowckInferCtxt<'tcx>, sccs: &ConstraintSccs) {264    use crate::renumber::RegionCtxt;265266    let var_to_origin = infcx.reg_var_to_origin.borrow();267268    let mut var_to_origin_sorted = var_to_origin.clone().into_iter().collect::<Vec<_>>();269    var_to_origin_sorted.sort_by_key(|vto| vto.0);270271    if enabled!(Level::DEBUG) {272        let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string();273        for (reg_var, origin) in var_to_origin_sorted.into_iter() {274            reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n"));275        }276        debug!("{}", reg_vars_to_origins_str);277    }278279    let num_components = sccs.num_sccs();280    let mut components = vec![FxIndexSet::default(); num_components];281282    for (reg_var, scc_idx) in sccs.scc_indices().iter_enumerated() {283        let origin = var_to_origin.get(&reg_var).unwrap_or(&RegionCtxt::Unknown);284        components[scc_idx.as_usize()].insert((reg_var, *origin));285    }286287    if enabled!(Level::DEBUG) {288        let mut components_str = "strongly connected components:".to_string();289        for (scc_idx, reg_vars_origins) in components.iter().enumerate() {290            let regions_info = reg_vars_origins.clone().into_iter().collect::<Vec<_>>();291            components_str.push_str(&format!(292                "{:?}: {:?},\n)",293                ConstraintSccIndex::from_usize(scc_idx),294                regions_info,295            ))296        }297        debug!("{}", components_str);298    }299300    // calculate the best representative for each component301    let components_representatives = components302        .into_iter()303        .enumerate()304        .map(|(scc_idx, region_ctxts)| {305            let repr = region_ctxts306                .into_iter()307                .map(|reg_var_origin| reg_var_origin.1)308                .max_by(|x, y| x.preference_value().cmp(&y.preference_value()))309                .unwrap();310311            (ConstraintSccIndex::from_usize(scc_idx), repr)312        })313        .collect::<FxIndexMap<_, _>>();314315    let mut scc_node_to_edges = FxIndexMap::default();316    for (scc_idx, repr) in components_representatives.iter() {317        let edge_representatives = sccs318            .successors(*scc_idx)319            .iter()320            .map(|scc_idx| components_representatives[scc_idx])321            .collect::<Vec<_>>();322        scc_node_to_edges.insert((scc_idx, repr), edge_representatives);323    }324325    debug!("SCC edges {:#?}", scc_node_to_edges);326}327328impl<'tcx> RegionInferenceContext<'tcx> {329    /// Creates a new region inference context with a total of330    /// `num_region_variables` valid inference variables; the first N331    /// of those will be constant regions representing the free332    /// regions defined in `universal_regions`.333    ///334    /// The `outlives_constraints` and `type_tests` are an initial set335    /// of constraints produced by the MIR type check.336    pub(crate) fn new(337        infcx: &BorrowckInferCtxt<'tcx>,338        lowered_constraints: LoweredConstraints<'tcx>,339        universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,340        location_map: Rc<DenseLocationMap>,341    ) -> Self {342        let universal_regions = &universal_region_relations.universal_regions;343344        let LoweredConstraints {345            constraint_sccs,346            definitions,347            outlives_constraints,348            scc_annotations,349            type_tests,350            mut liveness_constraints,351            universe_causes,352            placeholder_indices,353        } = lowered_constraints;354355        debug!("universal_regions: {:#?}", universal_region_relations.universal_regions);356        debug!("outlives constraints: {:#?}", outlives_constraints);357        debug!("placeholder_indices: {:#?}", placeholder_indices);358        debug!("type tests: {:#?}", type_tests);359360        let constraint_graph = Frozen::freeze(outlives_constraints.graph(definitions.len()));361362        if cfg!(debug_assertions) {363            sccs_info(infcx, &constraint_sccs);364        }365366        let mut scc_values =367            RegionValues::new(location_map, universal_regions.len(), placeholder_indices);368369        // Initializes the region variables with their initial live points.370        for (region, definition) in definitions.iter_enumerated() {371            let scc = constraint_sccs.scc(region);372373            // For each universally quantified region (lifetime parameter). The374            // first N variables always correspond to the regions appearing in the375            // function signature (both named and anonymous) and in where-clauses.376            match definition.origin {377                // For each free, universally quantified region X:378                NllRegionVariableOrigin::FreeRegion => {379                    // Add all nodes in the CFG to liveness constraints380                    liveness_constraints.add_all_points(region);381382                    // Add `end(X)` into the set for X.383                    scc_values.add_free_region(scc, region);384                }385386                NllRegionVariableOrigin::Placeholder(placeholder) => {387                    scc_values.add_placeholder(scc, placeholder);388                }389390                NllRegionVariableOrigin::Existential { .. } => {391                    // For existential, regions, nothing to do.392                }393            }394395            // Initially copy the liveness constraints of any region that396            // has them, setting `scc_values[scc(region)] |= liveness_constraints[region]`.397            //398            // These values will later be propagated during [`Self::propagate_constraints()`].399            // The values include any live-at-all-points constraints added above400            // for free regions.401            if let Some(liveness) = liveness_constraints.point_liveness(region) {402                scc_values.merge_liveness(scc, liveness)403            }404        }405406        Self {407            definitions,408            liveness_constraints,409            constraints: outlives_constraints,410            constraint_graph,411            constraint_sccs,412            scc_annotations,413            universe_causes,414            scc_values,415            type_tests,416            universal_region_relations,417        }418    }419420    /// Returns an iterator over all the region indices.421    pub(crate) fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {422        self.definitions.indices()423    }424425    /// Given a universal region in scope on the MIR, returns the426    /// corresponding index.427    ///428    /// Panics if `r` is not a registered universal region, most notably429    /// if it is a placeholder. Handling placeholders requires access to the430    /// `MirTypeckRegionConstraints`.431    pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {432        self.universal_regions().to_region_vid(r)433    }434435    /// Returns an iterator over all the outlives constraints.436    pub(crate) fn outlives_constraints(&self) -> impl Iterator<Item = OutlivesConstraint<'tcx>> {437        self.constraints.outlives().iter().copied()438    }439440    /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.441    pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {442        self.universal_regions().annotate(tcx, err)443    }444445    /// Returns `true` if the region `r` contains the point `p`.446    ///447    /// Panics if called before `solve()` executes,448    pub(crate) fn region_contains_point(&self, r: RegionVid, p: Location) -> bool {449        let scc = self.constraint_sccs.scc(r);450        self.scc_values.contains_point(scc, p)451    }452453    /// Returns the lowest statement index in `start..=end` which is not contained by `r`.454    ///455    /// Panics if called before `solve()` executes.456    pub(crate) fn first_non_contained_inclusive(457        &self,458        r: RegionVid,459        block: BasicBlock,460        start: usize,461        end: usize,462    ) -> Option<usize> {463        let scc = self.constraint_sccs.scc(r);464        self.scc_values.first_non_contained_inclusive(scc, block, start, end)465    }466467    /// Returns access to the value of `r` for debugging purposes.468    pub(crate) fn region_value_str(&self, r: RegionVid) -> String {469        let scc = self.constraint_sccs.scc(r);470        self.scc_values.region_value_str(scc)471    }472473    pub(crate) fn placeholders_contained_in(474        &self,475        r: RegionVid,476    ) -> impl Iterator<Item = ty::PlaceholderRegion<'tcx>> {477        let scc = self.constraint_sccs.scc(r);478        self.scc_values.placeholders_contained_in(scc)479    }480481    /// Performs region inference and report errors if we see any482    /// unsatisfiable constraints. If this is a closure, returns the483    /// region requirements to propagate to our creator, if any.484    #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]485    pub(super) fn solve(486        &mut self,487        infcx: &InferCtxt<'tcx>,488        body: &Body<'tcx>,489        polonius_output: Option<Box<PoloniusOutput>>,490    ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {491        let mir_def_id = body.source.def_id();492        self.propagate_constraints();493494        let mut errors_buffer = RegionErrors::new(infcx.tcx);495496        // If this is a nested body, we propagate unsatisfied497        // outlives constraints to the parent body instead of498        // eagerly erroing.499        let mut propagated_outlives_requirements =500            infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);501502        self.check_type_tests(infcx, propagated_outlives_requirements.as_mut(), &mut errors_buffer);503504        debug!(?errors_buffer);505        debug!(?propagated_outlives_requirements);506507        // In Polonius mode, the errors about missing universal region relations are in the output508        // and need to be emitted or propagated. Otherwise, we need to check whether the509        // constraints were too strong, and if so, emit or propagate those errors.510        if infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled() {511            self.check_polonius_subset_errors(512                propagated_outlives_requirements.as_mut(),513                &mut errors_buffer,514                polonius_output515                    .as_ref()516                    .expect("Polonius output is unavailable despite `-Z polonius`"),517            );518        } else {519            self.check_universal_regions(520                propagated_outlives_requirements.as_mut(),521                &mut errors_buffer,522            );523        }524525        debug!(?errors_buffer);526527        let propagated_outlives_requirements = propagated_outlives_requirements.unwrap_or_default();528529        if propagated_outlives_requirements.is_empty() {530            (None, errors_buffer)531        } else {532            let num_external_vids = self.universal_regions().num_global_and_external_regions();533            (534                Some(ClosureRegionRequirements {535                    num_external_vids,536                    outlives_requirements: propagated_outlives_requirements,537                }),538                errors_buffer,539            )540        }541    }542543    /// Propagate the region constraints: this will grow the values544    /// for each region variable until all the constraints are545    /// satisfied. Note that some values may grow **too** large to be546    /// feasible, but we check this later.547    #[instrument(skip(self), level = "debug")]548    fn propagate_constraints(&mut self) {549        debug!("constraints={:#?}", {550            let mut constraints: Vec<_> = self.outlives_constraints().collect();551            constraints.sort_by_key(|c| (c.sup, c.sub));552            constraints553                .into_iter()554                .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))555                .collect::<Vec<_>>()556        });557558        // To propagate constraints, we walk the DAG induced by the559        // SCC. For each SCC `A`, we visit its successors and compute560        // their values, then we union all those values to get our561        // own. This one-shot approach works because iteration is in562        // dependency order. I.e. a chain A: B: C will visit C, B, A.563        for scc_a in self.constraint_sccs.all_sccs() {564            // Walk each SCC `B` such that `A: B`...565            for &scc_b in self.constraint_sccs.successors(scc_a) {566                debug!(?scc_b);567                self.scc_values.add_region(scc_a, scc_b);568            }569        }570    }571572    /// Returns `true` if all the placeholders in the value of `scc_b` are nameable573    /// in `scc_a`. Used during constraint propagation, and only once574    /// the value of `scc_b` has been computed.575    fn can_name_all_placeholders(576        &self,577        scc_a: ConstraintSccIndex,578        scc_b: ConstraintSccIndex,579    ) -> bool {580        self.scc_annotations[scc_a].can_name_all_placeholders(self.scc_annotations[scc_b])581    }582583    /// Once regions have been propagated, this method is used to see584    /// whether the "type tests" produced by typeck were satisfied;585    /// type tests encode type-outlives relationships like `T:586    /// 'a`. See `TypeTest` for more details.587    fn check_type_tests(588        &self,589        infcx: &InferCtxt<'tcx>,590        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,591        errors_buffer: &mut RegionErrors<'tcx>,592    ) {593        let tcx = infcx.tcx;594595        // Sometimes we register equivalent type-tests that would596        // result in basically the exact same error being reported to597        // the user. Avoid that.598        let mut deduplicate_errors = FxIndexSet::default();599600        for type_test in &self.type_tests {601            debug!("check_type_test: {:?}", type_test);602603            let generic_ty = type_test.generic_kind.to_ty(tcx);604            if self.eval_verify_bound(605                infcx,606                generic_ty,607                type_test.lower_bound,608                &type_test.verify_bound,609            ) {610                continue;611            }612613            if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements614                && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements)615            {616                continue;617            }618619            // Type-test failed. Report the error.620            let erased_generic_kind = infcx.tcx.erase_and_anonymize_regions(type_test.generic_kind);621622            // Skip duplicate-ish errors.623            if deduplicate_errors.insert((624                erased_generic_kind,625                type_test.lower_bound,626                type_test.span,627            )) {628                debug!(629                    "check_type_test: reporting error for erased_generic_kind={:?}, \630                     lower_bound_region={:?}, \631                     type_test.span={:?}",632                    erased_generic_kind, type_test.lower_bound, type_test.span,633                );634635                errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });636            }637        }638    }639640    /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot641    /// prove to be satisfied. If this is a closure, we will attempt to642    /// "promote" this type-test into our `ClosureRegionRequirements` and643    /// hence pass it up the creator. To do this, we have to phrase the644    /// type-test in terms of external free regions, as local free645    /// regions are not nameable by the closure's creator.646    ///647    /// Promotion works as follows: we first check that the type `T`648    /// contains only regions that the creator knows about. If this is649    /// true, then -- as a consequence -- we know that all regions in650    /// the type `T` are free regions that outlive the closure body. If651    /// false, then promotion fails.652    ///653    /// Once we've promoted T, we have to "promote" `'X` to some region654    /// that is "external" to the closure. Generally speaking, a region655    /// may be the union of some points in the closure body as well as656    /// various free lifetimes. We can ignore the points in the closure657    /// body: if the type T can be expressed in terms of external regions,658    /// we know it outlives the points in the closure body. That659    /// just leaves the free regions.660    ///661    /// The idea then is to lower the `T: 'X` constraint into multiple662    /// bounds -- e.g., if `'X` is the union of two free lifetimes,663    /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.664    #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]665    fn try_promote_type_test(666        &self,667        infcx: &InferCtxt<'tcx>,668        type_test: &TypeTest<'tcx>,669        propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,670    ) -> bool {671        let tcx = infcx.tcx;672        let TypeTest { generic_kind, lower_bound, span: blame_span, verify_bound: _ } = *type_test;673674        let generic_ty = generic_kind.to_ty(tcx);675        let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {676            return false;677        };678679        let r_scc = self.constraint_sccs.scc(lower_bound);680        debug!(681            "lower_bound = {:?} r_scc={:?} universe={:?}",682            lower_bound,683            r_scc,684            self.max_nameable_universe(r_scc)685        );686        // If the type test requires that `T: 'a` where `'a` is a687        // placeholder from another universe, that effectively requires688        // `T: 'static`, so we have to propagate that requirement.689        //690        // It doesn't matter *what* universe because the promoted `T` will691        // always be in the root universe.692        if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {693            debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);694            let static_r = self.universal_regions().fr_static;695            propagated_outlives_requirements.push(ClosureOutlivesRequirement {696                subject,697                outlived_free_region: static_r,698                blame_span,699                category: ConstraintCategory::Boring,700            });701702            // we can return here -- the code below might push add'l constraints703            // but they would all be weaker than this one.704            return true;705        }706707        // For each region outlived by lower_bound find a non-local,708        // universal region (it may be the same region) and add it to709        // `ClosureOutlivesRequirement`.710        let mut found_outlived_universal_region = false;711        for ur in self.scc_values.universal_regions_outlived_by(r_scc) {712            found_outlived_universal_region = true;713            debug!("universal_region_outlived_by ur={:?}", ur);714            let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);715            debug!(?non_local_ub);716717            // This is slightly too conservative. To show T: '1, given `'2: '1`718            // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to719            // avoid potential non-determinism we approximate this by requiring720            // T: '1 and T: '2.721            for upper_bound in non_local_ub {722                debug_assert!(self.universal_regions().is_universal_region(upper_bound));723                debug_assert!(!self.universal_regions().is_local_free_region(upper_bound));724725                let requirement = ClosureOutlivesRequirement {726                    subject,727                    outlived_free_region: upper_bound,728                    blame_span,729                    category: ConstraintCategory::Boring,730                };731                debug!(?requirement, "adding closure requirement");732                propagated_outlives_requirements.push(requirement);733            }734        }735        // If we succeed to promote the subject, i.e. it only contains non-local regions,736        // and fail to prove the type test inside of the closure, the `lower_bound` has to737        // also be at least as large as some universal region, as the type test is otherwise738        // trivial.739        assert!(found_outlived_universal_region);740        true741    }742743    /// When we promote a type test `T: 'r`, we have to replace all region744    /// variables in the type `T` with an equal universal region from the745    /// closure signature.746    /// This is not always possible, so this is a fallible process.747    #[instrument(level = "debug", skip(self, infcx), ret)]748    fn try_promote_type_test_subject(749        &self,750        infcx: &InferCtxt<'tcx>,751        ty: Ty<'tcx>,752    ) -> Option<ClosureOutlivesSubject<'tcx>> {753        let tcx = infcx.tcx;754        let mut failed = false;755        let ty = fold_regions(tcx, ty, |r, _depth| {756            let r_vid = self.to_region_vid(r);757            let r_scc = self.constraint_sccs.scc(r_vid);758759            // The challenge is this. We have some region variable `r`760            // whose value is a set of CFG points and universal761            // regions. We want to find if that set is *equivalent* to762            // any of the named regions found in the closure.763            // To do so, we simply check every candidate `u_r` for equality.764            self.scc_values765                .universal_regions_outlived_by(r_scc)766                .filter(|&u_r| !self.universal_regions().is_local_free_region(u_r))767                .find(|&u_r| self.eval_equal(u_r, r_vid))768                .map(|u_r| ty::Region::new_var(tcx, u_r))769                // In case we could not find a named region to map to,770                // we will return `None` below.771                .unwrap_or_else(|| {772                    failed = true;773                    r774                })775        });776777        debug!("try_promote_type_test_subject: folded ty = {:?}", ty);778779        // This will be true if we failed to promote some region.780        if failed {781            return None;782        }783784        Some(ClosureOutlivesSubject::Ty(ClosureOutlivesSubjectTy::bind(tcx, ty)))785    }786787    /// Like `universal_upper_bound`, but returns an approximation more suitable788    /// for diagnostics. If `r` contains multiple disjoint universal regions789    /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.790    /// This corresponds to picking named regions over unnamed regions791    /// (e.g. picking early-bound regions over a closure late-bound region).792    ///793    /// This means that the returned value may not be a true upper bound, since794    /// only 'static is known to outlive disjoint universal regions.795    /// Therefore, this method should only be used in diagnostic code,796    /// where displaying *some* named universal region is better than797    /// falling back to 'static.798    #[instrument(level = "debug", skip(self))]799    pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {800        debug!("{}", self.region_value_str(r));801802        // Find the smallest universal region that contains all other803        // universal regions within `region`.804        let mut lub = self.universal_regions().fr_fn_body;805        let r_scc = self.constraint_sccs.scc(r);806        let static_r = self.universal_regions().fr_static;807        for ur in self.scc_values.universal_regions_outlived_by(r_scc) {808            let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);809            debug!(?ur, ?lub, ?new_lub);810            // The upper bound of two non-static regions is static: this811            // means we know nothing about the relationship between these812            // two regions. Pick a 'better' one to use when constructing813            // a diagnostic814            if ur != static_r && lub != static_r && new_lub == static_r {815                // Prefer the region with an `external_name` - this816                // indicates that the region is early-bound, so working with817                // it can produce a nicer error.818                if self.region_definition(ur).external_name.is_some() {819                    lub = ur;820                } else if self.region_definition(lub).external_name.is_some() {821                    // Leave lub unchanged822                } else {823                    // If we get here, we don't have any reason to prefer824                    // one region over the other. Just pick the825                    // one with the lower index for now.826                    lub = std::cmp::min(ur, lub);827                }828            } else {829                lub = new_lub;830            }831        }832833        debug!(?r, ?lub);834835        lub836    }837838    /// Tests if `test` is true when applied to `lower_bound` at839    /// `point`.840    fn eval_verify_bound(841        &self,842        infcx: &InferCtxt<'tcx>,843        generic_ty: Ty<'tcx>,844        lower_bound: RegionVid,845        verify_bound: &VerifyBound<'tcx>,846    ) -> bool {847        debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);848849        match verify_bound {850            VerifyBound::IfEq(verify_if_eq_b) => {851                self.eval_if_eq(infcx, generic_ty, lower_bound, *verify_if_eq_b)852            }853854            VerifyBound::IsEmpty => {855                let lower_bound_scc = self.constraint_sccs.scc(lower_bound);856                self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()857            }858859            VerifyBound::OutlivedBy(r) => {860                let r_vid = self.to_region_vid(*r);861                self.eval_outlives(r_vid, lower_bound)862            }863864            VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {865                self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)866            }),867868            VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {869                self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)870            }),871        }872    }873874    fn eval_if_eq(875        &self,876        infcx: &InferCtxt<'tcx>,877        generic_ty: Ty<'tcx>,878        lower_bound: RegionVid,879        verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,880    ) -> bool {881        let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);882        let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);883        match test_type_match::extract_verify_if_eq(infcx.tcx, &verify_if_eq_b, generic_ty) {884            Some(r) => {885                let r_vid = self.to_region_vid(r);886                self.eval_outlives(r_vid, lower_bound)887            }888            None => false,889        }890    }891892    /// This is a conservative normalization procedure. It takes every893    /// free region in `value` and replaces it with the894    /// "representative" of its SCC (see `scc_representatives` field).895    /// We are guaranteed that if two values normalize to the same896    /// thing, then they are equal; this is a conservative check in897    /// that they could still be equal even if they normalize to898    /// different results. (For example, there might be two regions899    /// with the same value that are not in the same SCC).900    ///901    /// N.B., this is not an ideal approach and I would like to revisit902    /// it. However, it works pretty well in practice. In particular,903    /// this is needed to deal with projection outlives bounds like904    ///905    /// ```text906    /// <T as Foo<'0>>::Item: '1907    /// ```908    ///909    /// In particular, this routine winds up being important when910    /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the911    /// environment. In this case, if we can show that `'0 == 'a`,912    /// and that `'b: '1`, then we know that the clause is913    /// satisfied. In such cases, particularly due to limitations of914    /// the trait solver =), we usually wind up with a where-clause like915    /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as916    /// a constraint, and thus ensures that they are in the same SCC.917    ///918    /// So why can't we do a more correct routine? Well, we could919    /// *almost* use the `relate_tys` code, but the way it is920    /// currently setup it creates inference variables to deal with921    /// higher-ranked things and so forth, and right now the inference922    /// context is not permitted to make more inference variables. So923    /// we use this kind of hacky solution.924    fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T925    where926        T: TypeFoldable<TyCtxt<'tcx>>,927    {928        fold_regions(tcx, value, |r, _db| {929            let vid = self.to_region_vid(r);930            let scc = self.constraint_sccs.scc(vid);931            let repr = self.scc_representative(scc);932            ty::Region::new_var(tcx, repr)933        })934    }935936    /// Evaluate whether `sup_region == sub_region`.937    ///938    /// Panics if called before `solve()` executes,939    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.940    pub fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {941        self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)942    }943944    /// Evaluate whether `sup_region: sub_region`.945    ///946    /// Panics if called before `solve()` executes,947    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.948    #[instrument(skip(self), level = "debug", ret)]949    pub fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {950        debug!(951            "sup_region's value = {:?} universal={:?}",952            self.region_value_str(sup_region),953            self.universal_regions().is_universal_region(sup_region),954        );955        debug!(956            "sub_region's value = {:?} universal={:?}",957            self.region_value_str(sub_region),958            self.universal_regions().is_universal_region(sub_region),959        );960961        let sub_region_scc = self.constraint_sccs.scc(sub_region);962        let sup_region_scc = self.constraint_sccs.scc(sup_region);963964        if sub_region_scc == sup_region_scc {965            debug!("{sup_region:?}: {sub_region:?} holds trivially; they are in the same SCC");966            return true;967        }968969        let fr_static = self.universal_regions().fr_static;970971        // If we are checking that `'sup: 'sub`, and `'sub` contains972        // some placeholder that `'sup` cannot name, then this is only973        // true if `'sup` outlives static.974        //975        // Avoid infinite recursion if `sub_region` is already `'static`976        if sub_region != fr_static977            && !self.can_name_all_placeholders(sup_region_scc, sub_region_scc)978        {979            debug!(980                "sub universe `{sub_region_scc:?}` is not nameable \981                by super `{sup_region_scc:?}`, promoting to static",982            );983984            return self.eval_outlives(sup_region, fr_static);985        }986987        // Both the `sub_region` and `sup_region` consist of the union988        // of some number of universal regions (along with the union989        // of various points in the CFG; ignore those points for990        // now). Therefore, the sup-region outlives the sub-region if,991        // for each universal region R1 in the sub-region, there992        // exists some region R2 in the sup-region that outlives R1.993        let universal_outlives =994            self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {995                self.scc_values996                    .universal_regions_outlived_by(sup_region_scc)997                    .any(|r2| self.universal_region_relations.outlives(r2, r1))998            });9991000        if !universal_outlives {1001            debug!("sub region contains a universal region not present in super");1002            return false;1003        }10041005        // Now we have to compare all the points in the sub region and make1006        // sure they exist in the sup region.10071008        if self.universal_regions().is_universal_region(sup_region) {1009            // Micro-opt: universal regions contain all points.1010            debug!("super is universal and hence contains all points");1011            return true;1012        }10131014        debug!("comparison between points in sup/sub");10151016        self.scc_values.contains_points(sup_region_scc, sub_region_scc)1017    }10181019    /// Once regions have been propagated, this method is used to see1020    /// whether any of the constraints were too strong. In particular,1021    /// we want to check for a case where a universally quantified1022    /// region exceeded its bounds. Consider:1023    /// ```compile_fail1024    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }1025    /// ```1026    /// In this case, returning `x` requires `&'a u32 <: &'b u32`1027    /// and hence we establish (transitively) a constraint that1028    /// `'a: 'b`. The `propagate_constraints` code above will1029    /// therefore add `end('a)` into the region for `'b` -- but we1030    /// have no evidence that `'b` outlives `'a`, so we want to report1031    /// an error.1032    ///1033    /// If `propagated_outlives_requirements` is `Some`, then we will1034    /// push unsatisfied obligations into there. Otherwise, we'll1035    /// report them as errors.1036    fn check_universal_regions(1037        &self,1038        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1039        errors_buffer: &mut RegionErrors<'tcx>,1040    ) {1041        for (fr, fr_definition) in self.definitions.iter_enumerated() {1042            debug!(?fr, ?fr_definition);1043            match fr_definition.origin {1044                NllRegionVariableOrigin::FreeRegion => {1045                    // Go through each of the universal regions `fr` and check that1046                    // they did not grow too large, accumulating any requirements1047                    // for our caller into the `outlives_requirements` vector.1048                    self.check_universal_region(1049                        fr,1050                        &mut propagated_outlives_requirements,1051                        errors_buffer,1052                    );1053                }10541055                NllRegionVariableOrigin::Placeholder(placeholder) => {1056                    self.check_bound_universal_region(fr, placeholder, errors_buffer);1057                }10581059                NllRegionVariableOrigin::Existential { .. } => {1060                    // nothing to check here1061                }1062            }1063        }1064    }10651066    /// Checks if Polonius has found any unexpected free region relations.1067    ///1068    /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent1069    /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`1070    /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL1071    /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.1072    ///1073    /// More details can be found in this blog post by Niko:1074    /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>1075    ///1076    /// In the canonical example1077    /// ```compile_fail1078    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }1079    /// ```1080    /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a1081    /// constraint that `'a: 'b`. It is an error that we have no evidence that this1082    /// constraint holds.1083    ///1084    /// If `propagated_outlives_requirements` is `Some`, then we will1085    /// push unsatisfied obligations into there. Otherwise, we'll1086    /// report them as errors.1087    fn check_polonius_subset_errors(1088        &self,1089        mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1090        errors_buffer: &mut RegionErrors<'tcx>,1091        polonius_output: &PoloniusOutput,1092    ) {1093        debug!(1094            "check_polonius_subset_errors: {} subset_errors",1095            polonius_output.subset_errors.len()1096        );10971098        // Similarly to `check_universal_regions`: a free region relation, which was not explicitly1099        // declared ("known") was found by Polonius, so emit an error, or propagate the1100        // requirements for our caller into the `propagated_outlives_requirements` vector.1101        //1102        // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the1103        // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with1104        // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",1105        // and the "superset origin" is the outlived "shorter free region".1106        //1107        // Note: Polonius will produce a subset error at every point where the unexpected1108        // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful1109        // for diagnostics in the future, e.g. to point more precisely at the key locations1110        // requiring this constraint to hold. However, the error and diagnostics code downstream1111        // expects that these errors are not duplicated (and that they are in a certain order).1112        // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or1113        // anonymous lifetimes for example, could give these names differently, while others like1114        // the outlives suggestions or the debug output from `#[rustc_regions]` would be1115        // duplicated. The polonius subset errors are deduplicated here, while keeping the1116        // CFG-location ordering.1117        // We can iterate the HashMap here because the result is sorted afterwards.1118        #[allow(rustc::potential_query_instability)]1119        let mut subset_errors: Vec<_> = polonius_output1120            .subset_errors1121            .iter()1122            .flat_map(|(_location, subset_errors)| subset_errors.iter())1123            .collect();1124        subset_errors.sort();1125        subset_errors.dedup();11261127        for &(longer_fr, shorter_fr) in subset_errors.into_iter() {1128            debug!(1129                "check_polonius_subset_errors: subset_error longer_fr={:?},\1130                 shorter_fr={:?}",1131                longer_fr, shorter_fr1132            );11331134            let propagated = self.try_propagate_universal_region_error(1135                longer_fr.into(),1136                shorter_fr.into(),1137                &mut propagated_outlives_requirements,1138            );1139            if propagated == RegionRelationCheckResult::Error {1140                errors_buffer.push(RegionErrorKind::RegionError {1141                    longer_fr: longer_fr.into(),1142                    shorter_fr: shorter_fr.into(),1143                    fr_origin: NllRegionVariableOrigin::FreeRegion,1144                    is_reported: true,1145                });1146            }1147        }11481149        // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has1150        // a more complete picture on how to separate this responsibility.1151        for (fr, fr_definition) in self.definitions.iter_enumerated() {1152            match fr_definition.origin {1153                NllRegionVariableOrigin::FreeRegion => {1154                    // handled by polonius above1155                }11561157                NllRegionVariableOrigin::Placeholder(placeholder) => {1158                    self.check_bound_universal_region(fr, placeholder, errors_buffer);1159                }11601161                NllRegionVariableOrigin::Existential { .. } => {1162                    // nothing to check here1163                }1164            }1165        }1166    }11671168    /// The largest universe of any region nameable from this SCC.1169    fn max_nameable_universe(&self, scc: ConstraintSccIndex) -> UniverseIndex {1170        self.scc_annotations[scc].max_nameable_universe()1171    }11721173    /// Checks the final value for the free region `fr` to see if it1174    /// grew too large. In particular, examine what `end(X)` points1175    /// wound up in `fr`'s final value; for each `end(X)` where `X !=1176    /// fr`, we want to check that `fr: X`. If not, that's either an1177    /// error, or something we have to propagate to our creator.1178    ///1179    /// Things that are to be propagated are accumulated into the1180    /// `outlives_requirements` vector.1181    #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]1182    fn check_universal_region(1183        &self,1184        longer_fr: RegionVid,1185        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1186        errors_buffer: &mut RegionErrors<'tcx>,1187    ) {1188        let longer_fr_scc = self.constraint_sccs.scc(longer_fr);11891190        // Because this free region must be in the ROOT universe, we1191        // know it cannot contain any bound universes.1192        assert!(self.max_nameable_universe(longer_fr_scc).is_root());11931194        // Only check all of the relations for the main representative of each1195        // SCC, otherwise just check that we outlive said representative. This1196        // reduces the number of redundant relations propagated out of1197        // closures.1198        // Note that the representative will be a universal region if there is1199        // one in this SCC, so we will always check the representative here.1200        let representative = self.scc_representative(longer_fr_scc);1201        if representative != longer_fr {1202            if let RegionRelationCheckResult::Error = self.check_universal_region_relation(1203                longer_fr,1204                representative,1205                propagated_outlives_requirements,1206            ) {1207                errors_buffer.push(RegionErrorKind::RegionError {1208                    longer_fr,1209                    shorter_fr: representative,1210                    fr_origin: NllRegionVariableOrigin::FreeRegion,1211                    is_reported: true,1212                });1213            }1214            return;1215        }12161217        // Find every region `o` such that `fr: o`1218        // (because `fr` includes `end(o)`).1219        let mut error_reported = false;1220        for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {1221            if let RegionRelationCheckResult::Error = self.check_universal_region_relation(1222                longer_fr,1223                shorter_fr,1224                propagated_outlives_requirements,1225            ) {1226                // We only report the first region error. Subsequent errors are hidden so as1227                // not to overwhelm the user, but we do record them so as to potentially print1228                // better diagnostics elsewhere...1229                errors_buffer.push(RegionErrorKind::RegionError {1230                    longer_fr,1231                    shorter_fr,1232                    fr_origin: NllRegionVariableOrigin::FreeRegion,1233                    is_reported: !error_reported,1234                });12351236                error_reported = true;1237            }1238        }1239    }12401241    /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate1242    /// the constraint outward (e.g. to a closure environment), but if that fails, there is an1243    /// error.1244    fn check_universal_region_relation(1245        &self,1246        longer_fr: RegionVid,1247        shorter_fr: RegionVid,1248        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1249    ) -> RegionRelationCheckResult {1250        // If it is known that `fr: o`, carry on.1251        if self.universal_region_relations.outlives(longer_fr, shorter_fr) {1252            RegionRelationCheckResult::Ok1253        } else {1254            // If we are not in a context where we can't propagate errors, or we1255            // could not shrink `fr` to something smaller, then just report an1256            // error.1257            //1258            // Note: in this case, we use the unapproximated regions to report the1259            // error. This gives better error messages in some cases.1260            self.try_propagate_universal_region_error(1261                longer_fr,1262                shorter_fr,1263                propagated_outlives_requirements,1264            )1265        }1266    }12671268    /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's1269    /// creator. If we cannot, then the caller should report an error to the user.1270    fn try_propagate_universal_region_error(1271        &self,1272        longer_fr: RegionVid,1273        shorter_fr: RegionVid,1274        propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1275    ) -> RegionRelationCheckResult {1276        if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {1277            // Shrink `longer_fr` until we find some non-local regions.1278            // We'll call them `longer_fr-` -- they are ever so slightly smaller than1279            // `longer_fr`.1280            let longer_fr_minus = self.universal_region_relations.non_local_lower_bounds(longer_fr);12811282            debug!("try_propagate_universal_region_error: fr_minus={:?}", longer_fr_minus);12831284            // If we don't find a any non-local regions, we should error out as there is nothing1285            // to propagate.1286            if longer_fr_minus.is_empty() {1287                return RegionRelationCheckResult::Error;1288            }12891290            let best_blame = self.best_blame_constraint(1291                longer_fr,1292                NllRegionVariableOrigin::FreeRegion,1293                shorter_fr,1294            );1295            let OutlivesConstraint { category, span, .. } = best_blame.constraint();12961297            // Grow `shorter_fr` until we find some non-local regions.1298            // We will always find at least one: `'static`. We'll call1299            // them `shorter_fr+` -- they're ever so slightly larger1300            // than `shorter_fr`.1301            let shorter_fr_plus =1302                self.universal_region_relations.non_local_upper_bounds(shorter_fr);1303            debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus);13041305            // We then create constraints `longer_fr-: shorter_fr+` that may or may not1306            // be propagated (see below).1307            let mut constraints = vec![];1308            for fr_minus in longer_fr_minus {1309                for shorter_fr_plus in &shorter_fr_plus {1310                    constraints.push((fr_minus, *shorter_fr_plus));1311                }1312            }13131314            // We only need to propagate at least one of the constraints for1315            // soundness. However, we want to avoid arbitrary choices here1316            // and currently don't support returning OR constraints.1317            //1318            // If any of the `shorter_fr+` regions are already outlived by `longer_fr-`,1319            // we propagate only those.1320            //1321            // Consider this example (`'b: 'a` == `a -> b`), where we try to propagate `'d: 'a`:1322            // a --> b --> d1323            //  \1324            //   \-> c1325            // Here, `shorter_fr+` of `'a` == `['b, 'c]`.1326            // Propagating `'d: 'b` is correct and should occur; `'d: 'c` is redundant because of1327            // `'d: 'b` and could reject valid code.1328            //1329            // So we filter the constraints to regions already outlived by `longer_fr-`, but if1330            // the filter yields an empty set, we fall back to the original one.1331            let subset: Vec<_> = constraints1332                .iter()1333                .filter(|&&(fr_minus, shorter_fr_plus)| {1334                    self.eval_outlives(fr_minus, shorter_fr_plus)1335                })1336                .copied()1337                .collect();1338            let propagated_constraints = if subset.is_empty() { constraints } else { subset };1339            debug!(1340                "try_propagate_universal_region_error: constraints={:?}",1341                propagated_constraints1342            );13431344            assert!(1345                !propagated_constraints.is_empty(),1346                "Expected at least one constraint to propagate here"1347            );13481349            for (fr_minus, fr_plus) in propagated_constraints {1350                // Push the constraint `long_fr-: shorter_fr+`1351                propagated_outlives_requirements.push(ClosureOutlivesRequirement {1352                    subject: ClosureOutlivesSubject::Region(fr_minus),1353                    outlived_free_region: fr_plus,1354                    blame_span: *span,1355                    category: *category,1356                });1357            }1358            return RegionRelationCheckResult::Propagated;1359        }13601361        RegionRelationCheckResult::Error1362    }13631364    fn check_bound_universal_region(1365        &self,1366        longer_fr: RegionVid,1367        placeholder: ty::PlaceholderRegion<'tcx>,1368        errors_buffer: &mut RegionErrors<'tcx>,1369    ) {1370        debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);13711372        let longer_fr_scc = self.constraint_sccs.scc(longer_fr);1373        debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);13741375        // If we have some bound universal region `'a`, then the only1376        // elements it can contain is itself -- we don't know anything1377        // else about it!1378        if let Some(error_element) = self1379            .scc_values1380            .elements_contained_in(longer_fr_scc)1381            .find(|e| *e != RegionElement::PlaceholderRegion(placeholder))1382        {1383            let illegally_outlived_r = self.region_from_element(longer_fr, &error_element);1384            // Stop after the first error, it gets too noisy otherwise, and does not provide more information.1385            errors_buffer.push(RegionErrorKind::PlaceholderOutlivesIllegalRegion {1386                longer_fr,1387                illegally_outlived_r,1388            });1389        } else {1390            debug!("check_bound_universal_region: all bounds satisfied");1391        }1392    }13931394    pub(crate) fn constraint_path_between_regions(1395        &self,1396        from_region: RegionVid,1397        to_region: RegionVid,1398    ) -> Option<Vec<OutlivesConstraint<'tcx>>> {1399        if from_region == to_region {1400            bug!("Tried to find a path between {from_region:?} and itself!");1401        }1402        self.constraint_path_to(from_region, |to| to == to_region, true).map(|o| o.0)1403    }14041405    /// Walks the graph of constraints (where `'a: 'b` is considered1406    /// an edge `'a -> 'b`) to find a path from `from_region` to1407    /// `to_region`.1408    ///1409    /// Returns: a series of constraints as well as the region `R`1410    /// that passed the target test.1411    /// If `include_static_outlives_all` is `true`, then the synthetic1412    /// outlives constraints `'static -> a` for every region `a` are1413    /// considered in the search, otherwise they are ignored.1414    #[instrument(skip(self, target_test), ret)]1415    pub(crate) fn constraint_path_to(1416        &self,1417        from_region: RegionVid,1418        target_test: impl Fn(RegionVid) -> bool,1419        include_placeholder_static: bool,1420    ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {1421        self.find_constraint_path_between_regions_inner(1422            true,1423            from_region,1424            &target_test,1425            include_placeholder_static,1426        )1427        .or_else(|| {1428            self.find_constraint_path_between_regions_inner(1429                false,1430                from_region,1431                &target_test,1432                include_placeholder_static,1433            )1434        })1435    }14361437    /// The constraints we get from equating the hidden type of each use of an opaque1438    /// with its final hidden type may end up getting preferred over other, potentially1439    /// longer constraint paths.1440    ///1441    /// Given that we compute the final hidden type by relying on this existing constraint1442    /// path, this can easily end up hiding the actual reason for why we require these regions1443    /// to be equal.1444    ///1445    /// To handle this, we first look at the path while ignoring these constraints and then1446    /// retry while considering them. This is not perfect, as the `from_region` may have already1447    /// been partially related to its argument region, so while we rely on a member constraint1448    /// to get a complete path, the most relevant step of that path already existed before then.1449    fn find_constraint_path_between_regions_inner(1450        &self,1451        ignore_opaque_type_constraints: bool,1452        from_region: RegionVid,1453        target_test: impl Fn(RegionVid) -> bool,1454        include_placeholder_static: bool,1455    ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {1456        let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);1457        context[from_region] = Trace::StartRegion;14581459        let fr_static = self.universal_regions().fr_static;14601461        // Use a deque so that we do a breadth-first search. We will1462        // stop at the first match, which ought to be the shortest1463        // path (fewest constraints).1464        let mut deque = VecDeque::new();1465        deque.push_back(from_region);14661467        while let Some(r) = deque.pop_front() {1468            debug!(1469                "constraint_path_to: from_region={:?} r={:?} value={}",1470                from_region,1471                r,1472                self.region_value_str(r),1473            );14741475            // Check if we reached the region we were looking for. If so,1476            // we can reconstruct the path that led to it and return it.1477            if target_test(r) {1478                let mut result = vec![];1479                let mut p = r;1480                // This loop is cold and runs at the end, which is why we delay1481                // `OutlivesConstraint` construction until now.1482                loop {1483                    match context[p] {1484                        Trace::FromGraph(c) => {1485                            p = c.sup;1486                            result.push(*c);1487                        }14881489                        Trace::FromStatic(sub) => {1490                            let c = OutlivesConstraint {1491                                sup: fr_static,1492                                sub,1493                                locations: Locations::All(DUMMY_SP),1494                                span: DUMMY_SP,1495                                category: ConstraintCategory::Internal,1496                                variance_info: ty::VarianceDiagInfo::default(),1497                                from_closure: false,1498                            };1499                            p = c.sup;1500                            result.push(c);1501                        }15021503                        Trace::StartRegion => {1504                            result.reverse();1505                            return Some((result, r));1506                        }15071508                        Trace::NotVisited => {1509                            bug!("found unvisited region {:?} on path to {:?}", p, r)1510                        }1511                    }1512                }1513            }15141515            // Otherwise, walk over the outgoing constraints and1516            // enqueue any regions we find, keeping track of how we1517            // reached them.15181519            // A constraint like `'r: 'x` can come from our constraint1520            // graph.15211522            // Always inline this closure because it can be hot.1523            let mut handle_trace = #[inline(always)]1524            |sub, trace| {1525                if let Trace::NotVisited = context[sub] {1526                    context[sub] = trace;1527                    deque.push_back(sub);1528                }1529            };15301531            // If this is the `'static` region and the graph's direction is normal, then set up the1532            // Edges iterator to return all regions (#53178).1533            if r == fr_static && self.constraint_graph.is_normal() {1534                for sub in self.constraint_graph.outgoing_edges_from_static() {1535                    handle_trace(sub, Trace::FromStatic(sub));1536                }1537            } else {1538                let edges = self.constraint_graph.outgoing_edges_from_graph(r, &self.constraints);1539                // This loop can be hot.1540                for constraint in edges {1541                    match constraint.category {1542                        ConstraintCategory::OutlivesUnnameablePlaceholder(_)1543                            if !include_placeholder_static =>1544                        {1545                            debug!("Ignoring illegal placeholder constraint: {constraint:?}");1546                            continue;1547                        }1548                        ConstraintCategory::OpaqueType if ignore_opaque_type_constraints => {1549                            debug!("Ignoring member constraint: {constraint:?}");1550                            continue;1551                        }1552                        _ => {}1553                    }15541555                    debug_assert_eq!(constraint.sup, r);1556                    handle_trace(constraint.sub, Trace::FromGraph(constraint));1557                }1558            }1559        }15601561        None1562    }15631564    /// Finds some region R such that `fr1: R` and `R` is live at `location`.1565    #[instrument(skip(self), level = "trace", ret)]1566    pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, location: Location) -> RegionVid {1567        trace!(scc = ?self.constraint_sccs.scc(fr1));1568        trace!(universe = ?self.max_nameable_universe(self.constraint_sccs.scc(fr1)));1569        self.constraint_path_to(fr1, |r| {1570            trace!(?r, liveness_constraints=?self.liveness_constraints.pretty_print_live_points(r));1571            self.liveness_constraints.is_live_at(r, location)1572        }, true).unwrap().11573    }15741575    /// Get the region outlived by `longer_fr` and live at `element`.1576    fn region_from_element(1577        &self,1578        longer_fr: RegionVid,1579        element: &RegionElement<'tcx>,1580    ) -> RegionVid {1581        match *element {1582            RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),1583            RegionElement::RootUniversalRegion(r) => r,1584            RegionElement::PlaceholderRegion(error_placeholder) => self1585                .definitions1586                .iter_enumerated()1587                .find_map(|(r, definition)| match definition.origin {1588                    NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),1589                    _ => None,1590                })1591                .unwrap(),1592        }1593    }15941595    /// Get the region definition of `r`.1596    pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {1597        &self.definitions[r]1598    }15991600    /// Check if the SCC of `r` contains `upper`, a free region.1601    pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {1602        let r_scc = self.constraint_sccs.scc(r);1603        self.scc_values.contains_free_region(r_scc, upper)1604    }16051606    pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {1607        &self.universal_region_relations.universal_regions1608    }16091610    /// Tries to find the best constraint to blame for the fact that1611    /// `R: from_region`, where `R` is some region that meets1612    /// `target_test`. This works by following the constraint graph,1613    /// creating a constraint path that forces `R` to outlive1614    /// `from_region`, and then finding the best choices within that1615    /// path to blame.1616    #[instrument(level = "debug", skip(self))]1617    pub(crate) fn best_blame_constraint(1618        &self,1619        from_region: RegionVid,1620        from_region_origin: NllRegionVariableOrigin<'tcx>,1621        to_region: RegionVid,1622    ) -> BestBlame<'tcx> {1623        assert!(from_region != to_region, "Trying to blame a region for itself!");16241625        let path = self.constraint_path_between_regions(from_region, to_region).unwrap();16261627        // If we are passing through a constraint added because we reached an unnameable placeholder `'unnameable`,1628        // redirect search towards `'unnameable`.1629        let due_to_placeholder_outlives = path.iter().find_map(|c| {1630            if let ConstraintCategory::OutlivesUnnameablePlaceholder(unnameable) = c.category {1631                Some(unnameable)1632            } else {1633                None1634            }1635        });16361637        // Edge case: it's possible that `'from_region` is an unnameable placeholder.1638        let mut path = if let Some(unnameable) = due_to_placeholder_outlives1639            && unnameable != from_region1640        {1641            // We ignore the extra edges due to unnameable placeholders to get1642            // an explanation that was present in the original constraint graph.1643            self.constraint_path_to(from_region, |r| r == unnameable, false).unwrap().01644        } else {1645            path1646        };16471648        debug!(1649            "path={:#?}",1650            path.iter()1651                .map(|c| format!(1652                    "{:?} ({:?}: {:?})",1653                    c,1654                    self.constraint_sccs.scc(c.sup),1655                    self.constraint_sccs.scc(c.sub),1656                ))1657                .collect::<Vec<_>>()1658        );16591660        // When reporting an error, there is typically a chain of constraints leading from some1661        // "source" region which must outlive some "target" region.1662        // In most cases, we prefer to "blame" the constraints closer to the target --1663        // but there is one exception. When constraints arise from higher-ranked subtyping,1664        // we generally prefer to blame the source value,1665        // as the "target" in this case tends to be some type annotation that the user gave.1666        // Therefore, if we find that the region origin is some instantiation1667        // of a higher-ranked region, we start our search from the "source" point1668        // rather than the "target", and we also tweak a few other things.1669        //1670        // An example might be this bit of Rust code:1671        //1672        // ```rust1673        // let x: fn(&'static ()) = |_| {};1674        // let y: for<'a> fn(&'a ()) = x;1675        // ```1676        //1677        // In MIR, this will be converted into a combination of assignments and type ascriptions.1678        // In particular, the 'static is imposed through a type ascription:1679        //1680        // ```rust1681        // x = ...;1682        // AscribeUserType(x, fn(&'static ())1683        // y = x;1684        // ```1685        //1686        // We wind up ultimately with constraints like1687        //1688        // ```rust1689        // !a: 'temp1 // from the `y = x` statement1690        // 'temp1: 'temp21691        // 'temp2: 'static // from the AscribeUserType1692        // ```1693        //1694        // and here we prefer to blame the source (the y = x statement).1695        let blame_source = match from_region_origin {1696            NllRegionVariableOrigin::FreeRegion => true,1697            NllRegionVariableOrigin::Placeholder(_) => false,1698            // `'existential: 'whatever` never results in a region error by itself.1699            // We may always infer it to `'static` afterall. This means while an error1700            // path may go through an existential, these existentials are never the1701            // `from_region`.1702            NllRegionVariableOrigin::Existential { name: _ } => {1703                unreachable!("existentials can outlive everything")1704            }1705        };17061707        // To pick a constraint to blame, we organize constraints by how interesting we expect them1708        // to be in diagnostics, then pick the most interesting one closest to either the source or1709        // the target on our constraint path.1710        let constraint_interest = |constraint: &OutlivesConstraint<'tcx>| {1711            // Try to avoid blaming constraints from desugarings, since they may not clearly match1712            // match what users have written. As an exception, allow blaming returns generated by1713            // `?` desugaring, since the correspondence is fairly clear.1714            let category = if let Some(kind) = constraint.span.desugaring_kind()1715                && (kind != DesugaringKind::QuestionMark1716                    || !matches!(constraint.category, ConstraintCategory::Return(_)))1717            {1718                ConstraintCategory::Boring1719            } else {1720                constraint.category1721            };17221723            let interest = match category {1724                // Returns usually provide a type to blame and have specially written diagnostics,1725                // so prioritize them.1726                ConstraintCategory::Return(_) => 0,1727                // Unsizing coercions are interesting, since we have a note for that:1728                // `BorrowExplanation::add_object_lifetime_default_note`.1729                // FIXME(dianne): That note shouldn't depend on a coercion being blamed; see issue1730                // #131008 for an example of where we currently don't emit it but should.1731                // Once the note is handled properly, this case should be removed. Until then, it1732                // should be as limited as possible; the note is prone to false positives and this1733                // constraint usually isn't best to blame.1734                ConstraintCategory::Cast {1735                    is_raw_ptr_dyn_type_cast: _,1736                    unsize_to: Some(unsize_ty),1737                    is_implicit_coercion: true,1738                } if to_region == self.universal_regions().fr_static1739                    // Mirror the note's condition, to minimize how often this diverts blame.1740                    && let ty::Adt(_, args) = unsize_ty.kind()1741                    && args.iter().any(|arg| arg.as_type().is_some_and(|ty| ty.is_trait()))1742                    // Mimic old logic for this, to minimize false positives in tests.1743                    && !path1744                        .iter()1745                        .any(|c| matches!(c.category, ConstraintCategory::TypeAnnotation(_))) =>1746                {1747                    11748                }1749                // Between other interesting constraints, order by their position on the `path`.1750                ConstraintCategory::Yield1751                | ConstraintCategory::UseAsConst1752                | ConstraintCategory::UseAsStatic1753                | ConstraintCategory::TypeAnnotation(1754                    AnnotationSource::Ascription1755                    | AnnotationSource::Declaration1756                    | AnnotationSource::OpaqueCast,1757                )1758                | ConstraintCategory::Cast { .. }1759                | ConstraintCategory::CallArgument(_)1760                | ConstraintCategory::CopyBound1761                | ConstraintCategory::SizedBound1762                | ConstraintCategory::Assignment1763                | ConstraintCategory::Usage1764                | ConstraintCategory::ClosureUpvar(_) => 2,1765                // Generic arguments are unlikely to be what relates regions together1766                ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => 3,1767                // We handle predicates and opaque types specially; don't prioritize them here.1768                ConstraintCategory::Predicate(_) | ConstraintCategory::OpaqueType => 4,1769                // `Boring` constraints can correspond to user-written code and have useful spans,1770                // but don't provide any other useful information for diagnostics.1771                ConstraintCategory::Boring => 5,1772                // `BoringNoLocation` constraints can point to user-written code, but are less1773                // specific, and are not used for relations that would make sense to blame.1774                ConstraintCategory::BoringNoLocation => 6,1775                // Do not blame internal constraints if we can avoid it. Never blame1776                // the `'region: 'static` constraints introduced by placeholder outlives.1777                ConstraintCategory::Internal => 7,1778                ConstraintCategory::OutlivesUnnameablePlaceholder(_) => 8,1779                ConstraintCategory::SolverRegionConstraint(_) => 9,1780            };17811782            debug!("constraint {constraint:?} category: {category:?}, interest: {interest:?}");17831784            interest1785        };17861787        let best_choice = if blame_source {1788            path.iter().enumerate().rev().min_by_key(|(_, c)| constraint_interest(c)).unwrap().01789        } else {1790            path.iter().enumerate().min_by_key(|(_, c)| constraint_interest(c)).unwrap().01791        };17921793        debug!(?best_choice, ?blame_source);17941795        let best_blame_idx = if let Some(next) = path.get(best_choice + 1)1796            && matches!(path[best_choice].category, ConstraintCategory::Return(_))1797            && next.category == ConstraintCategory::OpaqueType1798        {1799            // The return expression is being influenced by the return type being1800            // impl Trait, point at the return type and not the return expr.1801            best_choice + 11802        } else if path[best_choice].category == ConstraintCategory::Return(ReturnConstraint::Normal)1803            && let Some(field) = path.iter().find_map(|p| {1804                if let ConstraintCategory::ClosureUpvar(f) = p.category { Some(f) } else { None }1805            })1806        {1807            path[best_choice].category =1808                ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));1809            best_choice1810        } else {1811            best_choice1812        };18131814        assert!(1815            !matches!(1816                path[best_blame_idx].category,1817                ConstraintCategory::OutlivesUnnameablePlaceholder(_)1818            ),1819            "Illegal placeholder constraint blamed; should have redirected to other region relation"1820        );18211822        BestBlame { path, idx: best_blame_idx }1823    }18241825    pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {1826        // Query canonicalization can create local superuniverses (for example in1827        // `InferCtx::query_response_instantiation_guess`), but they don't have an associated1828        // `UniverseInfo` explaining why they were created.1829        // This can cause ICEs if these causes are accessed in diagnostics, for example in issue1830        // #114907 where this happens via liveness and dropck outlives results.1831        // Therefore, we return a default value in case that happens, which should at worst emit a1832        // suboptimal error, instead of the ICE.1833        self.universe_causes.get(&universe).cloned().unwrap_or_else(UniverseInfo::other)1834    }18351836    /// Tries to find the terminator of the loop in which the region 'r' resides.1837    /// Returns the location of the terminator if found.1838    pub(crate) fn find_loop_terminator_location(1839        &self,1840        r: RegionVid,1841        body: &Body<'_>,1842    ) -> Option<Location> {1843        let scc = self.constraint_sccs.scc(r);1844        let locations = self.scc_values.locations_outlived_by(scc);1845        for location in locations {1846            let bb = &body[location.block];1847            if let Some(terminator) = &bb.terminator1848                // terminator of a loop should be TerminatorKind::FalseUnwind1849                && let TerminatorKind::FalseUnwind { .. } = terminator.kind1850            {1851                return Some(location);1852            }1853        }1854        None1855    }18561857    /// Access to the SCC constraint graph.1858    /// This can be used to quickly under-approximate the regions which are equal to each other1859    /// and their relative orderings.1860    // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.1861    pub fn constraint_sccs(&self) -> &ConstraintSccs {1862        &self.constraint_sccs1863    }18641865    /// Returns the representative `RegionVid` for a given SCC.1866    /// See `RegionTracker` for how a region variable ID is chosen.1867    ///1868    /// It is a hacky way to manage checking regions for equality,1869    /// since we can 'canonicalize' each region to the representative1870    /// of its SCC and be sure that -- if they have the same repr --1871    /// they *must* be equal (though not having the same repr does not1872    /// mean they are unequal).1873    fn scc_representative(&self, scc: ConstraintSccIndex) -> RegionVid {1874        self.scc_annotations[scc].representative.rvid()1875    }18761877    pub(crate) fn liveness_constraints(&self) -> &LivenessValues {1878        &self.liveness_constraints1879    }18801881    /// When using `-Zpolonius=next`, records the given live loans for the loan scopes and active1882    /// loans dataflow computations.1883    pub(crate) fn record_live_loans(&mut self, live_loans: LiveLoans) {1884        self.liveness_constraints.record_live_loans(live_loans);1885    }18861887    /// Returns whether the `loan_idx` is live at the given `location`: whether its issuing1888    /// region is contained within the type of a variable that is live at this point.1889    /// Note: for now, the sets of live loans is only available when using `-Zpolonius=next`.1890    pub(crate) fn is_loan_live_at(&self, loan_idx: BorrowIndex, location: Location) -> bool {1891        let point = self.liveness_constraints.point_from_location(location);1892        self.liveness_constraints.is_loan_live_at(loan_idx, point)1893    }1894}18951896#[derive(Clone, Debug)]1897pub(crate) struct BestBlame<'tcx> {1898    /// See docs on [`RegionInferenceContext::best_blame_constraint`] for what this is.1899    path: Vec<OutlivesConstraint<'tcx>>,1900    /// Index into `path` of the constraint most relevant to report to users.1901    idx: usize,1902}19031904impl<'tcx> BestBlame<'tcx> {1905    pub(crate) fn to_obligation_cause(&self) -> ObligationCause<'tcx> {1906        // FIXME - determine what we should do if we encounter multiple1907        // `ConstraintCategory::Predicate` constraints. Currently, we just pick the first one.1908        let cause_code = self1909            .path1910            .iter()1911            .find_map(|constraint| {1912                if let ConstraintCategory::Predicate(predicate_span) = constraint.category {1913                    // We currently do not store the `DefId` in the `ConstraintCategory`1914                    // for performances reasons. The error reporting code used by NLL only1915                    // uses the span, so this doesn't cause any problems at the moment.1916                    Some(ObligationCauseCode::WhereClause(CRATE_DEF_ID.to_def_id(), predicate_span))1917                } else {1918                    None1919                }1920            })1921            .unwrap_or_else(|| ObligationCauseCode::Misc);19221923        ObligationCause::new(self.constraint().span, CRATE_DEF_ID, cause_code.clone())1924    }19251926    pub(crate) fn constraint(&self) -> &OutlivesConstraint<'tcx> {1927        &self.path[self.idx]1928    }19291930    pub(crate) fn path(&self) -> &[OutlivesConstraint<'tcx>] {1931        &self.path1932    }1933}

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.