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::{self, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, fold_regions};21use rustc_mir_dataflow::points::DenseLocationMap;22use rustc_span::hygiene::DesugaringKind;23use rustc_span::{DUMMY_SP, Span};24use tracing::{Level, debug, enabled, instrument, trace};2526use crate::constraints::graph::NormalConstraintGraph;27use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet};28use crate::dataflow::BorrowIndex;29use crate::diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo};30use crate::handle_placeholders::{LoweredConstraints, RegionTracker};31use crate::polonius::LiveLoans;32use crate::polonius::legacy::PoloniusOutput;33use crate::region_infer::values::{LivenessValues, RegionElement, RegionValues};34use crate::type_check::Locations;35use crate::type_check::free_region_relations::UniversalRegionRelations;36use crate::universal_regions::UniversalRegions;37use crate::{38 BorrowckInferCtxt, ClosureOutlivesRequirement, ClosureOutlivesSubject,39 ClosureOutlivesSubjectTy, ClosureRegionRequirements,40};4142mod dump_mir;43mod graphviz;44pub(crate) mod opaque_types;45mod reverse_sccs;4647pub(crate) mod values;4849/// The representative region variable for an SCC, tagged by its origin.50/// We prefer placeholders over existentially quantified variables, otherwise51/// it's the one with the smallest Region Variable ID. In other words,52/// the order of this enumeration really matters!53#[derive(Copy, Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]54pub(crate) enum Representative {55 FreeRegion(RegionVid),56 Placeholder(RegionVid),57 Existential(RegionVid),58}5960impl Representative {61 pub(crate) fn rvid(self) -> RegionVid {62 match self {63 Representative::FreeRegion(region_vid)64 | Representative::Placeholder(region_vid)65 | Representative::Existential(region_vid) => region_vid,66 }67 }6869 pub(crate) fn new(r: RegionVid, definition: &RegionDefinition<'_>) -> Self {70 match definition.origin {71 NllRegionVariableOrigin::FreeRegion => Representative::FreeRegion(r),72 NllRegionVariableOrigin::Placeholder(_) => Representative::Placeholder(r),73 NllRegionVariableOrigin::Existential { .. } => Representative::Existential(r),74 }75 }76}7778pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex>;7980pub struct RegionInferenceContext<'tcx> {81 /// Contains the definition for every region variable. Region82 /// variables are identified by their index (`RegionVid`). The83 /// definition contains information about where the region came84 /// from as well as its final inferred value.85 pub(crate) definitions: Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>,8687 /// The liveness constraints added to each region. For most88 /// regions, these start out empty and steadily grow, though for89 /// each universally quantified region R they start out containing90 /// the entire CFG and `end(R)`.91 liveness_constraints: LivenessValues,9293 /// The outlives constraints computed by the type-check.94 constraints: Frozen<OutlivesConstraintSet<'tcx>>,9596 /// The constraint-set, but in graph form, making it easy to traverse97 /// the constraints adjacent to a particular region. Used to construct98 /// the SCC (see `constraint_sccs`) and for error reporting.99 constraint_graph: Frozen<NormalConstraintGraph>,100101 /// The SCC computed from `constraints` and the constraint102 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to103 /// compute the values of each region.104 constraint_sccs: ConstraintSccs,105106 scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,107108 /// Map universe indexes to information on why we created it.109 universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,110111 /// The final inferred values of the region variables; we compute112 /// one value per SCC. To get the value for any given *region*,113 /// you first find which scc it is a part of.114 scc_values: RegionValues<'tcx, ConstraintSccIndex>,115116 /// Type constraints that we check after solving.117 type_tests: Vec<TypeTest<'tcx>>,118119 /// Information about how the universally quantified regions in120 /// scope on this function relate to one another.121 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,122}123124#[derive(Debug)]125pub(crate) struct RegionDefinition<'tcx> {126 /// What kind of variable is this -- a free region? existential127 /// variable? etc. (See the `NllRegionVariableOrigin` for more128 /// info.)129 pub(crate) origin: NllRegionVariableOrigin<'tcx>,130131 /// Which universe is this region variable defined in? This is132 /// most often `ty::UniverseIndex::ROOT`, but when we encounter133 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create134 /// the variable for `'a` in a fresh universe that extends ROOT.135 pub(crate) universe: ty::UniverseIndex,136137 /// If this is 'static or an early-bound region, then this is138 /// `Some(X)` where `X` is the name of the region.139 pub(crate) external_name: Option<ty::Region<'tcx>>,140}141142/// N.B., the variants in `Cause` are intentionally ordered. Lower143/// values are preferred when it comes to error messages. Do not144/// reorder willy nilly.145#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]146pub(crate) enum Cause {147 /// point inserted because Local was live at the given Location148 LiveVar(Local, Location),149150 /// point inserted because Local was dropped at the given Location151 DropVar(Local, Location),152}153154/// A "type test" corresponds to an outlives constraint between a type155/// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are156/// translated from the `Verify` region constraints in the ordinary157/// inference context.158///159/// These sorts of constraints are handled differently than ordinary160/// constraints, at least at present. During type checking, the161/// `InferCtxt::process_registered_region_obligations` method will162/// attempt to convert a type test like `T: 'x` into an ordinary163/// outlives constraint when possible (for example, `&'a T: 'b` will164/// be converted into `'a: 'b` and registered as a `Constraint`).165///166/// In some cases, however, there are outlives relationships that are167/// not converted into a region constraint, but rather into one of168/// these "type tests". The distinction is that a type test does not169/// influence the inference result, but instead just examines the170/// values that we ultimately inferred for each region variable and171/// checks that they meet certain extra criteria. If not, an error172/// can be issued.173///174/// One reason for this is that these type tests typically boil down175/// to a check like `'a: 'x` where `'a` is a universally quantified176/// region -- and therefore not one whose value is really meant to be177/// *inferred*, precisely (this is not always the case: one can have a178/// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an179/// inference variable). Another reason is that these type tests can180/// involve *disjunction* -- that is, they can be satisfied in more181/// than one way.182///183/// For more information about this translation, see184/// `InferCtxt::process_registered_region_obligations` and185/// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.186#[derive(Clone)]187pub(crate) struct TypeTest<'tcx> {188 /// The type `T` that must outlive the region.189 pub generic_kind: GenericKind<'tcx>,190191 /// The region `'x` that the type must outlive.192 pub lower_bound: RegionVid,193194 /// The span to blame.195 pub span: Span,196197 /// A test which, if met by the region `'x`, proves that this type198 /// constraint is satisfied.199 pub verify_bound: VerifyBound<'tcx>,200}201202impl fmt::Debug for TypeTest<'_> {203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {204 fn fmt_bound(205 f: &mut fmt::Formatter<'_>,206 generic_kind: GenericKind<'_>,207 lower: RegionVid,208 bound: &VerifyBound<'_>,209 ) -> fmt::Result {210 let fmt_bounds =211 |f: &mut fmt::Formatter<'_>, bounds: &[VerifyBound<'_>]| -> fmt::Result {212 let mut it = bounds.iter().peekable();213 while let Some(bound) = it.next() {214 fmt_bound(f, generic_kind, lower, bound)?;215 if it.peek().is_some() {216 write!(f, ", ")?217 }218 }219 Ok(())220 };221 match bound {222 VerifyBound::IfEq(binder) => write!(f, "{:?} == {:?}", generic_kind, binder),223 VerifyBound::OutlivedBy(region) => write!(f, "{region:?}: {lower:?}"),224 VerifyBound::AnyBound(verify_bounds) => {225 write!(f, "Any[")?;226 fmt_bounds(f, verify_bounds)?;227 write!(f, "]")228 }229 VerifyBound::AllBounds(verify_bounds) => {230 write!(f, "All[")?;231 fmt_bounds(f, verify_bounds)?;232 write!(f, "]")233 }234 VerifyBound::IsEmpty => write!(f, "Empty({lower:?})"),235 }236 }237 write!(f, "TypeTest from {:?}[", self.span)?;238 fmt_bound(f, self.generic_kind, self.lower_bound, &self.verify_bound)?;239 write!(f, "] ⊢ {:?}: {:?}", self.generic_kind, self.lower_bound)240 }241}242243/// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure244/// environment). If we can't, it is an error.245#[derive(Clone, Copy, Debug, Eq, PartialEq)]246enum RegionRelationCheckResult {247 Ok,248 Propagated,249 Error,250}251252#[derive(Clone, PartialEq, Eq, Debug)]253enum Trace<'a, 'tcx> {254 StartRegion,255 FromGraph(&'a OutlivesConstraint<'tcx>),256 FromStatic(RegionVid),257 NotVisited,258}259260#[instrument(skip(infcx, sccs), level = "debug")]261fn sccs_info<'tcx>(infcx: &BorrowckInferCtxt<'tcx>, sccs: &ConstraintSccs) {262 use crate::renumber::RegionCtxt;263264 let var_to_origin = infcx.reg_var_to_origin.borrow();265266 let mut var_to_origin_sorted = var_to_origin.clone().into_iter().collect::<Vec<_>>();267 var_to_origin_sorted.sort_by_key(|vto| vto.0);268269 if enabled!(Level::DEBUG) {270 let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string();271 for (reg_var, origin) in var_to_origin_sorted.into_iter() {272 reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n"));273 }274 debug!("{}", reg_vars_to_origins_str);275 }276277 let num_components = sccs.num_sccs();278 let mut components = vec![FxIndexSet::default(); num_components];279280 for (reg_var, scc_idx) in sccs.scc_indices().iter_enumerated() {281 let origin = var_to_origin.get(®_var).unwrap_or(&RegionCtxt::Unknown);282 components[scc_idx.as_usize()].insert((reg_var, *origin));283 }284285 if enabled!(Level::DEBUG) {286 let mut components_str = "strongly connected components:".to_string();287 for (scc_idx, reg_vars_origins) in components.iter().enumerate() {288 let regions_info = reg_vars_origins.clone().into_iter().collect::<Vec<_>>();289 components_str.push_str(&format!(290 "{:?}: {:?},\n)",291 ConstraintSccIndex::from_usize(scc_idx),292 regions_info,293 ))294 }295 debug!("{}", components_str);296 }297298 // calculate the best representative for each component299 let components_representatives = components300 .into_iter()301 .enumerate()302 .map(|(scc_idx, region_ctxts)| {303 let repr = region_ctxts304 .into_iter()305 .map(|reg_var_origin| reg_var_origin.1)306 .max_by(|x, y| x.preference_value().cmp(&y.preference_value()))307 .unwrap();308309 (ConstraintSccIndex::from_usize(scc_idx), repr)310 })311 .collect::<FxIndexMap<_, _>>();312313 let mut scc_node_to_edges = FxIndexMap::default();314 for (scc_idx, repr) in components_representatives.iter() {315 let edge_representatives = sccs316 .successors(*scc_idx)317 .iter()318 .map(|scc_idx| components_representatives[scc_idx])319 .collect::<Vec<_>>();320 scc_node_to_edges.insert((scc_idx, repr), edge_representatives);321 }322323 debug!("SCC edges {:#?}", scc_node_to_edges);324}325326impl<'tcx> RegionInferenceContext<'tcx> {327 /// Creates a new region inference context with a total of328 /// `num_region_variables` valid inference variables; the first N329 /// of those will be constant regions representing the free330 /// regions defined in `universal_regions`.331 ///332 /// The `outlives_constraints` and `type_tests` are an initial set333 /// of constraints produced by the MIR type check.334 pub(crate) fn new(335 infcx: &BorrowckInferCtxt<'tcx>,336 lowered_constraints: LoweredConstraints<'tcx>,337 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,338 location_map: Rc<DenseLocationMap>,339 ) -> Self {340 let universal_regions = &universal_region_relations.universal_regions;341342 let LoweredConstraints {343 constraint_sccs,344 definitions,345 outlives_constraints,346 scc_annotations,347 type_tests,348 mut liveness_constraints,349 universe_causes,350 placeholder_indices,351 } = lowered_constraints;352353 debug!("universal_regions: {:#?}", universal_region_relations.universal_regions);354 debug!("outlives constraints: {:#?}", outlives_constraints);355 debug!("placeholder_indices: {:#?}", placeholder_indices);356 debug!("type tests: {:#?}", type_tests);357358 let constraint_graph = Frozen::freeze(outlives_constraints.graph(definitions.len()));359360 if cfg!(debug_assertions) {361 sccs_info(infcx, &constraint_sccs);362 }363364 let mut scc_values =365 RegionValues::new(location_map, universal_regions.len(), placeholder_indices);366367 // Initializes the region variables with their initial live points.368 for (region, definition) in definitions.iter_enumerated() {369 let scc = constraint_sccs.scc(region);370371 // For each universally quantified region (lifetime parameter). The372 // first N variables always correspond to the regions appearing in the373 // function signature (both named and anonymous) and in where-clauses.374 match definition.origin {375 // For each free, universally quantified region X:376 NllRegionVariableOrigin::FreeRegion => {377 // Add all nodes in the CFG to liveness constraints378 liveness_constraints.add_all_points(region);379380 // Add `end(X)` into the set for X.381 scc_values.add_free_region(scc, region);382 }383384 NllRegionVariableOrigin::Placeholder(placeholder) => {385 scc_values.add_placeholder(scc, placeholder);386 }387388 NllRegionVariableOrigin::Existential { .. } => {389 // For existential, regions, nothing to do.390 }391 }392393 // Initially copy the liveness constraints of any region that394 // has them, setting `scc_values[scc(region)] |= liveness_constraints[region]`.395 //396 // These values will later be propagated during [`Self::propagate_constraints()`].397 // The values include any live-at-all-points constraints added above398 // for free regions.399 if let Some(liveness) = liveness_constraints.point_liveness(region) {400 scc_values.merge_liveness(scc, liveness)401 }402 }403404 Self {405 definitions,406 liveness_constraints,407 constraints: outlives_constraints,408 constraint_graph,409 constraint_sccs,410 scc_annotations,411 universe_causes,412 scc_values,413 type_tests,414 universal_region_relations,415 }416 }417418 /// Returns an iterator over all the region indices.419 pub(crate) fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {420 self.definitions.indices()421 }422423 /// Given a universal region in scope on the MIR, returns the424 /// corresponding index.425 ///426 /// Panics if `r` is not a registered universal region, most notably427 /// if it is a placeholder. Handling placeholders requires access to the428 /// `MirTypeckRegionConstraints`.429 pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {430 self.universal_regions().to_region_vid(r)431 }432433 /// Returns an iterator over all the outlives constraints.434 pub(crate) fn outlives_constraints(&self) -> impl Iterator<Item = OutlivesConstraint<'tcx>> {435 self.constraints.outlives().iter().copied()436 }437438 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.439 pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {440 self.universal_regions().annotate(tcx, err)441 }442443 /// Returns `true` if the region `r` contains the point `p`.444 ///445 /// Panics if called before `solve()` executes,446 pub(crate) fn region_contains_point(&self, r: RegionVid, p: Location) -> bool {447 let scc = self.constraint_sccs.scc(r);448 self.scc_values.contains_point(scc, p)449 }450451 /// Returns the lowest statement index in `start..=end` which is not contained by `r`.452 ///453 /// Panics if called before `solve()` executes.454 pub(crate) fn first_non_contained_inclusive(455 &self,456 r: RegionVid,457 block: BasicBlock,458 start: usize,459 end: usize,460 ) -> Option<usize> {461 let scc = self.constraint_sccs.scc(r);462 self.scc_values.first_non_contained_inclusive(scc, block, start, end)463 }464465 /// Returns access to the value of `r` for debugging purposes.466 pub(crate) fn region_value_str(&self, r: RegionVid) -> String {467 let scc = self.constraint_sccs.scc(r);468 self.scc_values.region_value_str(scc)469 }470471 pub(crate) fn placeholders_contained_in(472 &self,473 r: RegionVid,474 ) -> impl Iterator<Item = ty::PlaceholderRegion<'tcx>> {475 let scc = self.constraint_sccs.scc(r);476 self.scc_values.placeholders_contained_in(scc)477 }478479 /// Performs region inference and report errors if we see any480 /// unsatisfiable constraints. If this is a closure, returns the481 /// region requirements to propagate to our creator, if any.482 #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]483 pub(super) fn solve(484 &mut self,485 infcx: &InferCtxt<'tcx>,486 body: &Body<'tcx>,487 polonius_output: Option<Box<PoloniusOutput>>,488 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {489 let mir_def_id = body.source.def_id();490 self.propagate_constraints();491492 let mut errors_buffer = RegionErrors::new(infcx.tcx);493494 // If this is a nested body, we propagate unsatisfied495 // outlives constraints to the parent body instead of496 // eagerly erroing.497 let mut propagated_outlives_requirements =498 infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);499500 self.check_type_tests(infcx, propagated_outlives_requirements.as_mut(), &mut errors_buffer);501502 debug!(?errors_buffer);503 debug!(?propagated_outlives_requirements);504505 // In Polonius mode, the errors about missing universal region relations are in the output506 // and need to be emitted or propagated. Otherwise, we need to check whether the507 // constraints were too strong, and if so, emit or propagate those errors.508 if infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled() {509 self.check_polonius_subset_errors(510 propagated_outlives_requirements.as_mut(),511 &mut errors_buffer,512 polonius_output513 .as_ref()514 .expect("Polonius output is unavailable despite `-Z polonius`"),515 );516 } else {517 self.check_universal_regions(518 propagated_outlives_requirements.as_mut(),519 &mut errors_buffer,520 );521 }522523 debug!(?errors_buffer);524525 let propagated_outlives_requirements = propagated_outlives_requirements.unwrap_or_default();526527 if propagated_outlives_requirements.is_empty() {528 (None, errors_buffer)529 } else {530 let num_external_vids = self.universal_regions().num_global_and_external_regions();531 (532 Some(ClosureRegionRequirements {533 num_external_vids,534 outlives_requirements: propagated_outlives_requirements,535 }),536 errors_buffer,537 )538 }539 }540541 /// Propagate the region constraints: this will grow the values542 /// for each region variable until all the constraints are543 /// satisfied. Note that some values may grow **too** large to be544 /// feasible, but we check this later.545 #[instrument(skip(self), level = "debug")]546 fn propagate_constraints(&mut self) {547 debug!("constraints={:#?}", {548 let mut constraints: Vec<_> = self.outlives_constraints().collect();549 constraints.sort_by_key(|c| (c.sup, c.sub));550 constraints551 .into_iter()552 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))553 .collect::<Vec<_>>()554 });555556 // To propagate constraints, we walk the DAG induced by the557 // SCC. For each SCC `A`, we visit its successors and compute558 // their values, then we union all those values to get our559 // own. This one-shot approach works because iteration is in560 // dependency order. I.e. a chain A: B: C will visit C, B, A.561 for scc_a in self.constraint_sccs.all_sccs() {562 // Walk each SCC `B` such that `A: B`...563 for &scc_b in self.constraint_sccs.successors(scc_a) {564 debug!(?scc_b);565 self.scc_values.add_region(scc_a, scc_b);566 }567 }568 }569570 /// Returns `true` if all the placeholders in the value of `scc_b` are nameable571 /// in `scc_a`. Used during constraint propagation, and only once572 /// the value of `scc_b` has been computed.573 fn can_name_all_placeholders(574 &self,575 scc_a: ConstraintSccIndex,576 scc_b: ConstraintSccIndex,577 ) -> bool {578 self.scc_annotations[scc_a].can_name_all_placeholders(self.scc_annotations[scc_b])579 }580581 /// Once regions have been propagated, this method is used to see582 /// whether the "type tests" produced by typeck were satisfied;583 /// type tests encode type-outlives relationships like `T:584 /// 'a`. See `TypeTest` for more details.585 fn check_type_tests(586 &self,587 infcx: &InferCtxt<'tcx>,588 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,589 errors_buffer: &mut RegionErrors<'tcx>,590 ) {591 let tcx = infcx.tcx;592593 // Sometimes we register equivalent type-tests that would594 // result in basically the exact same error being reported to595 // the user. Avoid that.596 let mut deduplicate_errors = FxIndexSet::default();597598 for type_test in &self.type_tests {599 debug!("check_type_test: {:?}", type_test);600601 let generic_ty = type_test.generic_kind.to_ty(tcx);602 if self.eval_verify_bound(603 infcx,604 generic_ty,605 type_test.lower_bound,606 &type_test.verify_bound,607 ) {608 continue;609 }610611 if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements612 && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements)613 {614 continue;615 }616617 // Type-test failed. Report the error.618 let erased_generic_kind = infcx.tcx.erase_and_anonymize_regions(type_test.generic_kind);619620 // Skip duplicate-ish errors.621 if deduplicate_errors.insert((622 erased_generic_kind,623 type_test.lower_bound,624 type_test.span,625 )) {626 debug!(627 "check_type_test: reporting error for erased_generic_kind={:?}, \628 lower_bound_region={:?}, \629 type_test.span={:?}",630 erased_generic_kind, type_test.lower_bound, type_test.span,631 );632633 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });634 }635 }636 }637638 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot639 /// prove to be satisfied. If this is a closure, we will attempt to640 /// "promote" this type-test into our `ClosureRegionRequirements` and641 /// hence pass it up the creator. To do this, we have to phrase the642 /// type-test in terms of external free regions, as local free643 /// regions are not nameable by the closure's creator.644 ///645 /// Promotion works as follows: we first check that the type `T`646 /// contains only regions that the creator knows about. If this is647 /// true, then -- as a consequence -- we know that all regions in648 /// the type `T` are free regions that outlive the closure body. If649 /// false, then promotion fails.650 ///651 /// Once we've promoted T, we have to "promote" `'X` to some region652 /// that is "external" to the closure. Generally speaking, a region653 /// may be the union of some points in the closure body as well as654 /// various free lifetimes. We can ignore the points in the closure655 /// body: if the type T can be expressed in terms of external regions,656 /// we know it outlives the points in the closure body. That657 /// just leaves the free regions.658 ///659 /// The idea then is to lower the `T: 'X` constraint into multiple660 /// bounds -- e.g., if `'X` is the union of two free lifetimes,661 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.662 #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]663 fn try_promote_type_test(664 &self,665 infcx: &InferCtxt<'tcx>,666 type_test: &TypeTest<'tcx>,667 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,668 ) -> bool {669 let tcx = infcx.tcx;670 let TypeTest { generic_kind, lower_bound, span: blame_span, verify_bound: _ } = *type_test;671672 let generic_ty = generic_kind.to_ty(tcx);673 let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {674 return false;675 };676677 let r_scc = self.constraint_sccs.scc(lower_bound);678 debug!(679 "lower_bound = {:?} r_scc={:?} universe={:?}",680 lower_bound,681 r_scc,682 self.max_nameable_universe(r_scc)683 );684 // If the type test requires that `T: 'a` where `'a` is a685 // placeholder from another universe, that effectively requires686 // `T: 'static`, so we have to propagate that requirement.687 //688 // It doesn't matter *what* universe because the promoted `T` will689 // always be in the root universe.690 if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {691 debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);692 let static_r = self.universal_regions().fr_static;693 propagated_outlives_requirements.push(ClosureOutlivesRequirement {694 subject,695 outlived_free_region: static_r,696 blame_span,697 category: ConstraintCategory::Boring,698 });699700 // we can return here -- the code below might push add'l constraints701 // but they would all be weaker than this one.702 return true;703 }704705 // For each region outlived by lower_bound find a non-local,706 // universal region (it may be the same region) and add it to707 // `ClosureOutlivesRequirement`.708 let mut found_outlived_universal_region = false;709 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {710 found_outlived_universal_region = true;711 debug!("universal_region_outlived_by ur={:?}", ur);712 let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);713 debug!(?non_local_ub);714715 // This is slightly too conservative. To show T: '1, given `'2: '1`716 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to717 // avoid potential non-determinism we approximate this by requiring718 // T: '1 and T: '2.719 for upper_bound in non_local_ub {720 debug_assert!(self.universal_regions().is_universal_region(upper_bound));721 debug_assert!(!self.universal_regions().is_local_free_region(upper_bound));722723 let requirement = ClosureOutlivesRequirement {724 subject,725 outlived_free_region: upper_bound,726 blame_span,727 category: ConstraintCategory::Boring,728 };729 debug!(?requirement, "adding closure requirement");730 propagated_outlives_requirements.push(requirement);731 }732 }733 // If we succeed to promote the subject, i.e. it only contains non-local regions,734 // and fail to prove the type test inside of the closure, the `lower_bound` has to735 // also be at least as large as some universal region, as the type test is otherwise736 // trivial.737 assert!(found_outlived_universal_region);738 true739 }740741 /// When we promote a type test `T: 'r`, we have to replace all region742 /// variables in the type `T` with an equal universal region from the743 /// closure signature.744 /// This is not always possible, so this is a fallible process.745 #[instrument(level = "debug", skip(self, infcx), ret)]746 fn try_promote_type_test_subject(747 &self,748 infcx: &InferCtxt<'tcx>,749 ty: Ty<'tcx>,750 ) -> Option<ClosureOutlivesSubject<'tcx>> {751 let tcx = infcx.tcx;752 let mut failed = false;753 let ty = fold_regions(tcx, ty, |r, _depth| {754 let r_vid = self.to_region_vid(r);755 let r_scc = self.constraint_sccs.scc(r_vid);756757 // The challenge is this. We have some region variable `r`758 // whose value is a set of CFG points and universal759 // regions. We want to find if that set is *equivalent* to760 // any of the named regions found in the closure.761 // To do so, we simply check every candidate `u_r` for equality.762 self.scc_values763 .universal_regions_outlived_by(r_scc)764 .filter(|&u_r| !self.universal_regions().is_local_free_region(u_r))765 .find(|&u_r| self.eval_equal(u_r, r_vid))766 .map(|u_r| ty::Region::new_var(tcx, u_r))767 // In case we could not find a named region to map to,768 // we will return `None` below.769 .unwrap_or_else(|| {770 failed = true;771 r772 })773 });774775 debug!("try_promote_type_test_subject: folded ty = {:?}", ty);776777 // This will be true if we failed to promote some region.778 if failed {779 return None;780 }781782 Some(ClosureOutlivesSubject::Ty(ClosureOutlivesSubjectTy::bind(tcx, ty)))783 }784785 /// Like `universal_upper_bound`, but returns an approximation more suitable786 /// for diagnostics. If `r` contains multiple disjoint universal regions787 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.788 /// This corresponds to picking named regions over unnamed regions789 /// (e.g. picking early-bound regions over a closure late-bound region).790 ///791 /// This means that the returned value may not be a true upper bound, since792 /// only 'static is known to outlive disjoint universal regions.793 /// Therefore, this method should only be used in diagnostic code,794 /// where displaying *some* named universal region is better than795 /// falling back to 'static.796 #[instrument(level = "debug", skip(self))]797 pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {798 debug!("{}", self.region_value_str(r));799800 // Find the smallest universal region that contains all other801 // universal regions within `region`.802 let mut lub = self.universal_regions().fr_fn_body;803 let r_scc = self.constraint_sccs.scc(r);804 let static_r = self.universal_regions().fr_static;805 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {806 let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);807 debug!(?ur, ?lub, ?new_lub);808 // The upper bound of two non-static regions is static: this809 // means we know nothing about the relationship between these810 // two regions. Pick a 'better' one to use when constructing811 // a diagnostic812 if ur != static_r && lub != static_r && new_lub == static_r {813 // Prefer the region with an `external_name` - this814 // indicates that the region is early-bound, so working with815 // it can produce a nicer error.816 if self.region_definition(ur).external_name.is_some() {817 lub = ur;818 } else if self.region_definition(lub).external_name.is_some() {819 // Leave lub unchanged820 } else {821 // If we get here, we don't have any reason to prefer822 // one region over the other. Just pick the823 // one with the lower index for now.824 lub = std::cmp::min(ur, lub);825 }826 } else {827 lub = new_lub;828 }829 }830831 debug!(?r, ?lub);832833 lub834 }835836 /// Tests if `test` is true when applied to `lower_bound` at837 /// `point`.838 fn eval_verify_bound(839 &self,840 infcx: &InferCtxt<'tcx>,841 generic_ty: Ty<'tcx>,842 lower_bound: RegionVid,843 verify_bound: &VerifyBound<'tcx>,844 ) -> bool {845 debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);846847 match verify_bound {848 VerifyBound::IfEq(verify_if_eq_b) => {849 self.eval_if_eq(infcx, generic_ty, lower_bound, *verify_if_eq_b)850 }851852 VerifyBound::IsEmpty => {853 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);854 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()855 }856857 VerifyBound::OutlivedBy(r) => {858 let r_vid = self.to_region_vid(*r);859 self.eval_outlives(r_vid, lower_bound)860 }861862 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {863 self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)864 }),865866 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {867 self.eval_verify_bound(infcx, generic_ty, lower_bound, verify_bound)868 }),869 }870 }871872 fn eval_if_eq(873 &self,874 infcx: &InferCtxt<'tcx>,875 generic_ty: Ty<'tcx>,876 lower_bound: RegionVid,877 verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,878 ) -> bool {879 let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);880 let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);881 match test_type_match::extract_verify_if_eq(infcx.tcx, &verify_if_eq_b, generic_ty) {882 Some(r) => {883 let r_vid = self.to_region_vid(r);884 self.eval_outlives(r_vid, lower_bound)885 }886 None => false,887 }888 }889890 /// This is a conservative normalization procedure. It takes every891 /// free region in `value` and replaces it with the892 /// "representative" of its SCC (see `scc_representatives` field).893 /// We are guaranteed that if two values normalize to the same894 /// thing, then they are equal; this is a conservative check in895 /// that they could still be equal even if they normalize to896 /// different results. (For example, there might be two regions897 /// with the same value that are not in the same SCC).898 ///899 /// N.B., this is not an ideal approach and I would like to revisit900 /// it. However, it works pretty well in practice. In particular,901 /// this is needed to deal with projection outlives bounds like902 ///903 /// ```text904 /// <T as Foo<'0>>::Item: '1905 /// ```906 ///907 /// In particular, this routine winds up being important when908 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the909 /// environment. In this case, if we can show that `'0 == 'a`,910 /// and that `'b: '1`, then we know that the clause is911 /// satisfied. In such cases, particularly due to limitations of912 /// the trait solver =), we usually wind up with a where-clause like913 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as914 /// a constraint, and thus ensures that they are in the same SCC.915 ///916 /// So why can't we do a more correct routine? Well, we could917 /// *almost* use the `relate_tys` code, but the way it is918 /// currently setup it creates inference variables to deal with919 /// higher-ranked things and so forth, and right now the inference920 /// context is not permitted to make more inference variables. So921 /// we use this kind of hacky solution.922 fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T923 where924 T: TypeFoldable<TyCtxt<'tcx>>,925 {926 fold_regions(tcx, value, |r, _db| {927 let vid = self.to_region_vid(r);928 let scc = self.constraint_sccs.scc(vid);929 let repr = self.scc_representative(scc);930 ty::Region::new_var(tcx, repr)931 })932 }933934 /// Evaluate whether `sup_region == sub_region`.935 ///936 /// Panics if called before `solve()` executes,937 // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.938 pub fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {939 self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)940 }941942 /// Evaluate whether `sup_region: sub_region`.943 ///944 /// Panics if called before `solve()` executes,945 // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.946 #[instrument(skip(self), level = "debug", ret)]947 pub fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {948 debug!(949 "sup_region's value = {:?} universal={:?}",950 self.region_value_str(sup_region),951 self.universal_regions().is_universal_region(sup_region),952 );953 debug!(954 "sub_region's value = {:?} universal={:?}",955 self.region_value_str(sub_region),956 self.universal_regions().is_universal_region(sub_region),957 );958959 let sub_region_scc = self.constraint_sccs.scc(sub_region);960 let sup_region_scc = self.constraint_sccs.scc(sup_region);961962 if sub_region_scc == sup_region_scc {963 debug!("{sup_region:?}: {sub_region:?} holds trivially; they are in the same SCC");964 return true;965 }966967 let fr_static = self.universal_regions().fr_static;968969 // If we are checking that `'sup: 'sub`, and `'sub` contains970 // some placeholder that `'sup` cannot name, then this is only971 // true if `'sup` outlives static.972 //973 // Avoid infinite recursion if `sub_region` is already `'static`974 if sub_region != fr_static975 && !self.can_name_all_placeholders(sup_region_scc, sub_region_scc)976 {977 debug!(978 "sub universe `{sub_region_scc:?}` is not nameable \979 by super `{sup_region_scc:?}`, promoting to static",980 );981982 return self.eval_outlives(sup_region, fr_static);983 }984985 // Both the `sub_region` and `sup_region` consist of the union986 // of some number of universal regions (along with the union987 // of various points in the CFG; ignore those points for988 // now). Therefore, the sup-region outlives the sub-region if,989 // for each universal region R1 in the sub-region, there990 // exists some region R2 in the sup-region that outlives R1.991 let universal_outlives =992 self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {993 self.scc_values994 .universal_regions_outlived_by(sup_region_scc)995 .any(|r2| self.universal_region_relations.outlives(r2, r1))996 });997998 if !universal_outlives {999 debug!("sub region contains a universal region not present in super");1000 return false;1001 }10021003 // Now we have to compare all the points in the sub region and make1004 // sure they exist in the sup region.10051006 if self.universal_regions().is_universal_region(sup_region) {1007 // Micro-opt: universal regions contain all points.1008 debug!("super is universal and hence contains all points");1009 return true;1010 }10111012 debug!("comparison between points in sup/sub");10131014 self.scc_values.contains_points(sup_region_scc, sub_region_scc)1015 }10161017 /// Once regions have been propagated, this method is used to see1018 /// whether any of the constraints were too strong. In particular,1019 /// we want to check for a case where a universally quantified1020 /// region exceeded its bounds. Consider:1021 /// ```compile_fail1022 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }1023 /// ```1024 /// In this case, returning `x` requires `&'a u32 <: &'b u32`1025 /// and hence we establish (transitively) a constraint that1026 /// `'a: 'b`. The `propagate_constraints` code above will1027 /// therefore add `end('a)` into the region for `'b` -- but we1028 /// have no evidence that `'b` outlives `'a`, so we want to report1029 /// an error.1030 ///1031 /// If `propagated_outlives_requirements` is `Some`, then we will1032 /// push unsatisfied obligations into there. Otherwise, we'll1033 /// report them as errors.1034 fn check_universal_regions(1035 &self,1036 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1037 errors_buffer: &mut RegionErrors<'tcx>,1038 ) {1039 for (fr, fr_definition) in self.definitions.iter_enumerated() {1040 debug!(?fr, ?fr_definition);1041 match fr_definition.origin {1042 NllRegionVariableOrigin::FreeRegion => {1043 // Go through each of the universal regions `fr` and check that1044 // they did not grow too large, accumulating any requirements1045 // for our caller into the `outlives_requirements` vector.1046 self.check_universal_region(1047 fr,1048 &mut propagated_outlives_requirements,1049 errors_buffer,1050 );1051 }10521053 NllRegionVariableOrigin::Placeholder(placeholder) => {1054 self.check_bound_universal_region(fr, placeholder, errors_buffer);1055 }10561057 NllRegionVariableOrigin::Existential { .. } => {1058 // nothing to check here1059 }1060 }1061 }1062 }10631064 /// Checks if Polonius has found any unexpected free region relations.1065 ///1066 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent1067 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`1068 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL1069 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.1070 ///1071 /// More details can be found in this blog post by Niko:1072 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>1073 ///1074 /// In the canonical example1075 /// ```compile_fail1076 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }1077 /// ```1078 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a1079 /// constraint that `'a: 'b`. It is an error that we have no evidence that this1080 /// constraint holds.1081 ///1082 /// If `propagated_outlives_requirements` is `Some`, then we will1083 /// push unsatisfied obligations into there. Otherwise, we'll1084 /// report them as errors.1085 fn check_polonius_subset_errors(1086 &self,1087 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1088 errors_buffer: &mut RegionErrors<'tcx>,1089 polonius_output: &PoloniusOutput,1090 ) {1091 debug!(1092 "check_polonius_subset_errors: {} subset_errors",1093 polonius_output.subset_errors.len()1094 );10951096 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly1097 // declared ("known") was found by Polonius, so emit an error, or propagate the1098 // requirements for our caller into the `propagated_outlives_requirements` vector.1099 //1100 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the1101 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with1102 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",1103 // and the "superset origin" is the outlived "shorter free region".1104 //1105 // Note: Polonius will produce a subset error at every point where the unexpected1106 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful1107 // for diagnostics in the future, e.g. to point more precisely at the key locations1108 // requiring this constraint to hold. However, the error and diagnostics code downstream1109 // expects that these errors are not duplicated (and that they are in a certain order).1110 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or1111 // anonymous lifetimes for example, could give these names differently, while others like1112 // the outlives suggestions or the debug output from `#[rustc_regions]` would be1113 // duplicated. The polonius subset errors are deduplicated here, while keeping the1114 // CFG-location ordering.1115 // We can iterate the HashMap here because the result is sorted afterwards.1116 #[allow(rustc::potential_query_instability)]1117 let mut subset_errors: Vec<_> = polonius_output1118 .subset_errors1119 .iter()1120 .flat_map(|(_location, subset_errors)| subset_errors.iter())1121 .collect();1122 subset_errors.sort();1123 subset_errors.dedup();11241125 for &(longer_fr, shorter_fr) in subset_errors.into_iter() {1126 debug!(1127 "check_polonius_subset_errors: subset_error longer_fr={:?},\1128 shorter_fr={:?}",1129 longer_fr, shorter_fr1130 );11311132 let propagated = self.try_propagate_universal_region_error(1133 longer_fr.into(),1134 shorter_fr.into(),1135 &mut propagated_outlives_requirements,1136 );1137 if propagated == RegionRelationCheckResult::Error {1138 errors_buffer.push(RegionErrorKind::RegionError {1139 longer_fr: longer_fr.into(),1140 shorter_fr: shorter_fr.into(),1141 fr_origin: NllRegionVariableOrigin::FreeRegion,1142 is_reported: true,1143 });1144 }1145 }11461147 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has1148 // a more complete picture on how to separate this responsibility.1149 for (fr, fr_definition) in self.definitions.iter_enumerated() {1150 match fr_definition.origin {1151 NllRegionVariableOrigin::FreeRegion => {1152 // handled by polonius above1153 }11541155 NllRegionVariableOrigin::Placeholder(placeholder) => {1156 self.check_bound_universal_region(fr, placeholder, errors_buffer);1157 }11581159 NllRegionVariableOrigin::Existential { .. } => {1160 // nothing to check here1161 }1162 }1163 }1164 }11651166 /// The largest universe of any region nameable from this SCC.1167 fn max_nameable_universe(&self, scc: ConstraintSccIndex) -> UniverseIndex {1168 self.scc_annotations[scc].max_nameable_universe()1169 }11701171 /// Checks the final value for the free region `fr` to see if it1172 /// grew too large. In particular, examine what `end(X)` points1173 /// wound up in `fr`'s final value; for each `end(X)` where `X !=1174 /// fr`, we want to check that `fr: X`. If not, that's either an1175 /// error, or something we have to propagate to our creator.1176 ///1177 /// Things that are to be propagated are accumulated into the1178 /// `outlives_requirements` vector.1179 #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]1180 fn check_universal_region(1181 &self,1182 longer_fr: RegionVid,1183 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1184 errors_buffer: &mut RegionErrors<'tcx>,1185 ) {1186 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);11871188 // Because this free region must be in the ROOT universe, we1189 // know it cannot contain any bound universes.1190 assert!(self.max_nameable_universe(longer_fr_scc).is_root());11911192 // Only check all of the relations for the main representative of each1193 // SCC, otherwise just check that we outlive said representative. This1194 // reduces the number of redundant relations propagated out of1195 // closures.1196 // Note that the representative will be a universal region if there is1197 // one in this SCC, so we will always check the representative here.1198 let representative = self.scc_representative(longer_fr_scc);1199 if representative != longer_fr {1200 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(1201 longer_fr,1202 representative,1203 propagated_outlives_requirements,1204 ) {1205 errors_buffer.push(RegionErrorKind::RegionError {1206 longer_fr,1207 shorter_fr: representative,1208 fr_origin: NllRegionVariableOrigin::FreeRegion,1209 is_reported: true,1210 });1211 }1212 return;1213 }12141215 // Find every region `o` such that `fr: o`1216 // (because `fr` includes `end(o)`).1217 let mut error_reported = false;1218 for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {1219 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(1220 longer_fr,1221 shorter_fr,1222 propagated_outlives_requirements,1223 ) {1224 // We only report the first region error. Subsequent errors are hidden so as1225 // not to overwhelm the user, but we do record them so as to potentially print1226 // better diagnostics elsewhere...1227 errors_buffer.push(RegionErrorKind::RegionError {1228 longer_fr,1229 shorter_fr,1230 fr_origin: NllRegionVariableOrigin::FreeRegion,1231 is_reported: !error_reported,1232 });12331234 error_reported = true;1235 }1236 }1237 }12381239 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate1240 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an1241 /// error.1242 fn check_universal_region_relation(1243 &self,1244 longer_fr: RegionVid,1245 shorter_fr: RegionVid,1246 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1247 ) -> RegionRelationCheckResult {1248 // If it is known that `fr: o`, carry on.1249 if self.universal_region_relations.outlives(longer_fr, shorter_fr) {1250 RegionRelationCheckResult::Ok1251 } else {1252 // If we are not in a context where we can't propagate errors, or we1253 // could not shrink `fr` to something smaller, then just report an1254 // error.1255 //1256 // Note: in this case, we use the unapproximated regions to report the1257 // error. This gives better error messages in some cases.1258 self.try_propagate_universal_region_error(1259 longer_fr,1260 shorter_fr,1261 propagated_outlives_requirements,1262 )1263 }1264 }12651266 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's1267 /// creator. If we cannot, then the caller should report an error to the user.1268 fn try_propagate_universal_region_error(1269 &self,1270 longer_fr: RegionVid,1271 shorter_fr: RegionVid,1272 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,1273 ) -> RegionRelationCheckResult {1274 if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {1275 // Shrink `longer_fr` until we find some non-local regions.1276 // We'll call them `longer_fr-` -- they are ever so slightly smaller than1277 // `longer_fr`.1278 let longer_fr_minus = self.universal_region_relations.non_local_lower_bounds(longer_fr);12791280 debug!("try_propagate_universal_region_error: fr_minus={:?}", longer_fr_minus);12811282 // If we don't find a any non-local regions, we should error out as there is nothing1283 // to propagate.1284 if longer_fr_minus.is_empty() {1285 return RegionRelationCheckResult::Error;1286 }12871288 let blame_constraint = self1289 .best_blame_constraint(longer_fr, NllRegionVariableOrigin::FreeRegion, shorter_fr)1290 .0;12911292 // Grow `shorter_fr` until we find some non-local regions.1293 // We will always find at least one: `'static`. We'll call1294 // them `shorter_fr+` -- they're ever so slightly larger1295 // than `shorter_fr`.1296 let shorter_fr_plus =1297 self.universal_region_relations.non_local_upper_bounds(shorter_fr);1298 debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus);12991300 // We then create constraints `longer_fr-: shorter_fr+` that may or may not1301 // be propagated (see below).1302 let mut constraints = vec![];1303 for fr_minus in longer_fr_minus {1304 for shorter_fr_plus in &shorter_fr_plus {1305 constraints.push((fr_minus, *shorter_fr_plus));1306 }1307 }13081309 // We only need to propagate at least one of the constraints for1310 // soundness. However, we want to avoid arbitrary choices here1311 // and currently don't support returning OR constraints.1312 //1313 // If any of the `shorter_fr+` regions are already outlived by `longer_fr-`,1314 // we propagate only those.1315 //1316 // Consider this example (`'b: 'a` == `a -> b`), where we try to propagate `'d: 'a`:1317 // a --> b --> d1318 // \1319 // \-> c1320 // Here, `shorter_fr+` of `'a` == `['b, 'c]`.1321 // Propagating `'d: 'b` is correct and should occur; `'d: 'c` is redundant because of1322 // `'d: 'b` and could reject valid code.1323 //1324 // So we filter the constraints to regions already outlived by `longer_fr-`, but if1325 // the filter yields an empty set, we fall back to the original one.1326 let subset: Vec<_> = constraints1327 .iter()1328 .filter(|&&(fr_minus, shorter_fr_plus)| {1329 self.eval_outlives(fr_minus, shorter_fr_plus)1330 })1331 .copied()1332 .collect();1333 let propagated_constraints = if subset.is_empty() { constraints } else { subset };1334 debug!(1335 "try_propagate_universal_region_error: constraints={:?}",1336 propagated_constraints1337 );13381339 assert!(1340 !propagated_constraints.is_empty(),1341 "Expected at least one constraint to propagate here"1342 );13431344 for (fr_minus, fr_plus) in propagated_constraints {1345 // Push the constraint `long_fr-: shorter_fr+`1346 propagated_outlives_requirements.push(ClosureOutlivesRequirement {1347 subject: ClosureOutlivesSubject::Region(fr_minus),1348 outlived_free_region: fr_plus,1349 blame_span: blame_constraint.cause.span,1350 category: blame_constraint.category,1351 });1352 }1353 return RegionRelationCheckResult::Propagated;1354 }13551356 RegionRelationCheckResult::Error1357 }13581359 fn check_bound_universal_region(1360 &self,1361 longer_fr: RegionVid,1362 placeholder: ty::PlaceholderRegion<'tcx>,1363 errors_buffer: &mut RegionErrors<'tcx>,1364 ) {1365 debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);13661367 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);1368 debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);13691370 // If we have some bound universal region `'a`, then the only1371 // elements it can contain is itself -- we don't know anything1372 // else about it!1373 if let Some(error_element) = self1374 .scc_values1375 .elements_contained_in(longer_fr_scc)1376 .find(|e| *e != RegionElement::PlaceholderRegion(placeholder))1377 {1378 let illegally_outlived_r = self.region_from_element(longer_fr, &error_element);1379 // Stop after the first error, it gets too noisy otherwise, and does not provide more information.1380 errors_buffer.push(RegionErrorKind::PlaceholderOutlivesIllegalRegion {1381 longer_fr,1382 illegally_outlived_r,1383 });1384 } else {1385 debug!("check_bound_universal_region: all bounds satisfied");1386 }1387 }13881389 pub(crate) fn constraint_path_between_regions(1390 &self,1391 from_region: RegionVid,1392 to_region: RegionVid,1393 ) -> Option<Vec<OutlivesConstraint<'tcx>>> {1394 if from_region == to_region {1395 bug!("Tried to find a path between {from_region:?} and itself!");1396 }1397 self.constraint_path_to(from_region, |to| to == to_region, true).map(|o| o.0)1398 }13991400 /// Walks the graph of constraints (where `'a: 'b` is considered1401 /// an edge `'a -> 'b`) to find a path from `from_region` to1402 /// `to_region`.1403 ///1404 /// Returns: a series of constraints as well as the region `R`1405 /// that passed the target test.1406 /// If `include_static_outlives_all` is `true`, then the synthetic1407 /// outlives constraints `'static -> a` for every region `a` are1408 /// considered in the search, otherwise they are ignored.1409 #[instrument(skip(self, target_test), ret)]1410 pub(crate) fn constraint_path_to(1411 &self,1412 from_region: RegionVid,1413 target_test: impl Fn(RegionVid) -> bool,1414 include_placeholder_static: bool,1415 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {1416 self.find_constraint_path_between_regions_inner(1417 true,1418 from_region,1419 &target_test,1420 include_placeholder_static,1421 )1422 .or_else(|| {1423 self.find_constraint_path_between_regions_inner(1424 false,1425 from_region,1426 &target_test,1427 include_placeholder_static,1428 )1429 })1430 }14311432 /// The constraints we get from equating the hidden type of each use of an opaque1433 /// with its final hidden type may end up getting preferred over other, potentially1434 /// longer constraint paths.1435 ///1436 /// Given that we compute the final hidden type by relying on this existing constraint1437 /// path, this can easily end up hiding the actual reason for why we require these regions1438 /// to be equal.1439 ///1440 /// To handle this, we first look at the path while ignoring these constraints and then1441 /// retry while considering them. This is not perfect, as the `from_region` may have already1442 /// been partially related to its argument region, so while we rely on a member constraint1443 /// to get a complete path, the most relevant step of that path already existed before then.1444 fn find_constraint_path_between_regions_inner(1445 &self,1446 ignore_opaque_type_constraints: bool,1447 from_region: RegionVid,1448 target_test: impl Fn(RegionVid) -> bool,1449 include_placeholder_static: bool,1450 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {1451 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);1452 context[from_region] = Trace::StartRegion;14531454 let fr_static = self.universal_regions().fr_static;14551456 // Use a deque so that we do a breadth-first search. We will1457 // stop at the first match, which ought to be the shortest1458 // path (fewest constraints).1459 let mut deque = VecDeque::new();1460 deque.push_back(from_region);14611462 while let Some(r) = deque.pop_front() {1463 debug!(1464 "constraint_path_to: from_region={:?} r={:?} value={}",1465 from_region,1466 r,1467 self.region_value_str(r),1468 );14691470 // Check if we reached the region we were looking for. If so,1471 // we can reconstruct the path that led to it and return it.1472 if target_test(r) {1473 let mut result = vec![];1474 let mut p = r;1475 // This loop is cold and runs at the end, which is why we delay1476 // `OutlivesConstraint` construction until now.1477 loop {1478 match context[p] {1479 Trace::FromGraph(c) => {1480 p = c.sup;1481 result.push(*c);1482 }14831484 Trace::FromStatic(sub) => {1485 let c = OutlivesConstraint {1486 sup: fr_static,1487 sub,1488 locations: Locations::All(DUMMY_SP),1489 span: DUMMY_SP,1490 category: ConstraintCategory::Internal,1491 variance_info: ty::VarianceDiagInfo::default(),1492 from_closure: false,1493 };1494 p = c.sup;1495 result.push(c);1496 }14971498 Trace::StartRegion => {1499 result.reverse();1500 return Some((result, r));1501 }15021503 Trace::NotVisited => {1504 bug!("found unvisited region {:?} on path to {:?}", p, r)1505 }1506 }1507 }1508 }15091510 // Otherwise, walk over the outgoing constraints and1511 // enqueue any regions we find, keeping track of how we1512 // reached them.15131514 // A constraint like `'r: 'x` can come from our constraint1515 // graph.15161517 // Always inline this closure because it can be hot.1518 let mut handle_trace = #[inline(always)]1519 |sub, trace| {1520 if let Trace::NotVisited = context[sub] {1521 context[sub] = trace;1522 deque.push_back(sub);1523 }1524 };15251526 // If this is the `'static` region and the graph's direction is normal, then set up the1527 // Edges iterator to return all regions (#53178).1528 if r == fr_static && self.constraint_graph.is_normal() {1529 for sub in self.constraint_graph.outgoing_edges_from_static() {1530 handle_trace(sub, Trace::FromStatic(sub));1531 }1532 } else {1533 let edges = self.constraint_graph.outgoing_edges_from_graph(r, &self.constraints);1534 // This loop can be hot.1535 for constraint in edges {1536 match constraint.category {1537 ConstraintCategory::OutlivesUnnameablePlaceholder(_)1538 if !include_placeholder_static =>1539 {1540 debug!("Ignoring illegal placeholder constraint: {constraint:?}");1541 continue;1542 }1543 ConstraintCategory::OpaqueType if ignore_opaque_type_constraints => {1544 debug!("Ignoring member constraint: {constraint:?}");1545 continue;1546 }1547 _ => {}1548 }15491550 debug_assert_eq!(constraint.sup, r);1551 handle_trace(constraint.sub, Trace::FromGraph(constraint));1552 }1553 }1554 }15551556 None1557 }15581559 /// Finds some region R such that `fr1: R` and `R` is live at `location`.1560 #[instrument(skip(self), level = "trace", ret)]1561 pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, location: Location) -> RegionVid {1562 trace!(scc = ?self.constraint_sccs.scc(fr1));1563 trace!(universe = ?self.max_nameable_universe(self.constraint_sccs.scc(fr1)));1564 self.constraint_path_to(fr1, |r| {1565 trace!(?r, liveness_constraints=?self.liveness_constraints.pretty_print_live_points(r));1566 self.liveness_constraints.is_live_at(r, location)1567 }, true).unwrap().11568 }15691570 /// Get the region outlived by `longer_fr` and live at `element`.1571 fn region_from_element(1572 &self,1573 longer_fr: RegionVid,1574 element: &RegionElement<'tcx>,1575 ) -> RegionVid {1576 match *element {1577 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),1578 RegionElement::RootUniversalRegion(r) => r,1579 RegionElement::PlaceholderRegion(error_placeholder) => self1580 .definitions1581 .iter_enumerated()1582 .find_map(|(r, definition)| match definition.origin {1583 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),1584 _ => None,1585 })1586 .unwrap(),1587 }1588 }15891590 /// Get the region definition of `r`.1591 pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {1592 &self.definitions[r]1593 }15941595 /// Check if the SCC of `r` contains `upper`, a free region.1596 pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {1597 let r_scc = self.constraint_sccs.scc(r);1598 self.scc_values.contains_free_region(r_scc, upper)1599 }16001601 pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {1602 &self.universal_region_relations.universal_regions1603 }16041605 /// Tries to find the best constraint to blame for the fact that1606 /// `R: from_region`, where `R` is some region that meets1607 /// `target_test`. This works by following the constraint graph,1608 /// creating a constraint path that forces `R` to outlive1609 /// `from_region`, and then finding the best choices within that1610 /// path to blame.1611 #[instrument(level = "debug", skip(self))]1612 pub(crate) fn best_blame_constraint(1613 &self,1614 from_region: RegionVid,1615 from_region_origin: NllRegionVariableOrigin<'tcx>,1616 to_region: RegionVid,1617 ) -> (BlameConstraint<'tcx>, Vec<OutlivesConstraint<'tcx>>) {1618 assert!(from_region != to_region, "Trying to blame a region for itself!");16191620 let path = self.constraint_path_between_regions(from_region, to_region).unwrap();16211622 // If we are passing through a constraint added because we reached an unnameable placeholder `'unnameable`,1623 // redirect search towards `'unnameable`.1624 let due_to_placeholder_outlives = path.iter().find_map(|c| {1625 if let ConstraintCategory::OutlivesUnnameablePlaceholder(unnameable) = c.category {1626 Some(unnameable)1627 } else {1628 None1629 }1630 });16311632 // Edge case: it's possible that `'from_region` is an unnameable placeholder.1633 let path = if let Some(unnameable) = due_to_placeholder_outlives1634 && unnameable != from_region1635 {1636 // We ignore the extra edges due to unnameable placeholders to get1637 // an explanation that was present in the original constraint graph.1638 self.constraint_path_to(from_region, |r| r == unnameable, false).unwrap().01639 } else {1640 path1641 };16421643 debug!(1644 "path={:#?}",1645 path.iter()1646 .map(|c| format!(1647 "{:?} ({:?}: {:?})",1648 c,1649 self.constraint_sccs.scc(c.sup),1650 self.constraint_sccs.scc(c.sub),1651 ))1652 .collect::<Vec<_>>()1653 );16541655 // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.1656 // Instead, we use it to produce an improved `ObligationCauseCode`.1657 // FIXME - determine what we should do if we encounter multiple1658 // `ConstraintCategory::Predicate` constraints. Currently, we just pick the first one.1659 let cause_code = path1660 .iter()1661 .find_map(|constraint| {1662 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {1663 // We currently do not store the `DefId` in the `ConstraintCategory`1664 // for performances reasons. The error reporting code used by NLL only1665 // uses the span, so this doesn't cause any problems at the moment.1666 Some(ObligationCauseCode::WhereClause(CRATE_DEF_ID.to_def_id(), predicate_span))1667 } else {1668 None1669 }1670 })1671 .unwrap_or_else(|| ObligationCauseCode::Misc);16721673 // When reporting an error, there is typically a chain of constraints leading from some1674 // "source" region which must outlive some "target" region.1675 // In most cases, we prefer to "blame" the constraints closer to the target --1676 // but there is one exception. When constraints arise from higher-ranked subtyping,1677 // we generally prefer to blame the source value,1678 // as the "target" in this case tends to be some type annotation that the user gave.1679 // Therefore, if we find that the region origin is some instantiation1680 // of a higher-ranked region, we start our search from the "source" point1681 // rather than the "target", and we also tweak a few other things.1682 //1683 // An example might be this bit of Rust code:1684 //1685 // ```rust1686 // let x: fn(&'static ()) = |_| {};1687 // let y: for<'a> fn(&'a ()) = x;1688 // ```1689 //1690 // In MIR, this will be converted into a combination of assignments and type ascriptions.1691 // In particular, the 'static is imposed through a type ascription:1692 //1693 // ```rust1694 // x = ...;1695 // AscribeUserType(x, fn(&'static ())1696 // y = x;1697 // ```1698 //1699 // We wind up ultimately with constraints like1700 //1701 // ```rust1702 // !a: 'temp1 // from the `y = x` statement1703 // 'temp1: 'temp21704 // 'temp2: 'static // from the AscribeUserType1705 // ```1706 //1707 // and here we prefer to blame the source (the y = x statement).1708 let blame_source = match from_region_origin {1709 NllRegionVariableOrigin::FreeRegion => true,1710 NllRegionVariableOrigin::Placeholder(_) => false,1711 // `'existential: 'whatever` never results in a region error by itself.1712 // We may always infer it to `'static` afterall. This means while an error1713 // path may go through an existential, these existentials are never the1714 // `from_region`.1715 NllRegionVariableOrigin::Existential { name: _ } => {1716 unreachable!("existentials can outlive everything")1717 }1718 };17191720 // To pick a constraint to blame, we organize constraints by how interesting we expect them1721 // to be in diagnostics, then pick the most interesting one closest to either the source or1722 // the target on our constraint path.1723 let constraint_interest = |constraint: &OutlivesConstraint<'tcx>| {1724 // Try to avoid blaming constraints from desugarings, since they may not clearly match1725 // match what users have written. As an exception, allow blaming returns generated by1726 // `?` desugaring, since the correspondence is fairly clear.1727 let category = if let Some(kind) = constraint.span.desugaring_kind()1728 && (kind != DesugaringKind::QuestionMark1729 || !matches!(constraint.category, ConstraintCategory::Return(_)))1730 {1731 ConstraintCategory::Boring1732 } else {1733 constraint.category1734 };17351736 let interest = match category {1737 // Returns usually provide a type to blame and have specially written diagnostics,1738 // so prioritize them.1739 ConstraintCategory::Return(_) => 0,1740 // Unsizing coercions are interesting, since we have a note for that:1741 // `BorrowExplanation::add_object_lifetime_default_note`.1742 // FIXME(dianne): That note shouldn't depend on a coercion being blamed; see issue1743 // #131008 for an example of where we currently don't emit it but should.1744 // Once the note is handled properly, this case should be removed. Until then, it1745 // should be as limited as possible; the note is prone to false positives and this1746 // constraint usually isn't best to blame.1747 ConstraintCategory::Cast {1748 is_raw_ptr_dyn_type_cast: _,1749 unsize_to: Some(unsize_ty),1750 is_implicit_coercion: true,1751 } if to_region == self.universal_regions().fr_static1752 // Mirror the note's condition, to minimize how often this diverts blame.1753 && let ty::Adt(_, args) = unsize_ty.kind()1754 && args.iter().any(|arg| arg.as_type().is_some_and(|ty| ty.is_trait()))1755 // Mimic old logic for this, to minimize false positives in tests.1756 && !path1757 .iter()1758 .any(|c| matches!(c.category, ConstraintCategory::TypeAnnotation(_))) =>1759 {1760 11761 }1762 // Between other interesting constraints, order by their position on the `path`.1763 ConstraintCategory::Yield1764 | ConstraintCategory::UseAsConst1765 | ConstraintCategory::UseAsStatic1766 | ConstraintCategory::TypeAnnotation(1767 AnnotationSource::Ascription1768 | AnnotationSource::Declaration1769 | AnnotationSource::OpaqueCast,1770 )1771 | ConstraintCategory::Cast { .. }1772 | ConstraintCategory::CallArgument(_)1773 | ConstraintCategory::CopyBound1774 | ConstraintCategory::SizedBound1775 | ConstraintCategory::Assignment1776 | ConstraintCategory::Usage1777 | ConstraintCategory::ClosureUpvar(_) => 2,1778 // Generic arguments are unlikely to be what relates regions together1779 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => 3,1780 // We handle predicates and opaque types specially; don't prioritize them here.1781 ConstraintCategory::Predicate(_) | ConstraintCategory::OpaqueType => 4,1782 // `Boring` constraints can correspond to user-written code and have useful spans,1783 // but don't provide any other useful information for diagnostics.1784 ConstraintCategory::Boring => 5,1785 // `BoringNoLocation` constraints can point to user-written code, but are less1786 // specific, and are not used for relations that would make sense to blame.1787 ConstraintCategory::BoringNoLocation => 6,1788 // Do not blame internal constraints if we can avoid it. Never blame1789 // the `'region: 'static` constraints introduced by placeholder outlives.1790 ConstraintCategory::Internal => 7,1791 ConstraintCategory::OutlivesUnnameablePlaceholder(_) => 8,1792 ConstraintCategory::SolverRegionConstraint(_) => 9,1793 };17941795 debug!("constraint {constraint:?} category: {category:?}, interest: {interest:?}");17961797 interest1798 };17991800 let best_choice = if blame_source {1801 path.iter().enumerate().rev().min_by_key(|(_, c)| constraint_interest(c)).unwrap().01802 } else {1803 path.iter().enumerate().min_by_key(|(_, c)| constraint_interest(c)).unwrap().01804 };18051806 debug!(?best_choice, ?blame_source);18071808 let best_constraint = if let Some(next) = path.get(best_choice + 1)1809 && matches!(path[best_choice].category, ConstraintCategory::Return(_))1810 && next.category == ConstraintCategory::OpaqueType1811 {1812 // The return expression is being influenced by the return type being1813 // impl Trait, point at the return type and not the return expr.1814 *next1815 } else if path[best_choice].category == ConstraintCategory::Return(ReturnConstraint::Normal)1816 && let Some(field) = path.iter().find_map(|p| {1817 if let ConstraintCategory::ClosureUpvar(f) = p.category { Some(f) } else { None }1818 })1819 {1820 OutlivesConstraint {1821 category: ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field)),1822 ..path[best_choice]1823 }1824 } else {1825 path[best_choice]1826 };18271828 assert!(1829 !matches!(1830 best_constraint.category,1831 ConstraintCategory::OutlivesUnnameablePlaceholder(_)1832 ),1833 "Illegal placeholder constraint blamed; should have redirected to other region relation"1834 );18351836 let blame_constraint = BlameConstraint {1837 category: best_constraint.category,1838 from_closure: best_constraint.from_closure,1839 cause: ObligationCause::new(best_constraint.span, CRATE_DEF_ID, cause_code.clone()),1840 variance_info: best_constraint.variance_info,1841 };1842 (blame_constraint, path)1843 }18441845 pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {1846 // Query canonicalization can create local superuniverses (for example in1847 // `InferCtx::query_response_instantiation_guess`), but they don't have an associated1848 // `UniverseInfo` explaining why they were created.1849 // This can cause ICEs if these causes are accessed in diagnostics, for example in issue1850 // #114907 where this happens via liveness and dropck outlives results.1851 // Therefore, we return a default value in case that happens, which should at worst emit a1852 // suboptimal error, instead of the ICE.1853 self.universe_causes.get(&universe).cloned().unwrap_or_else(UniverseInfo::other)1854 }18551856 /// Tries to find the terminator of the loop in which the region 'r' resides.1857 /// Returns the location of the terminator if found.1858 pub(crate) fn find_loop_terminator_location(1859 &self,1860 r: RegionVid,1861 body: &Body<'_>,1862 ) -> Option<Location> {1863 let scc = self.constraint_sccs.scc(r);1864 let locations = self.scc_values.locations_outlived_by(scc);1865 for location in locations {1866 let bb = &body[location.block];1867 if let Some(terminator) = &bb.terminator1868 // terminator of a loop should be TerminatorKind::FalseUnwind1869 && let TerminatorKind::FalseUnwind { .. } = terminator.kind1870 {1871 return Some(location);1872 }1873 }1874 None1875 }18761877 /// Access to the SCC constraint graph.1878 /// This can be used to quickly under-approximate the regions which are equal to each other1879 /// and their relative orderings.1880 // This is `pub` because it's used by unstable external borrowck data users, see `consumers.rs`.1881 pub fn constraint_sccs(&self) -> &ConstraintSccs {1882 &self.constraint_sccs1883 }18841885 /// Returns the representative `RegionVid` for a given SCC.1886 /// See `RegionTracker` for how a region variable ID is chosen.1887 ///1888 /// It is a hacky way to manage checking regions for equality,1889 /// since we can 'canonicalize' each region to the representative1890 /// of its SCC and be sure that -- if they have the same repr --1891 /// they *must* be equal (though not having the same repr does not1892 /// mean they are unequal).1893 fn scc_representative(&self, scc: ConstraintSccIndex) -> RegionVid {1894 self.scc_annotations[scc].representative.rvid()1895 }18961897 pub(crate) fn liveness_constraints(&self) -> &LivenessValues {1898 &self.liveness_constraints1899 }19001901 /// When using `-Zpolonius=next`, records the given live loans for the loan scopes and active1902 /// loans dataflow computations.1903 pub(crate) fn record_live_loans(&mut self, live_loans: LiveLoans) {1904 self.liveness_constraints.record_live_loans(live_loans);1905 }19061907 /// Returns whether the `loan_idx` is live at the given `location`: whether its issuing1908 /// region is contained within the type of a variable that is live at this point.1909 /// Note: for now, the sets of live loans is only available when using `-Zpolonius=next`.1910 pub(crate) fn is_loan_live_at(&self, loan_idx: BorrowIndex, location: Location) -> bool {1911 let point = self.liveness_constraints.point_from_location(location);1912 self.liveness_constraints.is_loan_live_at(loan_idx, point)1913 }1914}19151916#[derive(Clone, Debug)]1917pub(crate) struct BlameConstraint<'tcx> {1918 pub category: ConstraintCategory<'tcx>,1919 pub from_closure: bool,1920 pub cause: ObligationCause<'tcx>,1921 pub variance_info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,1922}
Findings
✓ No findings reported for this file.