1 use std::collections::VecDeque;
4 use rustc_data_structures::binary_search_util;
5 use rustc_data_structures::frozen::Frozen;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_data_structures::graph::scc::Sccs;
8 use rustc_errors::Diagnostic;
9 use rustc_hir::def_id::CRATE_DEF_ID;
10 use rustc_hir::CRATE_HIR_ID;
11 use rustc_index::vec::IndexVec;
12 use rustc_infer::infer::outlives::test_type_match;
13 use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound, VerifyIfEq};
14 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin};
15 use rustc_middle::mir::{
16 Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
17 ConstraintCategory, Local, Location, ReturnConstraint, TerminatorKind,
19 use rustc_middle::traits::ObligationCause;
20 use rustc_middle::traits::ObligationCauseCode;
21 use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable};
26 graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
28 diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
29 member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
30 nll::{PoloniusOutput, ToRegionVid},
31 region_infer::reverse_sccs::ReverseSccGraph,
32 region_infer::values::{
33 LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
36 type_check::{free_region_relations::UniversalRegionRelations, Locations},
37 universal_regions::UniversalRegions,
47 pub struct RegionInferenceContext<'tcx> {
48 pub var_infos: VarInfos,
50 /// Contains the definition for every region variable. Region
51 /// variables are identified by their index (`RegionVid`). The
52 /// definition contains information about where the region came
53 /// from as well as its final inferred value.
54 definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
56 /// The liveness constraints added to each region. For most
57 /// regions, these start out empty and steadily grow, though for
58 /// each universally quantified region R they start out containing
59 /// the entire CFG and `end(R)`.
60 liveness_constraints: LivenessValues<RegionVid>,
62 /// The outlives constraints computed by the type-check.
63 constraints: Frozen<OutlivesConstraintSet<'tcx>>,
65 /// The constraint-set, but in graph form, making it easy to traverse
66 /// the constraints adjacent to a particular region. Used to construct
67 /// the SCC (see `constraint_sccs`) and for error reporting.
68 constraint_graph: Frozen<NormalConstraintGraph>,
70 /// The SCC computed from `constraints` and the constraint
71 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
72 /// compute the values of each region.
73 constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
75 /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if
76 /// `B: A`. This is used to compute the universal regions that are required
77 /// to outlive a given SCC. Computed lazily.
78 rev_scc_graph: Option<Rc<ReverseSccGraph>>,
80 /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
81 member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
83 /// Records the member constraints that we applied to each scc.
84 /// This is useful for error reporting. Once constraint
85 /// propagation is done, this vector is sorted according to
86 /// `member_region_scc`.
87 member_constraints_applied: Vec<AppliedMemberConstraint>,
89 /// Map universe indexes to information on why we created it.
90 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
92 /// Contains the minimum universe of any variable within the same
93 /// SCC. We will ensure that no SCC contains values that are not
94 /// visible from this index.
95 scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
97 /// Contains a "representative" from each SCC. This will be the
98 /// minimal RegionVid belonging to that universe. It is used as a
99 /// kind of hacky way to manage checking outlives relationships,
100 /// since we can 'canonicalize' each region to the representative
101 /// of its SCC and be sure that -- if they have the same repr --
102 /// they *must* be equal (though not having the same repr does not
103 /// mean they are unequal).
104 scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
106 /// The final inferred values of the region variables; we compute
107 /// one value per SCC. To get the value for any given *region*,
108 /// you first find which scc it is a part of.
109 scc_values: RegionValues<ConstraintSccIndex>,
111 /// Type constraints that we check after solving.
112 type_tests: Vec<TypeTest<'tcx>>,
114 /// Information about the universally quantified regions in scope
115 /// on this function.
116 universal_regions: Rc<UniversalRegions<'tcx>>,
118 /// Information about how the universally quantified regions in
119 /// scope on this function relate to one another.
120 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
123 /// Each time that `apply_member_constraint` is successful, it appends
124 /// one of these structs to the `member_constraints_applied` field.
125 /// This is used in error reporting to trace out what happened.
127 /// The way that `apply_member_constraint` works is that it effectively
128 /// adds a new lower bound to the SCC it is analyzing: so you wind up
129 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
130 /// minimal viable option.
132 pub(crate) struct AppliedMemberConstraint {
133 /// The SCC that was affected. (The "member region".)
135 /// The vector if `AppliedMemberConstraint` elements is kept sorted
137 pub(crate) member_region_scc: ConstraintSccIndex,
139 /// The "best option" that `apply_member_constraint` found -- this was
140 /// added as an "ad-hoc" lower-bound to `member_region_scc`.
141 pub(crate) min_choice: ty::RegionVid,
143 /// The "member constraint index" -- we can find out details about
144 /// the constraint from
145 /// `set.member_constraints[member_constraint_index]`.
146 pub(crate) member_constraint_index: NllMemberConstraintIndex,
149 pub(crate) struct RegionDefinition<'tcx> {
150 /// What kind of variable is this -- a free region? existential
151 /// variable? etc. (See the `NllRegionVariableOrigin` for more
153 pub(crate) origin: NllRegionVariableOrigin,
155 /// Which universe is this region variable defined in? This is
156 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
157 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
158 /// the variable for `'a` in a fresh universe that extends ROOT.
159 pub(crate) universe: ty::UniverseIndex,
161 /// If this is 'static or an early-bound region, then this is
162 /// `Some(X)` where `X` is the name of the region.
163 pub(crate) external_name: Option<ty::Region<'tcx>>,
166 /// N.B., the variants in `Cause` are intentionally ordered. Lower
167 /// values are preferred when it comes to error messages. Do not
168 /// reorder willy nilly.
169 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
170 pub(crate) enum Cause {
171 /// point inserted because Local was live at the given Location
172 LiveVar(Local, Location),
174 /// point inserted because Local was dropped at the given Location
175 DropVar(Local, Location),
178 /// A "type test" corresponds to an outlives constraint between a type
179 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
180 /// translated from the `Verify` region constraints in the ordinary
181 /// inference context.
183 /// These sorts of constraints are handled differently than ordinary
184 /// constraints, at least at present. During type checking, the
185 /// `InferCtxt::process_registered_region_obligations` method will
186 /// attempt to convert a type test like `T: 'x` into an ordinary
187 /// outlives constraint when possible (for example, `&'a T: 'b` will
188 /// be converted into `'a: 'b` and registered as a `Constraint`).
190 /// In some cases, however, there are outlives relationships that are
191 /// not converted into a region constraint, but rather into one of
192 /// these "type tests". The distinction is that a type test does not
193 /// influence the inference result, but instead just examines the
194 /// values that we ultimately inferred for each region variable and
195 /// checks that they meet certain extra criteria. If not, an error
198 /// One reason for this is that these type tests typically boil down
199 /// to a check like `'a: 'x` where `'a` is a universally quantified
200 /// region -- and therefore not one whose value is really meant to be
201 /// *inferred*, precisely (this is not always the case: one can have a
202 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
203 /// inference variable). Another reason is that these type tests can
204 /// involve *disjunction* -- that is, they can be satisfied in more
207 /// For more information about this translation, see
208 /// `InferCtxt::process_registered_region_obligations` and
209 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
210 #[derive(Clone, Debug)]
211 pub struct TypeTest<'tcx> {
212 /// The type `T` that must outlive the region.
213 pub generic_kind: GenericKind<'tcx>,
215 /// The region `'x` that the type must outlive.
216 pub lower_bound: RegionVid,
218 /// The span to blame.
221 /// A test which, if met by the region `'x`, proves that this type
222 /// constraint is satisfied.
223 pub verify_bound: VerifyBound<'tcx>,
226 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
227 /// environment). If we can't, it is an error.
228 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
229 enum RegionRelationCheckResult {
235 #[derive(Clone, PartialEq, Eq, Debug)]
238 FromOutlivesConstraint(OutlivesConstraint<'tcx>),
242 #[derive(Clone, PartialEq, Eq, Debug)]
243 pub enum ExtraConstraintInfo {
244 PlaceholderFromPredicate(Span),
247 impl<'tcx> RegionInferenceContext<'tcx> {
248 /// Creates a new region inference context with a total of
249 /// `num_region_variables` valid inference variables; the first N
250 /// of those will be constant regions representing the free
251 /// regions defined in `universal_regions`.
253 /// The `outlives_constraints` and `type_tests` are an initial set
254 /// of constraints produced by the MIR type check.
257 universal_regions: Rc<UniversalRegions<'tcx>>,
258 placeholder_indices: Rc<PlaceholderIndices>,
259 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
260 outlives_constraints: OutlivesConstraintSet<'tcx>,
261 member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
262 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
263 type_tests: Vec<TypeTest<'tcx>>,
264 liveness_constraints: LivenessValues<RegionVid>,
265 elements: &Rc<RegionValueElements>,
267 // Create a RegionDefinition for each inference variable.
268 let definitions: IndexVec<_, _> = var_infos
270 .map(|info| RegionDefinition::new(info.universe, info.origin))
273 let constraints = Frozen::freeze(outlives_constraints);
274 let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
275 let fr_static = universal_regions.fr_static;
276 let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
279 RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
281 for region in liveness_constraints.rows() {
282 let scc = constraint_sccs.scc(region);
283 scc_values.merge_liveness(scc, region, &liveness_constraints);
286 let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
288 let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
290 let member_constraints =
291 Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
293 let mut result = Self {
296 liveness_constraints,
302 member_constraints_applied: Vec::new(),
309 universal_region_relations,
312 result.init_free_and_bound_regions();
317 /// Each SCC is the combination of many region variables which
318 /// have been equated. Therefore, we can associate a universe with
319 /// each SCC which is minimum of all the universes of its
320 /// constituent regions -- this is because whatever value the SCC
321 /// takes on must be a value that each of the regions within the
322 /// SCC could have as well. This implies that the SCC must have
323 /// the minimum, or narrowest, universe.
324 fn compute_scc_universes(
325 constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
326 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
327 ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
328 let num_sccs = constraint_sccs.num_sccs();
329 let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
331 debug!("compute_scc_universes()");
333 // For each region R in universe U, ensure that the universe for the SCC
334 // that contains R is "no bigger" than U. This effectively sets the universe
335 // for each SCC to be the minimum of the regions within.
336 for (region_vid, region_definition) in definitions.iter_enumerated() {
337 let scc = constraint_sccs.scc(region_vid);
338 let scc_universe = &mut scc_universes[scc];
339 let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
340 if scc_min != *scc_universe {
341 *scc_universe = scc_min;
343 "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
344 because it contains {region_vid:?} in {region_universe:?}",
347 region_vid = region_vid,
348 region_universe = region_definition.universe,
353 // Walk each SCC `A` and `B` such that `A: B`
354 // and ensure that universe(A) can see universe(B).
356 // This serves to enforce the 'empty/placeholder' hierarchy
357 // (described in more detail on `RegionKind`):
362 // empty(U0) placeholder(U1)
367 // In particular, imagine we have variables R0 in U0 and R1
368 // created in U1, and constraints like this;
371 // R1: !1 // R1 outlives the placeholder in U1
372 // R1: R0 // R1 outlives R0
375 // Here, we wish for R1 to be `'static`, because it
376 // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
378 // Thanks to this loop, what happens is that the `R1: R0`
379 // constraint lowers the universe of `R1` to `U0`, which in turn
380 // means that the `R1: !1` constraint will (later) cause
381 // `R1` to become `'static`.
382 for scc_a in constraint_sccs.all_sccs() {
383 for &scc_b in constraint_sccs.successors(scc_a) {
384 let scc_universe_a = scc_universes[scc_a];
385 let scc_universe_b = scc_universes[scc_b];
386 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
387 if scc_universe_a != scc_universe_min {
388 scc_universes[scc_a] = scc_universe_min;
391 "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
392 because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
395 scc_universe_min = scc_universe_min,
396 scc_universe_b = scc_universe_b
402 debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
407 /// For each SCC, we compute a unique `RegionVid` (in fact, the
408 /// minimal one that belongs to the SCC). See
409 /// `scc_representatives` field of `RegionInferenceContext` for
411 fn compute_scc_representatives(
412 constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
413 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
414 ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
415 let num_sccs = constraints_scc.num_sccs();
416 let next_region_vid = definitions.next_index();
417 let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
419 for region_vid in definitions.indices() {
420 let scc = constraints_scc.scc(region_vid);
421 let prev_min = scc_representatives[scc];
422 scc_representatives[scc] = region_vid.min(prev_min);
428 /// Initializes the region variables for each universally
429 /// quantified region (lifetime parameter). The first N variables
430 /// always correspond to the regions appearing in the function
431 /// signature (both named and anonymous) and where-clauses. This
432 /// function iterates over those regions and initializes them with
437 /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
439 /// would initialize two variables like so:
440 /// ```ignore (illustrative)
441 /// R0 = { CFG, R0 } // 'a
442 /// R1 = { CFG, R0, R1 } // 'b
444 /// Here, R0 represents `'a`, and it contains (a) the entire CFG
445 /// and (b) any universally quantified regions that it outlives,
446 /// which in this case is just itself. R1 (`'b`) in contrast also
447 /// outlives `'a` and hence contains R0 and R1.
448 fn init_free_and_bound_regions(&mut self) {
449 // Update the names (if any)
450 for (external_name, variable) in self.universal_regions.named_universal_regions() {
452 "init_universal_regions: region {:?} has external name {:?}",
453 variable, external_name
455 self.definitions[variable].external_name = Some(external_name);
458 for variable in self.definitions.indices() {
459 let scc = self.constraint_sccs.scc(variable);
461 match self.definitions[variable].origin {
462 NllRegionVariableOrigin::FreeRegion => {
463 // For each free, universally quantified region X:
465 // Add all nodes in the CFG to liveness constraints
466 self.liveness_constraints.add_all_points(variable);
467 self.scc_values.add_all_points(scc);
469 // Add `end(X)` into the set for X.
470 self.scc_values.add_element(scc, variable);
473 NllRegionVariableOrigin::Placeholder(placeholder) => {
474 // Each placeholder region is only visible from
475 // its universe `ui` and its extensions. So we
476 // can't just add it into `scc` unless the
477 // universe of the scc can name this region.
478 let scc_universe = self.scc_universes[scc];
479 if scc_universe.can_name(placeholder.universe) {
480 self.scc_values.add_element(scc, placeholder);
483 "init_free_and_bound_regions: placeholder {:?} is \
484 not compatible with universe {:?} of its SCC {:?}",
485 placeholder, scc_universe, scc,
487 self.add_incompatible_universe(scc);
491 NllRegionVariableOrigin::Existential { .. } => {
492 // For existential, regions, nothing to do.
498 /// Returns an iterator over all the region indices.
499 pub fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
500 self.definitions.indices()
503 /// Given a universal region in scope on the MIR, returns the
504 /// corresponding index.
506 /// (Panics if `r` is not a registered universal region.)
507 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
508 self.universal_regions.to_region_vid(r)
511 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
512 pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
513 self.universal_regions.annotate(tcx, err)
516 /// Returns `true` if the region `r` contains the point `p`.
518 /// Panics if called before `solve()` executes,
519 pub(crate) fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
520 let scc = self.constraint_sccs.scc(r.to_region_vid());
521 self.scc_values.contains(scc, p)
524 /// Returns access to the value of `r` for debugging purposes.
525 pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
526 let scc = self.constraint_sccs.scc(r.to_region_vid());
527 self.scc_values.region_value_str(scc)
530 pub(crate) fn placeholders_contained_in<'a>(
533 ) -> impl Iterator<Item = ty::PlaceholderRegion> + 'a {
534 let scc = self.constraint_sccs.scc(r.to_region_vid());
535 self.scc_values.placeholders_contained_in(scc)
538 /// Returns access to the value of `r` for debugging purposes.
539 pub(crate) fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
540 let scc = self.constraint_sccs.scc(r.to_region_vid());
541 self.scc_universes[scc]
544 /// Once region solving has completed, this function will return
545 /// the member constraints that were applied to the value of a given
546 /// region `r`. See `AppliedMemberConstraint`.
547 pub(crate) fn applied_member_constraints(
550 ) -> &[AppliedMemberConstraint] {
551 let scc = self.constraint_sccs.scc(r.to_region_vid());
552 binary_search_util::binary_search_slice(
553 &self.member_constraints_applied,
554 |applied| applied.member_region_scc,
559 /// Performs region inference and report errors if we see any
560 /// unsatisfiable constraints. If this is a closure, returns the
561 /// region requirements to propagate to our creator, if any.
562 #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
565 infcx: &InferCtxt<'tcx>,
566 param_env: ty::ParamEnv<'tcx>,
568 polonius_output: Option<Rc<PoloniusOutput>>,
569 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
570 let mir_def_id = body.source.def_id();
571 self.propagate_constraints(body);
573 let mut errors_buffer = RegionErrors::new(infcx.tcx);
575 // If this is a closure, we can propagate unsatisfied
576 // `outlives_requirements` to our creator, so create a vector
577 // to store those. Otherwise, we'll pass in `None` to the
578 // functions below, which will trigger them to report errors
580 let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
582 self.check_type_tests(
586 outlives_requirements.as_mut(),
590 // In Polonius mode, the errors about missing universal region relations are in the output
591 // and need to be emitted or propagated. Otherwise, we need to check whether the
592 // constraints were too strong, and if so, emit or propagate those errors.
593 if infcx.tcx.sess.opts.unstable_opts.polonius {
594 self.check_polonius_subset_errors(
595 outlives_requirements.as_mut(),
597 polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"),
600 self.check_universal_regions(outlives_requirements.as_mut(), &mut errors_buffer);
603 if errors_buffer.is_empty() {
604 self.check_member_constraints(infcx, &mut errors_buffer);
607 let outlives_requirements = outlives_requirements.unwrap_or_default();
609 if outlives_requirements.is_empty() {
610 (None, errors_buffer)
612 let num_external_vids = self.universal_regions.num_global_and_external_regions();
614 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
620 /// Propagate the region constraints: this will grow the values
621 /// for each region variable until all the constraints are
622 /// satisfied. Note that some values may grow **too** large to be
623 /// feasible, but we check this later.
624 #[instrument(skip(self, _body), level = "debug")]
625 fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
626 debug!("constraints={:#?}", {
627 let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
628 constraints.sort_by_key(|c| (c.sup, c.sub));
631 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
635 // To propagate constraints, we walk the DAG induced by the
636 // SCC. For each SCC, we visit its successors and compute
637 // their values, then we union all those values to get our
639 let constraint_sccs = self.constraint_sccs.clone();
640 for scc in constraint_sccs.all_sccs() {
641 self.compute_value_for_scc(scc);
644 // Sort the applied member constraints so we can binary search
645 // through them later.
646 self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
649 /// Computes the value of the SCC `scc_a`, which has not yet been
650 /// computed, by unioning the values of its successors.
651 /// Assumes that all successors have been computed already
652 /// (which is assured by iterating over SCCs in dependency order).
653 #[instrument(skip(self), level = "debug")]
654 fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) {
655 let constraint_sccs = self.constraint_sccs.clone();
657 // Walk each SCC `B` such that `A: B`...
658 for &scc_b in constraint_sccs.successors(scc_a) {
661 // ...and add elements from `B` into `A`. One complication
662 // arises because of universes: If `B` contains something
663 // that `A` cannot name, then `A` can only contain `B` if
664 // it outlives static.
665 if self.universe_compatible(scc_b, scc_a) {
666 // `A` can name everything that is in `B`, so just
668 self.scc_values.add_region(scc_a, scc_b);
670 self.add_incompatible_universe(scc_a);
674 // Now take member constraints into account.
675 let member_constraints = self.member_constraints.clone();
676 for m_c_i in member_constraints.indices(scc_a) {
677 self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i));
680 debug!(value = ?self.scc_values.region_value_str(scc_a));
683 /// Invoked for each `R0 member of [R1..Rn]` constraint.
685 /// `scc` is the SCC containing R0, and `choice_regions` are the
686 /// `R1..Rn` regions -- they are always known to be universal
687 /// regions (and if that's not true, we just don't attempt to
688 /// enforce the constraint).
690 /// The current value of `scc` at the time the method is invoked
691 /// is considered a *lower bound*. If possible, we will modify
692 /// the constraint to set it equal to one of the option regions.
693 /// If we make any changes, returns true, else false.
694 #[instrument(skip(self, member_constraint_index), level = "debug")]
695 fn apply_member_constraint(
697 scc: ConstraintSccIndex,
698 member_constraint_index: NllMemberConstraintIndex,
699 choice_regions: &[ty::RegionVid],
701 // Create a mutable vector of the options. We'll try to winnow
703 let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
705 // Convert to the SCC representative: sometimes we have inference
706 // variables in the member constraint that wind up equated with
707 // universal regions. The scc representative is the minimal numbered
708 // one from the corresponding scc so it will be the universal region
710 for c_r in &mut choice_regions {
711 let scc = self.constraint_sccs.scc(*c_r);
712 *c_r = self.scc_representatives[scc];
715 // The 'member region' in a member constraint is part of the
716 // hidden type, which must be in the root universe. Therefore,
717 // it cannot have any placeholders in its value.
718 assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
720 self.scc_values.placeholders_contained_in(scc).next().is_none(),
721 "scc {:?} in a member constraint has placeholder value: {:?}",
723 self.scc_values.region_value_str(scc),
726 // The existing value for `scc` is a lower-bound. This will
727 // consist of some set `{P} + {LB}` of points `{P}` and
728 // lower-bound free regions `{LB}`. As each choice region `O`
729 // is a free region, it will outlive the points. But we can
730 // only consider the option `O` if `O: LB`.
731 choice_regions.retain(|&o_r| {
733 .universal_regions_outlived_by(scc)
734 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
736 debug!(?choice_regions, "after lb");
738 // Now find all the *upper bounds* -- that is, each UB is a
739 // free region that must outlive the member region `R0` (`UB:
740 // R0`). Therefore, we need only keep an option `O` if `UB: O`
742 let rev_scc_graph = self.reverse_scc_graph();
743 let universal_region_relations = &self.universal_region_relations;
744 for ub in rev_scc_graph.upper_bounds(scc) {
746 choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
748 debug!(?choice_regions, "after ub");
750 // If we ruled everything out, we're done.
751 if choice_regions.is_empty() {
755 // Otherwise, we need to find the minimum remaining choice, if
756 // any, and take that.
757 debug!("choice_regions remaining are {:#?}", choice_regions);
758 let Some(&min_choice) = choice_regions.iter().find(|&r1| {
759 choice_regions.iter().all(|&r2| {
760 self.universal_region_relations.outlives(r2, *r1)
763 debug!("no choice region outlived by all others");
767 let min_choice_scc = self.constraint_sccs.scc(min_choice);
768 debug!(?min_choice, ?min_choice_scc);
769 if self.scc_values.add_region(scc, min_choice_scc) {
770 self.member_constraints_applied.push(AppliedMemberConstraint {
771 member_region_scc: scc,
773 member_constraint_index,
782 /// Returns `true` if all the elements in the value of `scc_b` are nameable
783 /// in `scc_a`. Used during constraint propagation, and only once
784 /// the value of `scc_b` has been computed.
785 fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
786 let universe_a = self.scc_universes[scc_a];
788 // Quick check: if scc_b's declared universe is a subset of
789 // scc_a's declared universe (typically, both are ROOT), then
790 // it cannot contain any problematic universe elements.
791 if universe_a.can_name(self.scc_universes[scc_b]) {
795 // Otherwise, we have to iterate over the universe elements in
796 // B's value, and check whether all of them are nameable
798 self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
801 /// Extend `scc` so that it can outlive some placeholder region
802 /// from a universe it can't name; at present, the only way for
803 /// this to be true is if `scc` outlives `'static`. This is
804 /// actually stricter than necessary: ideally, we'd support bounds
805 /// like `for<'a: 'b`>` that might then allow us to approximate
806 /// `'a` with `'b` and not `'static`. But it will have to do for
808 fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
809 debug!("add_incompatible_universe(scc={:?})", scc);
811 let fr_static = self.universal_regions.fr_static;
812 self.scc_values.add_all_points(scc);
813 self.scc_values.add_element(scc, fr_static);
816 /// Once regions have been propagated, this method is used to see
817 /// whether the "type tests" produced by typeck were satisfied;
818 /// type tests encode type-outlives relationships like `T:
819 /// 'a`. See `TypeTest` for more details.
822 infcx: &InferCtxt<'tcx>,
823 param_env: ty::ParamEnv<'tcx>,
825 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
826 errors_buffer: &mut RegionErrors<'tcx>,
830 // Sometimes we register equivalent type-tests that would
831 // result in basically the exact same error being reported to
832 // the user. Avoid that.
833 let mut deduplicate_errors = FxHashSet::default();
835 for type_test in &self.type_tests {
836 debug!("check_type_test: {:?}", type_test);
838 let generic_ty = type_test.generic_kind.to_ty(tcx);
839 if self.eval_verify_bound(
843 type_test.lower_bound,
844 &type_test.verify_bound,
849 if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
850 if self.try_promote_type_test(
855 propagated_outlives_requirements,
861 // Type-test failed. Report the error.
862 let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
864 // Skip duplicate-ish errors.
865 if deduplicate_errors.insert((
867 type_test.lower_bound,
871 "check_type_test: reporting error for erased_generic_kind={:?}, \
872 lower_bound_region={:?}, \
873 type_test.span={:?}",
874 erased_generic_kind, type_test.lower_bound, type_test.span,
877 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
882 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
883 /// prove to be satisfied. If this is a closure, we will attempt to
884 /// "promote" this type-test into our `ClosureRegionRequirements` and
885 /// hence pass it up the creator. To do this, we have to phrase the
886 /// type-test in terms of external free regions, as local free
887 /// regions are not nameable by the closure's creator.
889 /// Promotion works as follows: we first check that the type `T`
890 /// contains only regions that the creator knows about. If this is
891 /// true, then -- as a consequence -- we know that all regions in
892 /// the type `T` are free regions that outlive the closure body. If
893 /// false, then promotion fails.
895 /// Once we've promoted T, we have to "promote" `'X` to some region
896 /// that is "external" to the closure. Generally speaking, a region
897 /// may be the union of some points in the closure body as well as
898 /// various free lifetimes. We can ignore the points in the closure
899 /// body: if the type T can be expressed in terms of external regions,
900 /// we know it outlives the points in the closure body. That
901 /// just leaves the free regions.
903 /// The idea then is to lower the `T: 'X` constraint into multiple
904 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
905 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
906 #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]
907 fn try_promote_type_test(
909 infcx: &InferCtxt<'tcx>,
910 param_env: ty::ParamEnv<'tcx>,
912 type_test: &TypeTest<'tcx>,
913 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
917 let TypeTest { generic_kind, lower_bound, span: _, verify_bound: _ } = type_test;
919 let generic_ty = generic_kind.to_ty(tcx);
920 let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
924 debug!("subject = {:?}", subject);
926 let r_scc = self.constraint_sccs.scc(*lower_bound);
929 "lower_bound = {:?} r_scc={:?} universe={:?}",
930 lower_bound, r_scc, self.scc_universes[r_scc]
933 // If the type test requires that `T: 'a` where `'a` is a
934 // placeholder from another universe, that effectively requires
935 // `T: 'static`, so we have to propagate that requirement.
937 // It doesn't matter *what* universe because the promoted `T` will
938 // always be in the root universe.
939 if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
940 debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
941 let static_r = self.universal_regions.fr_static;
942 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
944 outlived_free_region: static_r,
945 blame_span: type_test.span,
946 category: ConstraintCategory::Boring,
949 // we can return here -- the code below might push add'l constraints
950 // but they would all be weaker than this one.
954 // For each region outlived by lower_bound find a non-local,
955 // universal region (it may be the same region) and add it to
956 // `ClosureOutlivesRequirement`.
957 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
958 debug!("universal_region_outlived_by ur={:?}", ur);
959 // Check whether we can already prove that the "subject" outlives `ur`.
960 // If so, we don't have to propagate this requirement to our caller.
962 // To continue the example from the function, if we are trying to promote
963 // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
964 // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
965 // we check whether `T: '1` is something we *can* prove. If so, no need
966 // to propagate that requirement.
968 // This is needed because -- particularly in the case
969 // where `ur` is a local bound -- we are sometimes in a
970 // position to prove things that our caller cannot. See
971 // #53570 for an example.
972 if self.eval_verify_bound(infcx, param_env, generic_ty, ur, &type_test.verify_bound) {
976 let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
977 debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
979 // This is slightly too conservative. To show T: '1, given `'2: '1`
980 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
981 // avoid potential non-determinism we approximate this by requiring
983 for upper_bound in non_local_ub {
984 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
985 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
987 let requirement = ClosureOutlivesRequirement {
989 outlived_free_region: upper_bound,
990 blame_span: type_test.span,
991 category: ConstraintCategory::Boring,
993 debug!("try_promote_type_test: pushing {:#?}", requirement);
994 propagated_outlives_requirements.push(requirement);
1000 /// When we promote a type test `T: 'r`, we have to convert the
1001 /// type `T` into something we can store in a query result (so
1002 /// something allocated for `'tcx`). This is problematic if `ty`
1003 /// contains regions. During the course of NLL region checking, we
1004 /// will have replaced all of those regions with fresh inference
1005 /// variables. To create a test subject, we want to replace those
1006 /// inference variables with some region from the closure
1007 /// signature -- this is not always possible, so this is a
1008 /// fallible process. Presuming we do find a suitable region, we
1009 /// will use it's *external name*, which will be a `RegionKind`
1010 /// variant that can be used in query responses such as
1012 #[instrument(level = "debug", skip(self, infcx))]
1013 fn try_promote_type_test_subject(
1015 infcx: &InferCtxt<'tcx>,
1017 ) -> Option<ClosureOutlivesSubject<'tcx>> {
1018 let tcx = infcx.tcx;
1020 let ty = tcx.fold_regions(ty, |r, _depth| {
1021 let region_vid = self.to_region_vid(r);
1023 // The challenge if this. We have some region variable `r`
1024 // whose value is a set of CFG points and universal
1025 // regions. We want to find if that set is *equivalent* to
1026 // any of the named regions found in the closure.
1028 // To do so, we compute the
1029 // `non_local_universal_upper_bound`. This will be a
1030 // non-local, universal region that is greater than `r`.
1031 // However, it might not be *contained* within `r`, so
1032 // then we further check whether this bound is contained
1033 // in `r`. If so, we can say that `r` is equivalent to the
1036 // Let's work through a few examples. For these, imagine
1037 // that we have 3 non-local regions (I'll denote them as
1038 // `'static`, `'a`, and `'b`, though of course in the code
1039 // they would be represented with indices) where:
1044 // First, let's assume that `r` is some existential
1045 // variable with an inferred value `{'a, 'static}` (plus
1046 // some CFG nodes). In this case, the non-local upper
1047 // bound is `'static`, since that outlives `'a`. `'static`
1048 // is also a member of `r` and hence we consider `r`
1049 // equivalent to `'static` (and replace it with
1052 // Now let's consider the inferred value `{'a, 'b}`. This
1053 // means `r` is effectively `'a | 'b`. I'm not sure if
1054 // this can come about, actually, but assuming it did, we
1055 // would get a non-local upper bound of `'static`. Since
1056 // `'static` is not contained in `r`, we would fail to
1057 // find an equivalent.
1058 let upper_bound = self.non_local_universal_upper_bound(region_vid);
1059 if self.region_contains(region_vid, upper_bound) {
1060 self.definitions[upper_bound].external_name.unwrap_or(r)
1062 // In the case of a failure, use a `ReVar` result. This will
1063 // cause the `needs_infer` later on to return `None`.
1068 debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1070 // `needs_infer` will only be true if we failed to promote some region.
1071 if ty.needs_infer() {
1075 Some(ClosureOutlivesSubject::Ty(ty))
1078 /// Given some universal or existential region `r`, finds a
1079 /// non-local, universal region `r+` that outlives `r` at entry to (and
1080 /// exit from) the closure. In the worst case, this will be
1083 /// This is used for two purposes. First, if we are propagated
1084 /// some requirement `T: r`, we can use this method to enlarge `r`
1085 /// to something we can encode for our creator (which only knows
1086 /// about non-local, universal regions). It is also used when
1087 /// encoding `T` as part of `try_promote_type_test_subject` (see
1088 /// that fn for details).
1090 /// This is based on the result `'y` of `universal_upper_bound`,
1091 /// except that it converts further takes the non-local upper
1092 /// bound of `'y`, so that the final result is non-local.
1093 fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1094 debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1096 let lub = self.universal_upper_bound(r);
1098 // Grow further to get smallest universal region known to
1100 let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1102 debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1107 /// Returns a universally quantified region that outlives the
1108 /// value of `r` (`r` may be existentially or universally
1111 /// Since `r` is (potentially) an existential region, it has some
1112 /// value which may include (a) any number of points in the CFG
1113 /// and (b) any number of `end('x)` elements of universally
1114 /// quantified regions. To convert this into a single universal
1115 /// region we do as follows:
1117 /// - Ignore the CFG points in `'r`. All universally quantified regions
1118 /// include the CFG anyhow.
1119 /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1121 #[instrument(skip(self), level = "debug", ret)]
1122 pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1123 debug!(r = %self.region_value_str(r));
1125 // Find the smallest universal region that contains all other
1126 // universal regions within `region`.
1127 let mut lub = self.universal_regions.fr_fn_body;
1128 let r_scc = self.constraint_sccs.scc(r);
1129 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1130 lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1136 /// Like `universal_upper_bound`, but returns an approximation more suitable
1137 /// for diagnostics. If `r` contains multiple disjoint universal regions
1138 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1139 /// This corresponds to picking named regions over unnamed regions
1140 /// (e.g. picking early-bound regions over a closure late-bound region).
1142 /// This means that the returned value may not be a true upper bound, since
1143 /// only 'static is known to outlive disjoint universal regions.
1144 /// Therefore, this method should only be used in diagnostic code,
1145 /// where displaying *some* named universal region is better than
1146 /// falling back to 'static.
1147 #[instrument(level = "debug", skip(self))]
1148 pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1149 debug!("{}", self.region_value_str(r));
1151 // Find the smallest universal region that contains all other
1152 // universal regions within `region`.
1153 let mut lub = self.universal_regions.fr_fn_body;
1154 let r_scc = self.constraint_sccs.scc(r);
1155 let static_r = self.universal_regions.fr_static;
1156 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1157 let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1158 debug!(?ur, ?lub, ?new_lub);
1159 // The upper bound of two non-static regions is static: this
1160 // means we know nothing about the relationship between these
1161 // two regions. Pick a 'better' one to use when constructing
1163 if ur != static_r && lub != static_r && new_lub == static_r {
1164 // Prefer the region with an `external_name` - this
1165 // indicates that the region is early-bound, so working with
1166 // it can produce a nicer error.
1167 if self.region_definition(ur).external_name.is_some() {
1169 } else if self.region_definition(lub).external_name.is_some() {
1170 // Leave lub unchanged
1172 // If we get here, we don't have any reason to prefer
1173 // one region over the other. Just pick the
1174 // one with the lower index for now.
1175 lub = std::cmp::min(ur, lub);
1187 /// Tests if `test` is true when applied to `lower_bound` at
1189 fn eval_verify_bound(
1191 infcx: &InferCtxt<'tcx>,
1192 param_env: ty::ParamEnv<'tcx>,
1193 generic_ty: Ty<'tcx>,
1194 lower_bound: RegionVid,
1195 verify_bound: &VerifyBound<'tcx>,
1197 debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1199 match verify_bound {
1200 VerifyBound::IfEq(verify_if_eq_b) => {
1201 self.eval_if_eq(infcx, param_env, generic_ty, lower_bound, *verify_if_eq_b)
1204 VerifyBound::IsEmpty => {
1205 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1206 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1209 VerifyBound::OutlivedBy(r) => {
1210 let r_vid = self.to_region_vid(*r);
1211 self.eval_outlives(r_vid, lower_bound)
1214 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1215 self.eval_verify_bound(infcx, param_env, generic_ty, lower_bound, verify_bound)
1218 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1219 self.eval_verify_bound(infcx, param_env, generic_ty, lower_bound, verify_bound)
1226 infcx: &InferCtxt<'tcx>,
1227 param_env: ty::ParamEnv<'tcx>,
1228 generic_ty: Ty<'tcx>,
1229 lower_bound: RegionVid,
1230 verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
1232 let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
1233 let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
1234 match test_type_match::extract_verify_if_eq(
1241 let r_vid = self.to_region_vid(r);
1242 self.eval_outlives(r_vid, lower_bound)
1248 /// This is a conservative normalization procedure. It takes every
1249 /// free region in `value` and replaces it with the
1250 /// "representative" of its SCC (see `scc_representatives` field).
1251 /// We are guaranteed that if two values normalize to the same
1252 /// thing, then they are equal; this is a conservative check in
1253 /// that they could still be equal even if they normalize to
1254 /// different results. (For example, there might be two regions
1255 /// with the same value that are not in the same SCC).
1257 /// N.B., this is not an ideal approach and I would like to revisit
1258 /// it. However, it works pretty well in practice. In particular,
1259 /// this is needed to deal with projection outlives bounds like
1262 /// <T as Foo<'0>>::Item: '1
1265 /// In particular, this routine winds up being important when
1266 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1267 /// environment. In this case, if we can show that `'0 == 'a`,
1268 /// and that `'b: '1`, then we know that the clause is
1269 /// satisfied. In such cases, particularly due to limitations of
1270 /// the trait solver =), we usually wind up with a where-clause like
1271 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1272 /// a constraint, and thus ensures that they are in the same SCC.
1274 /// So why can't we do a more correct routine? Well, we could
1275 /// *almost* use the `relate_tys` code, but the way it is
1276 /// currently setup it creates inference variables to deal with
1277 /// higher-ranked things and so forth, and right now the inference
1278 /// context is not permitted to make more inference variables. So
1279 /// we use this kind of hacky solution.
1280 fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1282 T: TypeFoldable<'tcx>,
1284 tcx.fold_regions(value, |r, _db| {
1285 let vid = self.to_region_vid(r);
1286 let scc = self.constraint_sccs.scc(vid);
1287 let repr = self.scc_representatives[scc];
1288 tcx.mk_region(ty::ReVar(repr))
1292 // Evaluate whether `sup_region == sub_region`.
1293 fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1294 self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1297 // Evaluate whether `sup_region: sub_region`.
1298 #[instrument(skip(self), level = "debug", ret)]
1299 fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1301 "sup_region's value = {:?} universal={:?}",
1302 self.region_value_str(sup_region),
1303 self.universal_regions.is_universal_region(sup_region),
1306 "sub_region's value = {:?} universal={:?}",
1307 self.region_value_str(sub_region),
1308 self.universal_regions.is_universal_region(sub_region),
1311 let sub_region_scc = self.constraint_sccs.scc(sub_region);
1312 let sup_region_scc = self.constraint_sccs.scc(sup_region);
1314 // If we are checking that `'sup: 'sub`, and `'sub` contains
1315 // some placeholder that `'sup` cannot name, then this is only
1316 // true if `'sup` outlives static.
1317 if !self.universe_compatible(sub_region_scc, sup_region_scc) {
1319 "sub universe `{sub_region_scc:?}` is not nameable \
1320 by super `{sup_region_scc:?}`, promoting to static",
1323 return self.eval_outlives(sup_region, self.universal_regions.fr_static);
1326 // Both the `sub_region` and `sup_region` consist of the union
1327 // of some number of universal regions (along with the union
1328 // of various points in the CFG; ignore those points for
1329 // now). Therefore, the sup-region outlives the sub-region if,
1330 // for each universal region R1 in the sub-region, there
1331 // exists some region R2 in the sup-region that outlives R1.
1332 let universal_outlives =
1333 self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1335 .universal_regions_outlived_by(sup_region_scc)
1336 .any(|r2| self.universal_region_relations.outlives(r2, r1))
1339 if !universal_outlives {
1340 debug!("sub region contains a universal region not present in super");
1344 // Now we have to compare all the points in the sub region and make
1345 // sure they exist in the sup region.
1347 if self.universal_regions.is_universal_region(sup_region) {
1348 // Micro-opt: universal regions contain all points.
1349 debug!("super is universal and hence contains all points");
1353 debug!("comparison between points in sup/sub");
1355 self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1358 /// Once regions have been propagated, this method is used to see
1359 /// whether any of the constraints were too strong. In particular,
1360 /// we want to check for a case where a universally quantified
1361 /// region exceeded its bounds. Consider:
1363 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1365 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1366 /// and hence we establish (transitively) a constraint that
1367 /// `'a: 'b`. The `propagate_constraints` code above will
1368 /// therefore add `end('a)` into the region for `'b` -- but we
1369 /// have no evidence that `'b` outlives `'a`, so we want to report
1372 /// If `propagated_outlives_requirements` is `Some`, then we will
1373 /// push unsatisfied obligations into there. Otherwise, we'll
1374 /// report them as errors.
1375 fn check_universal_regions(
1377 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1378 errors_buffer: &mut RegionErrors<'tcx>,
1380 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1381 match fr_definition.origin {
1382 NllRegionVariableOrigin::FreeRegion => {
1383 // Go through each of the universal regions `fr` and check that
1384 // they did not grow too large, accumulating any requirements
1385 // for our caller into the `outlives_requirements` vector.
1386 self.check_universal_region(
1388 &mut propagated_outlives_requirements,
1393 NllRegionVariableOrigin::Placeholder(placeholder) => {
1394 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1397 NllRegionVariableOrigin::Existential { .. } => {
1398 // nothing to check here
1404 /// Checks if Polonius has found any unexpected free region relations.
1406 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1407 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1408 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1409 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1411 /// More details can be found in this blog post by Niko:
1412 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1414 /// In the canonical example
1416 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1418 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1419 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1420 /// constraint holds.
1422 /// If `propagated_outlives_requirements` is `Some`, then we will
1423 /// push unsatisfied obligations into there. Otherwise, we'll
1424 /// report them as errors.
1425 fn check_polonius_subset_errors(
1427 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1428 errors_buffer: &mut RegionErrors<'tcx>,
1429 polonius_output: Rc<PoloniusOutput>,
1432 "check_polonius_subset_errors: {} subset_errors",
1433 polonius_output.subset_errors.len()
1436 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1437 // declared ("known") was found by Polonius, so emit an error, or propagate the
1438 // requirements for our caller into the `propagated_outlives_requirements` vector.
1440 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1441 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1442 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1443 // and the "superset origin" is the outlived "shorter free region".
1445 // Note: Polonius will produce a subset error at every point where the unexpected
1446 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1447 // for diagnostics in the future, e.g. to point more precisely at the key locations
1448 // requiring this constraint to hold. However, the error and diagnostics code downstream
1449 // expects that these errors are not duplicated (and that they are in a certain order).
1450 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1451 // anonymous lifetimes for example, could give these names differently, while others like
1452 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1453 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1454 // CFG-location ordering.
1455 let mut subset_errors: Vec<_> = polonius_output
1458 .flat_map(|(_location, subset_errors)| subset_errors.iter())
1460 subset_errors.sort();
1461 subset_errors.dedup();
1463 for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1465 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1467 longer_fr, shorter_fr
1470 let propagated = self.try_propagate_universal_region_error(
1473 &mut propagated_outlives_requirements,
1475 if propagated == RegionRelationCheckResult::Error {
1476 errors_buffer.push(RegionErrorKind::RegionError {
1477 longer_fr: *longer_fr,
1478 shorter_fr: *shorter_fr,
1479 fr_origin: NllRegionVariableOrigin::FreeRegion,
1485 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1486 // a more complete picture on how to separate this responsibility.
1487 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1488 match fr_definition.origin {
1489 NllRegionVariableOrigin::FreeRegion => {
1490 // handled by polonius above
1493 NllRegionVariableOrigin::Placeholder(placeholder) => {
1494 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1497 NllRegionVariableOrigin::Existential { .. } => {
1498 // nothing to check here
1504 /// Checks the final value for the free region `fr` to see if it
1505 /// grew too large. In particular, examine what `end(X)` points
1506 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1507 /// fr`, we want to check that `fr: X`. If not, that's either an
1508 /// error, or something we have to propagate to our creator.
1510 /// Things that are to be propagated are accumulated into the
1511 /// `outlives_requirements` vector.
1512 #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]
1513 fn check_universal_region(
1515 longer_fr: RegionVid,
1516 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1517 errors_buffer: &mut RegionErrors<'tcx>,
1519 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1521 // Because this free region must be in the ROOT universe, we
1522 // know it cannot contain any bound universes.
1523 assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1524 debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1526 // Only check all of the relations for the main representative of each
1527 // SCC, otherwise just check that we outlive said representative. This
1528 // reduces the number of redundant relations propagated out of
1530 // Note that the representative will be a universal region if there is
1531 // one in this SCC, so we will always check the representative here.
1532 let representative = self.scc_representatives[longer_fr_scc];
1533 if representative != longer_fr {
1534 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1537 propagated_outlives_requirements,
1539 errors_buffer.push(RegionErrorKind::RegionError {
1541 shorter_fr: representative,
1542 fr_origin: NllRegionVariableOrigin::FreeRegion,
1549 // Find every region `o` such that `fr: o`
1550 // (because `fr` includes `end(o)`).
1551 let mut error_reported = false;
1552 for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1553 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1556 propagated_outlives_requirements,
1558 // We only report the first region error. Subsequent errors are hidden so as
1559 // not to overwhelm the user, but we do record them so as to potentially print
1560 // better diagnostics elsewhere...
1561 errors_buffer.push(RegionErrorKind::RegionError {
1564 fr_origin: NllRegionVariableOrigin::FreeRegion,
1565 is_reported: !error_reported,
1568 error_reported = true;
1573 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1574 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1576 fn check_universal_region_relation(
1578 longer_fr: RegionVid,
1579 shorter_fr: RegionVid,
1580 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1581 ) -> RegionRelationCheckResult {
1582 // If it is known that `fr: o`, carry on.
1583 if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1584 RegionRelationCheckResult::Ok
1586 // If we are not in a context where we can't propagate errors, or we
1587 // could not shrink `fr` to something smaller, then just report an
1590 // Note: in this case, we use the unapproximated regions to report the
1591 // error. This gives better error messages in some cases.
1592 self.try_propagate_universal_region_error(
1595 propagated_outlives_requirements,
1600 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1601 /// creator. If we cannot, then the caller should report an error to the user.
1602 fn try_propagate_universal_region_error(
1604 longer_fr: RegionVid,
1605 shorter_fr: RegionVid,
1606 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1607 ) -> RegionRelationCheckResult {
1608 if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1609 // Shrink `longer_fr` until we find a non-local region (if we do).
1610 // We'll call it `fr-` -- it's ever so slightly smaller than
1612 if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1614 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1616 let blame_span_category = self.find_outlives_blame_span(
1618 NllRegionVariableOrigin::FreeRegion,
1622 // Grow `shorter_fr` until we find some non-local regions. (We
1623 // always will.) We'll call them `shorter_fr+` -- they're ever
1624 // so slightly larger than `shorter_fr`.
1625 let shorter_fr_plus =
1626 self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1628 "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1631 for fr in shorter_fr_plus {
1632 // Push the constraint `fr-: shorter_fr+`
1633 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1634 subject: ClosureOutlivesSubject::Region(fr_minus),
1635 outlived_free_region: fr,
1636 blame_span: blame_span_category.1.span,
1637 category: blame_span_category.0,
1640 return RegionRelationCheckResult::Propagated;
1644 RegionRelationCheckResult::Error
1647 fn check_bound_universal_region(
1649 longer_fr: RegionVid,
1650 placeholder: ty::PlaceholderRegion,
1651 errors_buffer: &mut RegionErrors<'tcx>,
1653 debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1655 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1656 debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1658 for error_element in self.scc_values.elements_contained_in(longer_fr_scc) {
1659 match error_element {
1660 RegionElement::Location(_) | RegionElement::RootUniversalRegion(_) => {}
1661 // If we have some bound universal region `'a`, then the only
1662 // elements it can contain is itself -- we don't know anything
1664 RegionElement::PlaceholderRegion(placeholder1) => {
1665 if placeholder == placeholder1 {
1671 errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1677 // Stop after the first error, it gets too noisy otherwise, and does not provide more information.
1680 debug!("check_bound_universal_region: all bounds satisfied");
1683 #[instrument(level = "debug", skip(self, infcx, errors_buffer))]
1684 fn check_member_constraints(
1686 infcx: &InferCtxt<'tcx>,
1687 errors_buffer: &mut RegionErrors<'tcx>,
1689 let member_constraints = self.member_constraints.clone();
1690 for m_c_i in member_constraints.all_indices() {
1692 let m_c = &member_constraints[m_c_i];
1693 let member_region_vid = m_c.member_region_vid;
1696 value = ?self.region_value_str(member_region_vid),
1698 let choice_regions = member_constraints.choice_regions(m_c_i);
1699 debug!(?choice_regions);
1701 // Did the member region wind up equal to any of the option regions?
1703 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1705 debug!("evaluated as equal to {:?}", o);
1709 // If not, report an error.
1710 let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1711 errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1712 span: m_c.definition_span,
1713 hidden_ty: m_c.hidden_ty,
1720 /// We have a constraint `fr1: fr2` that is not satisfied, where
1721 /// `fr2` represents some universal region. Here, `r` is some
1722 /// region where we know that `fr1: r` and this function has the
1723 /// job of determining whether `r` is "to blame" for the fact that
1724 /// `fr1: fr2` is required.
1726 /// This is true under two conditions:
1729 /// - `fr2` is `'static` and `r` is some placeholder in a universe
1730 /// that cannot be named by `fr1`; in that case, we will require
1731 /// that `fr1: 'static` because it is the only way to `fr1: r` to
1732 /// be satisfied. (See `add_incompatible_universe`.)
1733 pub(crate) fn provides_universal_region(
1739 debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1742 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1745 debug!("provides_universal_region: result = {:?}", result);
1749 /// If `r2` represents a placeholder region, then this returns
1750 /// `true` if `r1` cannot name that placeholder in its
1751 /// value; otherwise, returns `false`.
1752 pub(crate) fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1753 debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1755 match self.definitions[r2].origin {
1756 NllRegionVariableOrigin::Placeholder(placeholder) => {
1757 let universe1 = self.definitions[r1].universe;
1759 "cannot_name_value_of: universe1={:?} placeholder={:?}",
1760 universe1, placeholder
1762 universe1.cannot_name(placeholder.universe)
1765 NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { .. } => {
1771 /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1772 pub(crate) fn find_outlives_blame_span(
1775 fr1_origin: NllRegionVariableOrigin,
1777 ) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
1778 let BlameConstraint { category, cause, .. } = self
1779 .best_blame_constraint(fr1, fr1_origin, |r| self.provides_universal_region(r, fr1, fr2))
1784 /// Walks the graph of constraints (where `'a: 'b` is considered
1785 /// an edge `'a -> 'b`) to find all paths from `from_region` to
1786 /// `to_region`. The paths are accumulated into the vector
1787 /// `results`. The paths are stored as a series of
1788 /// `ConstraintIndex` values -- in other words, a list of *edges*.
1790 /// Returns: a series of constraints as well as the region `R`
1791 /// that passed the target test.
1792 pub(crate) fn find_constraint_paths_between_regions(
1794 from_region: RegionVid,
1795 target_test: impl Fn(RegionVid) -> bool,
1796 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1797 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1798 context[from_region] = Trace::StartRegion;
1800 // Use a deque so that we do a breadth-first search. We will
1801 // stop at the first match, which ought to be the shortest
1802 // path (fewest constraints).
1803 let mut deque = VecDeque::new();
1804 deque.push_back(from_region);
1806 while let Some(r) = deque.pop_front() {
1808 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1811 self.region_value_str(r),
1814 // Check if we reached the region we were looking for. If so,
1815 // we can reconstruct the path that led to it and return it.
1817 let mut result = vec![];
1820 match context[p].clone() {
1821 Trace::NotVisited => {
1822 bug!("found unvisited region {:?} on path to {:?}", p, r)
1825 Trace::FromOutlivesConstraint(c) => {
1830 Trace::StartRegion => {
1832 return Some((result, r));
1838 // Otherwise, walk over the outgoing constraints and
1839 // enqueue any regions we find, keeping track of how we
1842 // A constraint like `'r: 'x` can come from our constraint
1844 let fr_static = self.universal_regions.fr_static;
1845 let outgoing_edges_from_graph =
1846 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1848 // Always inline this closure because it can be hot.
1849 let mut handle_constraint = #[inline(always)]
1850 |constraint: OutlivesConstraint<'tcx>| {
1851 debug_assert_eq!(constraint.sup, r);
1852 let sub_region = constraint.sub;
1853 if let Trace::NotVisited = context[sub_region] {
1854 context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1855 deque.push_back(sub_region);
1859 // This loop can be hot.
1860 for constraint in outgoing_edges_from_graph {
1861 handle_constraint(constraint);
1864 // Member constraints can also give rise to `'r: 'x` edges that
1865 // were not part of the graph initially, so watch out for those.
1866 // (But they are extremely rare; this loop is very cold.)
1867 for constraint in self.applied_member_constraints(r) {
1868 let p_c = &self.member_constraints[constraint.member_constraint_index];
1869 let constraint = OutlivesConstraint {
1871 sub: constraint.min_choice,
1872 locations: Locations::All(p_c.definition_span),
1873 span: p_c.definition_span,
1874 category: ConstraintCategory::OpaqueType,
1875 variance_info: ty::VarianceDiagInfo::default(),
1876 from_closure: false,
1878 handle_constraint(constraint);
1885 /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1886 #[instrument(skip(self), level = "trace", ret)]
1887 pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1888 trace!(scc = ?self.constraint_sccs.scc(fr1));
1889 trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1890 self.find_constraint_paths_between_regions(fr1, |r| {
1891 // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1892 trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1893 self.liveness_constraints.contains(r, elem)
1896 // If we fail to find that, we may find some `r` such that
1897 // `fr1: r` and `r` is a placeholder from some universe
1898 // `fr1` cannot name. This would force `fr1` to be
1900 self.find_constraint_paths_between_regions(fr1, |r| {
1901 self.cannot_name_placeholder(fr1, r)
1905 // If we fail to find THAT, it may be that `fr1` is a
1906 // placeholder that cannot "fit" into its SCC. In that
1907 // case, there should be some `r` where `fr1: r` and `fr1` is a
1908 // placeholder that `r` cannot name. We can blame that
1911 // Remember that if `R1: R2`, then the universe of R1
1912 // must be able to name the universe of R2, because R2 will
1913 // be at least `'empty(Universe(R2))`, and `R1` must be at
1914 // larger than that.
1915 self.find_constraint_paths_between_regions(fr1, |r| {
1916 self.cannot_name_placeholder(r, fr1)
1919 .map(|(_path, r)| r)
1923 /// Get the region outlived by `longer_fr` and live at `element`.
1924 pub(crate) fn region_from_element(
1926 longer_fr: RegionVid,
1927 element: &RegionElement,
1930 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1931 RegionElement::RootUniversalRegion(r) => r,
1932 RegionElement::PlaceholderRegion(error_placeholder) => self
1935 .find_map(|(r, definition)| match definition.origin {
1936 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1943 /// Get the region definition of `r`.
1944 pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1945 &self.definitions[r]
1948 /// Check if the SCC of `r` contains `upper`.
1949 pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1950 let r_scc = self.constraint_sccs.scc(r);
1951 self.scc_values.contains(r_scc, upper)
1954 pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
1955 self.universal_regions.as_ref()
1958 /// Tries to find the best constraint to blame for the fact that
1959 /// `R: from_region`, where `R` is some region that meets
1960 /// `target_test`. This works by following the constraint graph,
1961 /// creating a constraint path that forces `R` to outlive
1962 /// `from_region`, and then finding the best choices within that
1964 #[instrument(level = "debug", skip(self, target_test))]
1965 pub(crate) fn best_blame_constraint(
1967 from_region: RegionVid,
1968 from_region_origin: NllRegionVariableOrigin,
1969 target_test: impl Fn(RegionVid) -> bool,
1970 ) -> (BlameConstraint<'tcx>, Vec<ExtraConstraintInfo>) {
1972 let (path, target_region) =
1973 self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
1978 "{:?} ({:?}: {:?})",
1980 self.constraint_sccs.scc(c.sup),
1981 self.constraint_sccs.scc(c.sub),
1983 .collect::<Vec<_>>()
1986 let mut extra_info = vec![];
1987 for constraint in path.iter() {
1988 let outlived = constraint.sub;
1989 let Some(origin) = self.var_infos.get(outlived) else { continue; };
1990 let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; };
1991 debug!(?constraint, ?p);
1992 let ConstraintCategory::Predicate(span) = constraint.category else { continue; };
1993 extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span));
1994 // We only want to point to one
1998 // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
1999 // Instead, we use it to produce an improved `ObligationCauseCode`.
2000 // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
2001 // constraints. Currently, we just pick the first one.
2002 let cause_code = path
2004 .find_map(|constraint| {
2005 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
2006 // We currently do not store the `DefId` in the `ConstraintCategory`
2007 // for performances reasons. The error reporting code used by NLL only
2008 // uses the span, so this doesn't cause any problems at the moment.
2009 Some(ObligationCauseCode::BindingObligation(
2010 CRATE_DEF_ID.to_def_id(),
2017 .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2019 // Classify each of the constraints along the path.
2020 let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2022 .map(|constraint| BlameConstraint {
2023 category: constraint.category,
2024 from_closure: constraint.from_closure,
2025 cause: ObligationCause::new(constraint.span, CRATE_HIR_ID, cause_code.clone()),
2026 variance_info: constraint.variance_info,
2027 outlives_constraint: *constraint,
2030 debug!("categorized_path={:#?}", categorized_path);
2032 // To find the best span to cite, we first try to look for the
2033 // final constraint that is interesting and where the `sup` is
2034 // not unified with the ultimate target region. The reason
2035 // for this is that we have a chain of constraints that lead
2036 // from the source to the target region, something like:
2038 // '0: '1 ('0 is the source)
2043 // '5: '6 ('6 is the target)
2045 // Some of those regions are unified with `'6` (in the same
2046 // SCC). We want to screen those out. After that point, the
2047 // "closest" constraint we have to the end is going to be the
2048 // most likely to be the point where the value escapes -- but
2049 // we still want to screen for an "interesting" point to
2050 // highlight (e.g., a call site or something).
2051 let target_scc = self.constraint_sccs.scc(target_region);
2052 let mut range = 0..path.len();
2054 // As noted above, when reporting an error, there is typically a chain of constraints
2055 // leading from some "source" region which must outlive some "target" region.
2056 // In most cases, we prefer to "blame" the constraints closer to the target --
2057 // but there is one exception. When constraints arise from higher-ranked subtyping,
2058 // we generally prefer to blame the source value,
2059 // as the "target" in this case tends to be some type annotation that the user gave.
2060 // Therefore, if we find that the region origin is some instantiation
2061 // of a higher-ranked region, we start our search from the "source" point
2062 // rather than the "target", and we also tweak a few other things.
2064 // An example might be this bit of Rust code:
2067 // let x: fn(&'static ()) = |_| {};
2068 // let y: for<'a> fn(&'a ()) = x;
2071 // In MIR, this will be converted into a combination of assignments and type ascriptions.
2072 // In particular, the 'static is imposed through a type ascription:
2076 // AscribeUserType(x, fn(&'static ())
2080 // We wind up ultimately with constraints like
2083 // !a: 'temp1 // from the `y = x` statement
2085 // 'temp2: 'static // from the AscribeUserType
2088 // and here we prefer to blame the source (the y = x statement).
2089 let blame_source = match from_region_origin {
2090 NllRegionVariableOrigin::FreeRegion
2091 | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2092 NllRegionVariableOrigin::Placeholder(_)
2093 | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2096 let find_region = |i: &usize| {
2097 let constraint = &path[*i];
2099 let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2102 match categorized_path[*i].category {
2103 ConstraintCategory::OpaqueType
2104 | ConstraintCategory::Boring
2105 | ConstraintCategory::BoringNoLocation
2106 | ConstraintCategory::Internal
2107 | ConstraintCategory::Predicate(_) => false,
2108 ConstraintCategory::TypeAnnotation
2109 | ConstraintCategory::Return(_)
2110 | ConstraintCategory::Yield => true,
2111 _ => constraint_sup_scc != target_scc,
2115 categorized_path[*i].category,
2116 ConstraintCategory::OpaqueType
2117 | ConstraintCategory::Boring
2118 | ConstraintCategory::BoringNoLocation
2119 | ConstraintCategory::Internal
2120 | ConstraintCategory::Predicate(_)
2126 if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2128 debug!(?best_choice, ?blame_source, ?extra_info);
2130 if let Some(i) = best_choice {
2131 if let Some(next) = categorized_path.get(i + 1) {
2132 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2133 && next.category == ConstraintCategory::OpaqueType
2135 // The return expression is being influenced by the return type being
2136 // impl Trait, point at the return type and not the return expr.
2137 return (next.clone(), extra_info);
2141 if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2143 let field = categorized_path.iter().find_map(|p| {
2144 if let ConstraintCategory::ClosureUpvar(f) = p.category {
2151 if let Some(field) = field {
2152 categorized_path[i].category =
2153 ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2157 return (categorized_path[i].clone(), extra_info);
2160 // If that search fails, that is.. unusual. Maybe everything
2161 // is in the same SCC or something. In that case, find what
2162 // appears to be the most interesting point to report to the
2163 // user via an even more ad-hoc guess.
2164 categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2165 debug!("sorted_path={:#?}", categorized_path);
2167 (categorized_path.remove(0), extra_info)
2170 pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2171 self.universe_causes[&universe].clone()
2174 /// Tries to find the terminator of the loop in which the region 'r' resides.
2175 /// Returns the location of the terminator if found.
2176 pub(crate) fn find_loop_terminator_location(
2180 ) -> Option<Location> {
2181 let scc = self.constraint_sccs.scc(r.to_region_vid());
2182 let locations = self.scc_values.locations_outlived_by(scc);
2183 for location in locations {
2184 let bb = &body[location.block];
2185 if let Some(terminator) = &bb.terminator {
2186 // terminator of a loop should be TerminatorKind::FalseUnwind
2187 if let TerminatorKind::FalseUnwind { .. } = terminator.kind {
2188 return Some(location);
2196 impl<'tcx> RegionDefinition<'tcx> {
2197 fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2198 // Create a new region definition. Note that, for free
2199 // regions, the `external_name` field gets updated later in
2200 // `init_universal_regions`.
2202 let origin = match rv_origin {
2203 RegionVariableOrigin::Nll(origin) => origin,
2204 _ => NllRegionVariableOrigin::Existential { from_forall: false },
2207 Self { origin, universe, external_name: None }
2211 #[derive(Clone, Debug)]
2212 pub struct BlameConstraint<'tcx> {
2213 pub category: ConstraintCategory<'tcx>,
2214 pub from_closure: bool,
2215 pub cause: ObligationCause<'tcx>,
2216 pub variance_info: ty::VarianceDiagInfo<'tcx>,
2217 pub outlives_constraint: OutlivesConstraint<'tcx>,