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::{DefId, CRATE_DEF_ID};
10 use rustc_hir::CRATE_HIR_ID;
11 use rustc_index::vec::IndexVec;
12 use rustc_infer::infer::canonical::QueryOutlivesConstraint;
13 use rustc_infer::infer::outlives::test_type_match;
14 use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound, VerifyIfEq};
15 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin};
16 use rustc_middle::mir::{
17 Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
18 ConstraintCategory, Local, Location, ReturnConstraint,
20 use rustc_middle::traits::ObligationCause;
21 use rustc_middle::traits::ObligationCauseCode;
22 use rustc_middle::ty::{
23 self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable,
29 graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
31 diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
32 member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
33 nll::{PoloniusOutput, ToRegionVid},
34 region_infer::reverse_sccs::ReverseSccGraph,
35 region_infer::values::{
36 LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
39 type_check::{free_region_relations::UniversalRegionRelations, Locations},
40 universal_regions::UniversalRegions,
50 pub struct RegionInferenceContext<'tcx> {
51 pub var_infos: VarInfos,
53 /// Contains the definition for every region variable. Region
54 /// variables are identified by their index (`RegionVid`). The
55 /// definition contains information about where the region came
56 /// from as well as its final inferred value.
57 definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
59 /// The liveness constraints added to each region. For most
60 /// regions, these start out empty and steadily grow, though for
61 /// each universally quantified region R they start out containing
62 /// the entire CFG and `end(R)`.
63 liveness_constraints: LivenessValues<RegionVid>,
65 /// The outlives constraints computed by the type-check.
66 constraints: Frozen<OutlivesConstraintSet<'tcx>>,
68 /// The constraint-set, but in graph form, making it easy to traverse
69 /// the constraints adjacent to a particular region. Used to construct
70 /// the SCC (see `constraint_sccs`) and for error reporting.
71 constraint_graph: Frozen<NormalConstraintGraph>,
73 /// The SCC computed from `constraints` and the constraint
74 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
75 /// compute the values of each region.
76 constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
78 /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if
79 /// `B: A`. This is used to compute the universal regions that are required
80 /// to outlive a given SCC. Computed lazily.
81 rev_scc_graph: Option<Rc<ReverseSccGraph>>,
83 /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
84 member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
86 /// Records the member constraints that we applied to each scc.
87 /// This is useful for error reporting. Once constraint
88 /// propagation is done, this vector is sorted according to
89 /// `member_region_scc`.
90 member_constraints_applied: Vec<AppliedMemberConstraint>,
92 /// Map closure bounds to a `Span` that should be used for error reporting.
93 closure_bounds_mapping:
94 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>>,
96 /// Map universe indexes to information on why we created it.
97 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
99 /// Contains the minimum universe of any variable within the same
100 /// SCC. We will ensure that no SCC contains values that are not
101 /// visible from this index.
102 scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
104 /// Contains a "representative" from each SCC. This will be the
105 /// minimal RegionVid belonging to that universe. It is used as a
106 /// kind of hacky way to manage checking outlives relationships,
107 /// since we can 'canonicalize' each region to the representative
108 /// of its SCC and be sure that -- if they have the same repr --
109 /// they *must* be equal (though not having the same repr does not
110 /// mean they are unequal).
111 scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
113 /// The final inferred values of the region variables; we compute
114 /// one value per SCC. To get the value for any given *region*,
115 /// you first find which scc it is a part of.
116 scc_values: RegionValues<ConstraintSccIndex>,
118 /// Type constraints that we check after solving.
119 type_tests: Vec<TypeTest<'tcx>>,
121 /// Information about the universally quantified regions in scope
122 /// on this function.
123 universal_regions: Rc<UniversalRegions<'tcx>>,
125 /// Information about how the universally quantified regions in
126 /// scope on this function relate to one another.
127 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
130 /// Each time that `apply_member_constraint` is successful, it appends
131 /// one of these structs to the `member_constraints_applied` field.
132 /// This is used in error reporting to trace out what happened.
134 /// The way that `apply_member_constraint` works is that it effectively
135 /// adds a new lower bound to the SCC it is analyzing: so you wind up
136 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
137 /// minimal viable option.
138 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
139 pub(crate) struct AppliedMemberConstraint {
140 /// The SCC that was affected. (The "member region".)
142 /// The vector if `AppliedMemberConstraint` elements is kept sorted
144 pub(crate) member_region_scc: ConstraintSccIndex,
146 /// The "best option" that `apply_member_constraint` found -- this was
147 /// added as an "ad-hoc" lower-bound to `member_region_scc`.
148 pub(crate) min_choice: ty::RegionVid,
150 /// The "member constraint index" -- we can find out details about
151 /// the constraint from
152 /// `set.member_constraints[member_constraint_index]`.
153 pub(crate) member_constraint_index: NllMemberConstraintIndex,
156 pub(crate) struct RegionDefinition<'tcx> {
157 /// What kind of variable is this -- a free region? existential
158 /// variable? etc. (See the `NllRegionVariableOrigin` for more
160 pub(crate) origin: NllRegionVariableOrigin,
162 /// Which universe is this region variable defined in? This is
163 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
164 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
165 /// the variable for `'a` in a fresh universe that extends ROOT.
166 pub(crate) universe: ty::UniverseIndex,
168 /// If this is 'static or an early-bound region, then this is
169 /// `Some(X)` where `X` is the name of the region.
170 pub(crate) external_name: Option<ty::Region<'tcx>>,
173 /// N.B., the variants in `Cause` are intentionally ordered. Lower
174 /// values are preferred when it comes to error messages. Do not
175 /// reorder willy nilly.
176 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
177 pub(crate) enum Cause {
178 /// point inserted because Local was live at the given Location
179 LiveVar(Local, Location),
181 /// point inserted because Local was dropped at the given Location
182 DropVar(Local, Location),
185 /// A "type test" corresponds to an outlives constraint between a type
186 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
187 /// translated from the `Verify` region constraints in the ordinary
188 /// inference context.
190 /// These sorts of constraints are handled differently than ordinary
191 /// constraints, at least at present. During type checking, the
192 /// `InferCtxt::process_registered_region_obligations` method will
193 /// attempt to convert a type test like `T: 'x` into an ordinary
194 /// outlives constraint when possible (for example, `&'a T: 'b` will
195 /// be converted into `'a: 'b` and registered as a `Constraint`).
197 /// In some cases, however, there are outlives relationships that are
198 /// not converted into a region constraint, but rather into one of
199 /// these "type tests". The distinction is that a type test does not
200 /// influence the inference result, but instead just examines the
201 /// values that we ultimately inferred for each region variable and
202 /// checks that they meet certain extra criteria. If not, an error
205 /// One reason for this is that these type tests typically boil down
206 /// to a check like `'a: 'x` where `'a` is a universally quantified
207 /// region -- and therefore not one whose value is really meant to be
208 /// *inferred*, precisely (this is not always the case: one can have a
209 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
210 /// inference variable). Another reason is that these type tests can
211 /// involve *disjunction* -- that is, they can be satisfied in more
214 /// For more information about this translation, see
215 /// `InferCtxt::process_registered_region_obligations` and
216 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
217 #[derive(Clone, Debug)]
218 pub struct TypeTest<'tcx> {
219 /// The type `T` that must outlive the region.
220 pub generic_kind: GenericKind<'tcx>,
222 /// The region `'x` that the type must outlive.
223 pub lower_bound: RegionVid,
225 /// Where did this constraint arise and why?
226 pub locations: Locations,
228 /// A test which, if met by the region `'x`, proves that this type
229 /// constraint is satisfied.
230 pub verify_bound: VerifyBound<'tcx>,
233 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
234 /// environment). If we can't, it is an error.
235 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
236 enum RegionRelationCheckResult {
242 #[derive(Clone, PartialEq, Eq, Debug)]
245 FromOutlivesConstraint(OutlivesConstraint<'tcx>),
249 impl<'tcx> RegionInferenceContext<'tcx> {
250 /// Creates a new region inference context with a total of
251 /// `num_region_variables` valid inference variables; the first N
252 /// of those will be constant regions representing the free
253 /// regions defined in `universal_regions`.
255 /// The `outlives_constraints` and `type_tests` are an initial set
256 /// of constraints produced by the MIR type check.
259 universal_regions: Rc<UniversalRegions<'tcx>>,
260 placeholder_indices: Rc<PlaceholderIndices>,
261 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
262 outlives_constraints: OutlivesConstraintSet<'tcx>,
263 member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
264 closure_bounds_mapping: FxHashMap<
266 FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>,
268 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
269 type_tests: Vec<TypeTest<'tcx>>,
270 liveness_constraints: LivenessValues<RegionVid>,
271 elements: &Rc<RegionValueElements>,
273 // Create a RegionDefinition for each inference variable.
274 let definitions: IndexVec<_, _> = var_infos
276 .map(|info| RegionDefinition::new(info.universe, info.origin))
279 let constraints = Frozen::freeze(outlives_constraints);
280 let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
281 let fr_static = universal_regions.fr_static;
282 let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
285 RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
287 for region in liveness_constraints.rows() {
288 let scc = constraint_sccs.scc(region);
289 scc_values.merge_liveness(scc, region, &liveness_constraints);
292 let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
294 let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
296 let member_constraints =
297 Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
299 let mut result = Self {
302 liveness_constraints,
308 member_constraints_applied: Vec::new(),
309 closure_bounds_mapping,
316 universal_region_relations,
319 result.init_free_and_bound_regions();
324 /// Each SCC is the combination of many region variables which
325 /// have been equated. Therefore, we can associate a universe with
326 /// each SCC which is minimum of all the universes of its
327 /// constituent regions -- this is because whatever value the SCC
328 /// takes on must be a value that each of the regions within the
329 /// SCC could have as well. This implies that the SCC must have
330 /// the minimum, or narrowest, universe.
331 fn compute_scc_universes(
332 constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
333 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
334 ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
335 let num_sccs = constraint_sccs.num_sccs();
336 let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
338 debug!("compute_scc_universes()");
340 // For each region R in universe U, ensure that the universe for the SCC
341 // that contains R is "no bigger" than U. This effectively sets the universe
342 // for each SCC to be the minimum of the regions within.
343 for (region_vid, region_definition) in definitions.iter_enumerated() {
344 let scc = constraint_sccs.scc(region_vid);
345 let scc_universe = &mut scc_universes[scc];
346 let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
347 if scc_min != *scc_universe {
348 *scc_universe = scc_min;
350 "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
351 because it contains {region_vid:?} in {region_universe:?}",
354 region_vid = region_vid,
355 region_universe = region_definition.universe,
360 // Walk each SCC `A` and `B` such that `A: B`
361 // and ensure that universe(A) can see universe(B).
363 // This serves to enforce the 'empty/placeholder' hierarchy
364 // (described in more detail on `RegionKind`):
369 // empty(U0) placeholder(U1)
374 // In particular, imagine we have variables R0 in U0 and R1
375 // created in U1, and constraints like this;
378 // R1: !1 // R1 outlives the placeholder in U1
379 // R1: R0 // R1 outlives R0
382 // Here, we wish for R1 to be `'static`, because it
383 // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
385 // Thanks to this loop, what happens is that the `R1: R0`
386 // constraint lowers the universe of `R1` to `U0`, which in turn
387 // means that the `R1: !1` constraint will (later) cause
388 // `R1` to become `'static`.
389 for scc_a in constraint_sccs.all_sccs() {
390 for &scc_b in constraint_sccs.successors(scc_a) {
391 let scc_universe_a = scc_universes[scc_a];
392 let scc_universe_b = scc_universes[scc_b];
393 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
394 if scc_universe_a != scc_universe_min {
395 scc_universes[scc_a] = scc_universe_min;
398 "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
399 because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
402 scc_universe_min = scc_universe_min,
403 scc_universe_b = scc_universe_b
409 debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
414 /// For each SCC, we compute a unique `RegionVid` (in fact, the
415 /// minimal one that belongs to the SCC). See
416 /// `scc_representatives` field of `RegionInferenceContext` for
418 fn compute_scc_representatives(
419 constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
420 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
421 ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
422 let num_sccs = constraints_scc.num_sccs();
423 let next_region_vid = definitions.next_index();
424 let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
426 for region_vid in definitions.indices() {
427 let scc = constraints_scc.scc(region_vid);
428 let prev_min = scc_representatives[scc];
429 scc_representatives[scc] = region_vid.min(prev_min);
435 /// Initializes the region variables for each universally
436 /// quantified region (lifetime parameter). The first N variables
437 /// always correspond to the regions appearing in the function
438 /// signature (both named and anonymous) and where-clauses. This
439 /// function iterates over those regions and initializes them with
444 /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
446 /// would initialize two variables like so:
447 /// ```ignore (illustrative)
448 /// R0 = { CFG, R0 } // 'a
449 /// R1 = { CFG, R0, R1 } // 'b
451 /// Here, R0 represents `'a`, and it contains (a) the entire CFG
452 /// and (b) any universally quantified regions that it outlives,
453 /// which in this case is just itself. R1 (`'b`) in contrast also
454 /// outlives `'a` and hence contains R0 and R1.
455 fn init_free_and_bound_regions(&mut self) {
456 // Update the names (if any)
457 for (external_name, variable) in self.universal_regions.named_universal_regions() {
459 "init_universal_regions: region {:?} has external name {:?}",
460 variable, external_name
462 self.definitions[variable].external_name = Some(external_name);
465 for variable in self.definitions.indices() {
466 let scc = self.constraint_sccs.scc(variable);
468 match self.definitions[variable].origin {
469 NllRegionVariableOrigin::FreeRegion => {
470 // For each free, universally quantified region X:
472 // Add all nodes in the CFG to liveness constraints
473 self.liveness_constraints.add_all_points(variable);
474 self.scc_values.add_all_points(scc);
476 // Add `end(X)` into the set for X.
477 self.scc_values.add_element(scc, variable);
480 NllRegionVariableOrigin::Placeholder(placeholder) => {
481 // Each placeholder region is only visible from
482 // its universe `ui` and its extensions. So we
483 // can't just add it into `scc` unless the
484 // universe of the scc can name this region.
485 let scc_universe = self.scc_universes[scc];
486 if scc_universe.can_name(placeholder.universe) {
487 self.scc_values.add_element(scc, placeholder);
490 "init_free_and_bound_regions: placeholder {:?} is \
491 not compatible with universe {:?} of its SCC {:?}",
492 placeholder, scc_universe, scc,
494 self.add_incompatible_universe(scc);
498 NllRegionVariableOrigin::Existential { .. } => {
499 // For existential, regions, nothing to do.
505 /// Returns an iterator over all the region indices.
506 pub fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
507 self.definitions.indices()
510 /// Given a universal region in scope on the MIR, returns the
511 /// corresponding index.
513 /// (Panics if `r` is not a registered universal region.)
514 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
515 self.universal_regions.to_region_vid(r)
518 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
519 pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
520 self.universal_regions.annotate(tcx, err)
523 /// Returns `true` if the region `r` contains the point `p`.
525 /// Panics if called before `solve()` executes,
526 pub(crate) fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
527 let scc = self.constraint_sccs.scc(r.to_region_vid());
528 self.scc_values.contains(scc, p)
531 /// Returns access to the value of `r` for debugging purposes.
532 pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
533 let scc = self.constraint_sccs.scc(r.to_region_vid());
534 self.scc_values.region_value_str(scc)
537 /// Returns access to the value of `r` for debugging purposes.
538 pub(crate) fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
539 let scc = self.constraint_sccs.scc(r.to_region_vid());
540 self.scc_universes[scc]
543 /// Once region solving has completed, this function will return
544 /// the member constraints that were applied to the value of a given
545 /// region `r`. See `AppliedMemberConstraint`.
546 pub(crate) fn applied_member_constraints(
549 ) -> &[AppliedMemberConstraint] {
550 let scc = self.constraint_sccs.scc(r.to_region_vid());
551 binary_search_util::binary_search_slice(
552 &self.member_constraints_applied,
553 |applied| applied.member_region_scc,
558 /// Performs region inference and report errors if we see any
559 /// unsatisfiable constraints. If this is a closure, returns the
560 /// region requirements to propagate to our creator, if any.
561 #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
564 infcx: &InferCtxt<'_, 'tcx>,
565 param_env: ty::ParamEnv<'tcx>,
567 polonius_output: Option<Rc<PoloniusOutput>>,
568 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
569 let mir_def_id = body.source.def_id();
570 self.propagate_constraints(body);
572 let mut errors_buffer = RegionErrors::new();
574 // If this is a closure, we can propagate unsatisfied
575 // `outlives_requirements` to our creator, so create a vector
576 // to store those. Otherwise, we'll pass in `None` to the
577 // functions below, which will trigger them to report errors
579 let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
581 self.check_type_tests(
585 outlives_requirements.as_mut(),
589 // In Polonius mode, the errors about missing universal region relations are in the output
590 // and need to be emitted or propagated. Otherwise, we need to check whether the
591 // constraints were too strong, and if so, emit or propagate those errors.
592 if infcx.tcx.sess.opts.unstable_opts.polonius {
593 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(body, 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 min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> {
759 let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2);
760 let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1);
761 match (r1_outlives_r2, r2_outlives_r1) {
762 (true, true) => Some(r1.min(r2)),
763 (true, false) => Some(r2),
764 (false, true) => Some(r1),
765 (false, false) => None,
768 let mut min_choice = choice_regions[0];
769 for &other_option in &choice_regions[1..] {
770 debug!(?min_choice, ?other_option,);
771 match min(min_choice, other_option) {
772 Some(m) => min_choice = m,
774 debug!(?min_choice, ?other_option, "incomparable; no min choice",);
780 let min_choice_scc = self.constraint_sccs.scc(min_choice);
781 debug!(?min_choice, ?min_choice_scc);
782 if self.scc_values.add_region(scc, min_choice_scc) {
783 self.member_constraints_applied.push(AppliedMemberConstraint {
784 member_region_scc: scc,
786 member_constraint_index,
795 /// Returns `true` if all the elements in the value of `scc_b` are nameable
796 /// in `scc_a`. Used during constraint propagation, and only once
797 /// the value of `scc_b` has been computed.
798 fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
799 let universe_a = self.scc_universes[scc_a];
801 // Quick check: if scc_b's declared universe is a subset of
802 // scc_a's declared universe (typically, both are ROOT), then
803 // it cannot contain any problematic universe elements.
804 if universe_a.can_name(self.scc_universes[scc_b]) {
808 // Otherwise, we have to iterate over the universe elements in
809 // B's value, and check whether all of them are nameable
811 self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
814 /// Extend `scc` so that it can outlive some placeholder region
815 /// from a universe it can't name; at present, the only way for
816 /// this to be true is if `scc` outlives `'static`. This is
817 /// actually stricter than necessary: ideally, we'd support bounds
818 /// like `for<'a: 'b`>` that might then allow us to approximate
819 /// `'a` with `'b` and not `'static`. But it will have to do for
821 fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
822 debug!("add_incompatible_universe(scc={:?})", scc);
824 let fr_static = self.universal_regions.fr_static;
825 self.scc_values.add_all_points(scc);
826 self.scc_values.add_element(scc, fr_static);
829 /// Once regions have been propagated, this method is used to see
830 /// whether the "type tests" produced by typeck were satisfied;
831 /// type tests encode type-outlives relationships like `T:
832 /// 'a`. See `TypeTest` for more details.
835 infcx: &InferCtxt<'_, 'tcx>,
836 param_env: ty::ParamEnv<'tcx>,
838 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
839 errors_buffer: &mut RegionErrors<'tcx>,
843 // Sometimes we register equivalent type-tests that would
844 // result in basically the exact same error being reported to
845 // the user. Avoid that.
846 let mut deduplicate_errors = FxHashSet::default();
848 for type_test in &self.type_tests {
849 debug!("check_type_test: {:?}", type_test);
851 let generic_ty = type_test.generic_kind.to_ty(tcx);
852 if self.eval_verify_bound(
857 type_test.lower_bound,
858 &type_test.verify_bound,
863 if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
864 if self.try_promote_type_test(
869 propagated_outlives_requirements,
875 // Type-test failed. Report the error.
876 let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
878 // Skip duplicate-ish errors.
879 if deduplicate_errors.insert((
881 type_test.lower_bound,
885 "check_type_test: reporting error for erased_generic_kind={:?}, \
886 lower_bound_region={:?}, \
887 type_test.locations={:?}",
888 erased_generic_kind, type_test.lower_bound, type_test.locations,
891 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
896 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
897 /// prove to be satisfied. If this is a closure, we will attempt to
898 /// "promote" this type-test into our `ClosureRegionRequirements` and
899 /// hence pass it up the creator. To do this, we have to phrase the
900 /// type-test in terms of external free regions, as local free
901 /// regions are not nameable by the closure's creator.
903 /// Promotion works as follows: we first check that the type `T`
904 /// contains only regions that the creator knows about. If this is
905 /// true, then -- as a consequence -- we know that all regions in
906 /// the type `T` are free regions that outlive the closure body. If
907 /// false, then promotion fails.
909 /// Once we've promoted T, we have to "promote" `'X` to some region
910 /// that is "external" to the closure. Generally speaking, a region
911 /// may be the union of some points in the closure body as well as
912 /// various free lifetimes. We can ignore the points in the closure
913 /// body: if the type T can be expressed in terms of external regions,
914 /// we know it outlives the points in the closure body. That
915 /// just leaves the free regions.
917 /// The idea then is to lower the `T: 'X` constraint into multiple
918 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
919 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
920 #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]
921 fn try_promote_type_test(
923 infcx: &InferCtxt<'_, 'tcx>,
924 param_env: ty::ParamEnv<'tcx>,
926 type_test: &TypeTest<'tcx>,
927 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
931 let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test;
933 let generic_ty = generic_kind.to_ty(tcx);
934 let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
938 debug!("subject = {:?}", subject);
940 let r_scc = self.constraint_sccs.scc(*lower_bound);
943 "lower_bound = {:?} r_scc={:?} universe={:?}",
944 lower_bound, r_scc, self.scc_universes[r_scc]
947 // If the type test requires that `T: 'a` where `'a` is a
948 // placeholder from another universe, that effectively requires
949 // `T: 'static`, so we have to propagate that requirement.
951 // It doesn't matter *what* universe because the promoted `T` will
952 // always be in the root universe.
953 if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
954 debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
955 let static_r = self.universal_regions.fr_static;
956 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
958 outlived_free_region: static_r,
959 blame_span: locations.span(body),
960 category: ConstraintCategory::Boring,
963 // we can return here -- the code below might push add'l constraints
964 // but they would all be weaker than this one.
968 // For each region outlived by lower_bound find a non-local,
969 // universal region (it may be the same region) and add it to
970 // `ClosureOutlivesRequirement`.
971 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
972 debug!("universal_region_outlived_by ur={:?}", ur);
973 // Check whether we can already prove that the "subject" outlives `ur`.
974 // If so, we don't have to propagate this requirement to our caller.
976 // To continue the example from the function, if we are trying to promote
977 // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
978 // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
979 // we check whether `T: '1` is something we *can* prove. If so, no need
980 // to propagate that requirement.
982 // This is needed because -- particularly in the case
983 // where `ur` is a local bound -- we are sometimes in a
984 // position to prove things that our caller cannot. See
985 // #53570 for an example.
986 if self.eval_verify_bound(
992 &type_test.verify_bound,
997 let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
998 debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
1000 // This is slightly too conservative. To show T: '1, given `'2: '1`
1001 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
1002 // avoid potential non-determinism we approximate this by requiring
1004 for upper_bound in non_local_ub {
1005 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
1006 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
1008 let requirement = ClosureOutlivesRequirement {
1010 outlived_free_region: upper_bound,
1011 blame_span: locations.span(body),
1012 category: ConstraintCategory::Boring,
1014 debug!("try_promote_type_test: pushing {:#?}", requirement);
1015 propagated_outlives_requirements.push(requirement);
1021 /// When we promote a type test `T: 'r`, we have to convert the
1022 /// type `T` into something we can store in a query result (so
1023 /// something allocated for `'tcx`). This is problematic if `ty`
1024 /// contains regions. During the course of NLL region checking, we
1025 /// will have replaced all of those regions with fresh inference
1026 /// variables. To create a test subject, we want to replace those
1027 /// inference variables with some region from the closure
1028 /// signature -- this is not always possible, so this is a
1029 /// fallible process. Presuming we do find a suitable region, we
1030 /// will use it's *external name*, which will be a `RegionKind`
1031 /// variant that can be used in query responses such as
1033 #[instrument(level = "debug", skip(self, infcx))]
1034 fn try_promote_type_test_subject(
1036 infcx: &InferCtxt<'_, 'tcx>,
1038 ) -> Option<ClosureOutlivesSubject<'tcx>> {
1039 let tcx = infcx.tcx;
1041 let ty = tcx.fold_regions(ty, |r, _depth| {
1042 let region_vid = self.to_region_vid(r);
1044 // The challenge if this. We have some region variable `r`
1045 // whose value is a set of CFG points and universal
1046 // regions. We want to find if that set is *equivalent* to
1047 // any of the named regions found in the closure.
1049 // To do so, we compute the
1050 // `non_local_universal_upper_bound`. This will be a
1051 // non-local, universal region that is greater than `r`.
1052 // However, it might not be *contained* within `r`, so
1053 // then we further check whether this bound is contained
1054 // in `r`. If so, we can say that `r` is equivalent to the
1057 // Let's work through a few examples. For these, imagine
1058 // that we have 3 non-local regions (I'll denote them as
1059 // `'static`, `'a`, and `'b`, though of course in the code
1060 // they would be represented with indices) where:
1065 // First, let's assume that `r` is some existential
1066 // variable with an inferred value `{'a, 'static}` (plus
1067 // some CFG nodes). In this case, the non-local upper
1068 // bound is `'static`, since that outlives `'a`. `'static`
1069 // is also a member of `r` and hence we consider `r`
1070 // equivalent to `'static` (and replace it with
1073 // Now let's consider the inferred value `{'a, 'b}`. This
1074 // means `r` is effectively `'a | 'b`. I'm not sure if
1075 // this can come about, actually, but assuming it did, we
1076 // would get a non-local upper bound of `'static`. Since
1077 // `'static` is not contained in `r`, we would fail to
1078 // find an equivalent.
1079 let upper_bound = self.non_local_universal_upper_bound(region_vid);
1080 if self.region_contains(region_vid, upper_bound) {
1081 self.definitions[upper_bound].external_name.unwrap_or(r)
1083 // In the case of a failure, use a `ReVar` result. This will
1084 // cause the `needs_infer` later on to return `None`.
1089 debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1091 // `needs_infer` will only be true if we failed to promote some region.
1092 if ty.needs_infer() {
1096 Some(ClosureOutlivesSubject::Ty(ty))
1099 /// Given some universal or existential region `r`, finds a
1100 /// non-local, universal region `r+` that outlives `r` at entry to (and
1101 /// exit from) the closure. In the worst case, this will be
1104 /// This is used for two purposes. First, if we are propagated
1105 /// some requirement `T: r`, we can use this method to enlarge `r`
1106 /// to something we can encode for our creator (which only knows
1107 /// about non-local, universal regions). It is also used when
1108 /// encoding `T` as part of `try_promote_type_test_subject` (see
1109 /// that fn for details).
1111 /// This is based on the result `'y` of `universal_upper_bound`,
1112 /// except that it converts further takes the non-local upper
1113 /// bound of `'y`, so that the final result is non-local.
1114 fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1115 debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1117 let lub = self.universal_upper_bound(r);
1119 // Grow further to get smallest universal region known to
1121 let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1123 debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1128 /// Returns a universally quantified region that outlives the
1129 /// value of `r` (`r` may be existentially or universally
1132 /// Since `r` is (potentially) an existential region, it has some
1133 /// value which may include (a) any number of points in the CFG
1134 /// and (b) any number of `end('x)` elements of universally
1135 /// quantified regions. To convert this into a single universal
1136 /// region we do as follows:
1138 /// - Ignore the CFG points in `'r`. All universally quantified regions
1139 /// include the CFG anyhow.
1140 /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1142 #[instrument(skip(self), level = "debug")]
1143 pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1144 debug!(r = %self.region_value_str(r));
1146 // Find the smallest universal region that contains all other
1147 // universal regions within `region`.
1148 let mut lub = self.universal_regions.fr_fn_body;
1149 let r_scc = self.constraint_sccs.scc(r);
1150 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1151 lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1159 /// Like `universal_upper_bound`, but returns an approximation more suitable
1160 /// for diagnostics. If `r` contains multiple disjoint universal regions
1161 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1162 /// This corresponds to picking named regions over unnamed regions
1163 /// (e.g. picking early-bound regions over a closure late-bound region).
1165 /// This means that the returned value may not be a true upper bound, since
1166 /// only 'static is known to outlive disjoint universal regions.
1167 /// Therefore, this method should only be used in diagnostic code,
1168 /// where displaying *some* named universal region is better than
1169 /// falling back to 'static.
1170 pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1171 debug!("approx_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1173 // Find the smallest universal region that contains all other
1174 // universal regions within `region`.
1175 let mut lub = self.universal_regions.fr_fn_body;
1176 let r_scc = self.constraint_sccs.scc(r);
1177 let static_r = self.universal_regions.fr_static;
1178 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1179 let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1180 debug!("approx_universal_upper_bound: ur={:?} lub={:?} new_lub={:?}", ur, lub, new_lub);
1181 // The upper bound of two non-static regions is static: this
1182 // means we know nothing about the relationship between these
1183 // two regions. Pick a 'better' one to use when constructing
1185 if ur != static_r && lub != static_r && new_lub == static_r {
1186 // Prefer the region with an `external_name` - this
1187 // indicates that the region is early-bound, so working with
1188 // it can produce a nicer error.
1189 if self.region_definition(ur).external_name.is_some() {
1191 } else if self.region_definition(lub).external_name.is_some() {
1192 // Leave lub unchanged
1194 // If we get here, we don't have any reason to prefer
1195 // one region over the other. Just pick the
1196 // one with the lower index for now.
1197 lub = std::cmp::min(ur, lub);
1204 debug!("approx_universal_upper_bound: r={:?} lub={:?}", r, lub);
1209 /// Tests if `test` is true when applied to `lower_bound` at
1211 fn eval_verify_bound(
1213 infcx: &InferCtxt<'_, 'tcx>,
1214 param_env: ty::ParamEnv<'tcx>,
1216 generic_ty: Ty<'tcx>,
1217 lower_bound: RegionVid,
1218 verify_bound: &VerifyBound<'tcx>,
1220 debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1222 match verify_bound {
1223 VerifyBound::IfEq(verify_if_eq_b) => {
1224 self.eval_if_eq(infcx, param_env, generic_ty, lower_bound, *verify_if_eq_b)
1227 VerifyBound::IsEmpty => {
1228 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1229 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1232 VerifyBound::OutlivedBy(r) => {
1233 let r_vid = self.to_region_vid(*r);
1234 self.eval_outlives(r_vid, lower_bound)
1237 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1238 self.eval_verify_bound(
1248 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1249 self.eval_verify_bound(
1263 infcx: &InferCtxt<'_, 'tcx>,
1264 param_env: ty::ParamEnv<'tcx>,
1265 generic_ty: Ty<'tcx>,
1266 lower_bound: RegionVid,
1267 verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
1269 let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
1270 let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
1271 match test_type_match::extract_verify_if_eq(
1278 let r_vid = self.to_region_vid(r);
1279 self.eval_outlives(r_vid, lower_bound)
1285 /// This is a conservative normalization procedure. It takes every
1286 /// free region in `value` and replaces it with the
1287 /// "representative" of its SCC (see `scc_representatives` field).
1288 /// We are guaranteed that if two values normalize to the same
1289 /// thing, then they are equal; this is a conservative check in
1290 /// that they could still be equal even if they normalize to
1291 /// different results. (For example, there might be two regions
1292 /// with the same value that are not in the same SCC).
1294 /// N.B., this is not an ideal approach and I would like to revisit
1295 /// it. However, it works pretty well in practice. In particular,
1296 /// this is needed to deal with projection outlives bounds like
1299 /// <T as Foo<'0>>::Item: '1
1302 /// In particular, this routine winds up being important when
1303 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1304 /// environment. In this case, if we can show that `'0 == 'a`,
1305 /// and that `'b: '1`, then we know that the clause is
1306 /// satisfied. In such cases, particularly due to limitations of
1307 /// the trait solver =), we usually wind up with a where-clause like
1308 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1309 /// a constraint, and thus ensures that they are in the same SCC.
1311 /// So why can't we do a more correct routine? Well, we could
1312 /// *almost* use the `relate_tys` code, but the way it is
1313 /// currently setup it creates inference variables to deal with
1314 /// higher-ranked things and so forth, and right now the inference
1315 /// context is not permitted to make more inference variables. So
1316 /// we use this kind of hacky solution.
1317 fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1319 T: TypeFoldable<'tcx>,
1321 tcx.fold_regions(value, |r, _db| {
1322 let vid = self.to_region_vid(r);
1323 let scc = self.constraint_sccs.scc(vid);
1324 let repr = self.scc_representatives[scc];
1325 tcx.mk_region(ty::ReVar(repr))
1329 // Evaluate whether `sup_region == sub_region`.
1330 fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1331 self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1334 // Evaluate whether `sup_region: sub_region`.
1335 #[instrument(skip(self), level = "debug")]
1336 fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1338 "eval_outlives: sup_region's value = {:?} universal={:?}",
1339 self.region_value_str(sup_region),
1340 self.universal_regions.is_universal_region(sup_region),
1343 "eval_outlives: sub_region's value = {:?} universal={:?}",
1344 self.region_value_str(sub_region),
1345 self.universal_regions.is_universal_region(sub_region),
1348 let sub_region_scc = self.constraint_sccs.scc(sub_region);
1349 let sup_region_scc = self.constraint_sccs.scc(sup_region);
1351 // If we are checking that `'sup: 'sub`, and `'sub` contains
1352 // some placeholder that `'sup` cannot name, then this is only
1353 // true if `'sup` outlives static.
1354 if !self.universe_compatible(sub_region_scc, sup_region_scc) {
1356 "eval_outlives: sub universe `{sub_region_scc:?}` is not nameable \
1357 by super `{sup_region_scc:?}`, promoting to static",
1360 return self.eval_outlives(sup_region, self.universal_regions.fr_static);
1363 // Both the `sub_region` and `sup_region` consist of the union
1364 // of some number of universal regions (along with the union
1365 // of various points in the CFG; ignore those points for
1366 // now). Therefore, the sup-region outlives the sub-region if,
1367 // for each universal region R1 in the sub-region, there
1368 // exists some region R2 in the sup-region that outlives R1.
1369 let universal_outlives =
1370 self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1372 .universal_regions_outlived_by(sup_region_scc)
1373 .any(|r2| self.universal_region_relations.outlives(r2, r1))
1376 if !universal_outlives {
1378 "eval_outlives: returning false because sub region contains a universal region not present in super"
1383 // Now we have to compare all the points in the sub region and make
1384 // sure they exist in the sup region.
1386 if self.universal_regions.is_universal_region(sup_region) {
1387 // Micro-opt: universal regions contain all points.
1389 "eval_outlives: returning true because super is universal and hence contains all points"
1394 let result = self.scc_values.contains_points(sup_region_scc, sub_region_scc);
1395 debug!("returning {} because of comparison between points in sup/sub", result);
1399 /// Once regions have been propagated, this method is used to see
1400 /// whether any of the constraints were too strong. In particular,
1401 /// we want to check for a case where a universally quantified
1402 /// region exceeded its bounds. Consider:
1403 /// ```compile_fail,E0312
1404 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1406 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1407 /// and hence we establish (transitively) a constraint that
1408 /// `'a: 'b`. The `propagate_constraints` code above will
1409 /// therefore add `end('a)` into the region for `'b` -- but we
1410 /// have no evidence that `'b` outlives `'a`, so we want to report
1413 /// If `propagated_outlives_requirements` is `Some`, then we will
1414 /// push unsatisfied obligations into there. Otherwise, we'll
1415 /// report them as errors.
1416 fn check_universal_regions(
1419 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1420 errors_buffer: &mut RegionErrors<'tcx>,
1422 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1423 match fr_definition.origin {
1424 NllRegionVariableOrigin::FreeRegion => {
1425 // Go through each of the universal regions `fr` and check that
1426 // they did not grow too large, accumulating any requirements
1427 // for our caller into the `outlives_requirements` vector.
1428 self.check_universal_region(
1431 &mut propagated_outlives_requirements,
1436 NllRegionVariableOrigin::Placeholder(placeholder) => {
1437 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1440 NllRegionVariableOrigin::Existential { .. } => {
1441 // nothing to check here
1447 /// Checks if Polonius has found any unexpected free region relations.
1449 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1450 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1451 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1452 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1454 /// More details can be found in this blog post by Niko:
1455 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1457 /// In the canonical example
1458 /// ```compile_fail,E0312
1459 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1461 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1462 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1463 /// constraint holds.
1465 /// If `propagated_outlives_requirements` is `Some`, then we will
1466 /// push unsatisfied obligations into there. Otherwise, we'll
1467 /// report them as errors.
1468 fn check_polonius_subset_errors(
1471 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1472 errors_buffer: &mut RegionErrors<'tcx>,
1473 polonius_output: Rc<PoloniusOutput>,
1476 "check_polonius_subset_errors: {} subset_errors",
1477 polonius_output.subset_errors.len()
1480 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1481 // declared ("known") was found by Polonius, so emit an error, or propagate the
1482 // requirements for our caller into the `propagated_outlives_requirements` vector.
1484 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1485 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1486 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1487 // and the "superset origin" is the outlived "shorter free region".
1489 // Note: Polonius will produce a subset error at every point where the unexpected
1490 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1491 // for diagnostics in the future, e.g. to point more precisely at the key locations
1492 // requiring this constraint to hold. However, the error and diagnostics code downstream
1493 // expects that these errors are not duplicated (and that they are in a certain order).
1494 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1495 // anonymous lifetimes for example, could give these names differently, while others like
1496 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1497 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1498 // CFG-location ordering.
1499 let mut subset_errors: Vec<_> = polonius_output
1502 .flat_map(|(_location, subset_errors)| subset_errors.iter())
1504 subset_errors.sort();
1505 subset_errors.dedup();
1507 for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1509 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1511 longer_fr, shorter_fr
1514 let propagated = self.try_propagate_universal_region_error(
1518 &mut propagated_outlives_requirements,
1520 if propagated == RegionRelationCheckResult::Error {
1521 errors_buffer.push(RegionErrorKind::RegionError {
1522 longer_fr: *longer_fr,
1523 shorter_fr: *shorter_fr,
1524 fr_origin: NllRegionVariableOrigin::FreeRegion,
1530 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1531 // a more complete picture on how to separate this responsibility.
1532 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1533 match fr_definition.origin {
1534 NllRegionVariableOrigin::FreeRegion => {
1535 // handled by polonius above
1538 NllRegionVariableOrigin::Placeholder(placeholder) => {
1539 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1542 NllRegionVariableOrigin::Existential { .. } => {
1543 // nothing to check here
1549 /// Checks the final value for the free region `fr` to see if it
1550 /// grew too large. In particular, examine what `end(X)` points
1551 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1552 /// fr`, we want to check that `fr: X`. If not, that's either an
1553 /// error, or something we have to propagate to our creator.
1555 /// Things that are to be propagated are accumulated into the
1556 /// `outlives_requirements` vector.
1558 skip(self, body, propagated_outlives_requirements, errors_buffer),
1561 fn check_universal_region(
1564 longer_fr: RegionVid,
1565 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1566 errors_buffer: &mut RegionErrors<'tcx>,
1568 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1570 // Because this free region must be in the ROOT universe, we
1571 // know it cannot contain any bound universes.
1572 assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1573 debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1575 // Only check all of the relations for the main representative of each
1576 // SCC, otherwise just check that we outlive said representative. This
1577 // reduces the number of redundant relations propagated out of
1579 // Note that the representative will be a universal region if there is
1580 // one in this SCC, so we will always check the representative here.
1581 let representative = self.scc_representatives[longer_fr_scc];
1582 if representative != longer_fr {
1583 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1587 propagated_outlives_requirements,
1589 errors_buffer.push(RegionErrorKind::RegionError {
1591 shorter_fr: representative,
1592 fr_origin: NllRegionVariableOrigin::FreeRegion,
1599 // Find every region `o` such that `fr: o`
1600 // (because `fr` includes `end(o)`).
1601 let mut error_reported = false;
1602 for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1603 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1607 propagated_outlives_requirements,
1609 // We only report the first region error. Subsequent errors are hidden so as
1610 // not to overwhelm the user, but we do record them so as to potentially print
1611 // better diagnostics elsewhere...
1612 errors_buffer.push(RegionErrorKind::RegionError {
1615 fr_origin: NllRegionVariableOrigin::FreeRegion,
1616 is_reported: !error_reported,
1619 error_reported = true;
1624 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1625 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1627 fn check_universal_region_relation(
1629 longer_fr: RegionVid,
1630 shorter_fr: RegionVid,
1632 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1633 ) -> RegionRelationCheckResult {
1634 // If it is known that `fr: o`, carry on.
1635 if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1636 RegionRelationCheckResult::Ok
1638 // If we are not in a context where we can't propagate errors, or we
1639 // could not shrink `fr` to something smaller, then just report an
1642 // Note: in this case, we use the unapproximated regions to report the
1643 // error. This gives better error messages in some cases.
1644 self.try_propagate_universal_region_error(
1648 propagated_outlives_requirements,
1653 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1654 /// creator. If we cannot, then the caller should report an error to the user.
1655 fn try_propagate_universal_region_error(
1657 longer_fr: RegionVid,
1658 shorter_fr: RegionVid,
1660 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1661 ) -> RegionRelationCheckResult {
1662 if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1663 // Shrink `longer_fr` until we find a non-local region (if we do).
1664 // We'll call it `fr-` -- it's ever so slightly smaller than
1666 if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1668 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1670 let blame_span_category = self.find_outlives_blame_span(
1673 NllRegionVariableOrigin::FreeRegion,
1677 // Grow `shorter_fr` until we find some non-local regions. (We
1678 // always will.) We'll call them `shorter_fr+` -- they're ever
1679 // so slightly larger than `shorter_fr`.
1680 let shorter_fr_plus =
1681 self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1683 "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1686 for fr in shorter_fr_plus {
1687 // Push the constraint `fr-: shorter_fr+`
1688 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1689 subject: ClosureOutlivesSubject::Region(fr_minus),
1690 outlived_free_region: fr,
1691 blame_span: blame_span_category.1.span,
1692 category: blame_span_category.0,
1695 return RegionRelationCheckResult::Propagated;
1699 RegionRelationCheckResult::Error
1702 fn check_bound_universal_region(
1704 longer_fr: RegionVid,
1705 placeholder: ty::PlaceholderRegion,
1706 errors_buffer: &mut RegionErrors<'tcx>,
1708 debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1710 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1711 debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1713 // If we have some bound universal region `'a`, then the only
1714 // elements it can contain is itself -- we don't know anything
1716 let Some(error_element) = ({
1717 self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element {
1718 RegionElement::Location(_) => true,
1719 RegionElement::RootUniversalRegion(_) => true,
1720 RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1725 debug!("check_bound_universal_region: error_element = {:?}", error_element);
1727 // Find the region that introduced this `error_element`.
1728 errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1735 fn check_member_constraints(
1737 infcx: &InferCtxt<'_, 'tcx>,
1738 errors_buffer: &mut RegionErrors<'tcx>,
1740 let member_constraints = self.member_constraints.clone();
1741 for m_c_i in member_constraints.all_indices() {
1742 debug!("check_member_constraint(m_c_i={:?})", m_c_i);
1743 let m_c = &member_constraints[m_c_i];
1744 let member_region_vid = m_c.member_region_vid;
1746 "check_member_constraint: member_region_vid={:?} with value {}",
1748 self.region_value_str(member_region_vid),
1750 let choice_regions = member_constraints.choice_regions(m_c_i);
1751 debug!("check_member_constraint: choice_regions={:?}", choice_regions);
1753 // Did the member region wind up equal to any of the option regions?
1755 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1757 debug!("check_member_constraint: evaluated as equal to {:?}", o);
1761 // If not, report an error.
1762 let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1763 errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1764 span: m_c.definition_span,
1765 hidden_ty: m_c.hidden_ty,
1771 /// We have a constraint `fr1: fr2` that is not satisfied, where
1772 /// `fr2` represents some universal region. Here, `r` is some
1773 /// region where we know that `fr1: r` and this function has the
1774 /// job of determining whether `r` is "to blame" for the fact that
1775 /// `fr1: fr2` is required.
1777 /// This is true under two conditions:
1780 /// - `fr2` is `'static` and `r` is some placeholder in a universe
1781 /// that cannot be named by `fr1`; in that case, we will require
1782 /// that `fr1: 'static` because it is the only way to `fr1: r` to
1783 /// be satisfied. (See `add_incompatible_universe`.)
1784 pub(crate) fn provides_universal_region(
1790 debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1793 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1796 debug!("provides_universal_region: result = {:?}", result);
1800 /// If `r2` represents a placeholder region, then this returns
1801 /// `true` if `r1` cannot name that placeholder in its
1802 /// value; otherwise, returns `false`.
1803 pub(crate) fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1804 debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1806 match self.definitions[r2].origin {
1807 NllRegionVariableOrigin::Placeholder(placeholder) => {
1808 let universe1 = self.definitions[r1].universe;
1810 "cannot_name_value_of: universe1={:?} placeholder={:?}",
1811 universe1, placeholder
1813 universe1.cannot_name(placeholder.universe)
1816 NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { .. } => {
1822 pub(crate) fn retrieve_closure_constraint_info(
1825 constraint: &OutlivesConstraint<'tcx>,
1826 ) -> BlameConstraint<'tcx> {
1827 let loc = match constraint.locations {
1828 Locations::All(span) => {
1829 return BlameConstraint {
1830 category: constraint.category,
1831 from_closure: false,
1832 cause: ObligationCause::dummy_with_span(span),
1833 variance_info: constraint.variance_info,
1836 Locations::Single(loc) => loc,
1839 let opt_span_category =
1840 self.closure_bounds_mapping[&loc].get(&(constraint.sup, constraint.sub));
1842 .map(|&(category, span)| BlameConstraint {
1845 cause: ObligationCause::dummy_with_span(span),
1846 variance_info: constraint.variance_info,
1848 .unwrap_or(BlameConstraint {
1849 category: constraint.category,
1850 from_closure: false,
1851 cause: ObligationCause::dummy_with_span(constraint.span),
1852 variance_info: constraint.variance_info,
1856 /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1857 pub(crate) fn find_outlives_blame_span(
1861 fr1_origin: NllRegionVariableOrigin,
1863 ) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
1864 let BlameConstraint { category, cause, .. } =
1865 self.best_blame_constraint(body, fr1, fr1_origin, |r| {
1866 self.provides_universal_region(r, fr1, fr2)
1871 /// Walks the graph of constraints (where `'a: 'b` is considered
1872 /// an edge `'a -> 'b`) to find all paths from `from_region` to
1873 /// `to_region`. The paths are accumulated into the vector
1874 /// `results`. The paths are stored as a series of
1875 /// `ConstraintIndex` values -- in other words, a list of *edges*.
1877 /// Returns: a series of constraints as well as the region `R`
1878 /// that passed the target test.
1879 pub(crate) fn find_constraint_paths_between_regions(
1881 from_region: RegionVid,
1882 target_test: impl Fn(RegionVid) -> bool,
1883 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1884 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1885 context[from_region] = Trace::StartRegion;
1887 // Use a deque so that we do a breadth-first search. We will
1888 // stop at the first match, which ought to be the shortest
1889 // path (fewest constraints).
1890 let mut deque = VecDeque::new();
1891 deque.push_back(from_region);
1893 while let Some(r) = deque.pop_front() {
1895 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1898 self.region_value_str(r),
1901 // Check if we reached the region we were looking for. If so,
1902 // we can reconstruct the path that led to it and return it.
1904 let mut result = vec![];
1907 match context[p].clone() {
1908 Trace::NotVisited => {
1909 bug!("found unvisited region {:?} on path to {:?}", p, r)
1912 Trace::FromOutlivesConstraint(c) => {
1917 Trace::StartRegion => {
1919 return Some((result, r));
1925 // Otherwise, walk over the outgoing constraints and
1926 // enqueue any regions we find, keeping track of how we
1929 // A constraint like `'r: 'x` can come from our constraint
1931 let fr_static = self.universal_regions.fr_static;
1932 let outgoing_edges_from_graph =
1933 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1935 // Always inline this closure because it can be hot.
1936 let mut handle_constraint = #[inline(always)]
1937 |constraint: OutlivesConstraint<'tcx>| {
1938 debug_assert_eq!(constraint.sup, r);
1939 let sub_region = constraint.sub;
1940 if let Trace::NotVisited = context[sub_region] {
1941 context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1942 deque.push_back(sub_region);
1946 // This loop can be hot.
1947 for constraint in outgoing_edges_from_graph {
1948 handle_constraint(constraint);
1951 // Member constraints can also give rise to `'r: 'x` edges that
1952 // were not part of the graph initially, so watch out for those.
1953 // (But they are extremely rare; this loop is very cold.)
1954 for constraint in self.applied_member_constraints(r) {
1955 let p_c = &self.member_constraints[constraint.member_constraint_index];
1956 let constraint = OutlivesConstraint {
1958 sub: constraint.min_choice,
1959 locations: Locations::All(p_c.definition_span),
1960 span: p_c.definition_span,
1961 category: ConstraintCategory::OpaqueType,
1962 variance_info: ty::VarianceDiagInfo::default(),
1964 handle_constraint(constraint);
1971 /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1972 #[instrument(skip(self), level = "trace")]
1973 pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1974 trace!(scc = ?self.constraint_sccs.scc(fr1));
1975 trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1976 self.find_constraint_paths_between_regions(fr1, |r| {
1977 // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1978 trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1979 self.liveness_constraints.contains(r, elem)
1982 // If we fail to find that, we may find some `r` such that
1983 // `fr1: r` and `r` is a placeholder from some universe
1984 // `fr1` cannot name. This would force `fr1` to be
1986 self.find_constraint_paths_between_regions(fr1, |r| {
1987 self.cannot_name_placeholder(fr1, r)
1991 // If we fail to find THAT, it may be that `fr1` is a
1992 // placeholder that cannot "fit" into its SCC. In that
1993 // case, there should be some `r` where `fr1: r` and `fr1` is a
1994 // placeholder that `r` cannot name. We can blame that
1997 // Remember that if `R1: R2`, then the universe of R1
1998 // must be able to name the universe of R2, because R2 will
1999 // be at least `'empty(Universe(R2))`, and `R1` must be at
2000 // larger than that.
2001 self.find_constraint_paths_between_regions(fr1, |r| {
2002 self.cannot_name_placeholder(r, fr1)
2005 .map(|(_path, r)| r)
2009 /// Get the region outlived by `longer_fr` and live at `element`.
2010 pub(crate) fn region_from_element(
2012 longer_fr: RegionVid,
2013 element: &RegionElement,
2016 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
2017 RegionElement::RootUniversalRegion(r) => r,
2018 RegionElement::PlaceholderRegion(error_placeholder) => self
2021 .find_map(|(r, definition)| match definition.origin {
2022 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
2029 /// Get the region definition of `r`.
2030 pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
2031 &self.definitions[r]
2034 /// Check if the SCC of `r` contains `upper`.
2035 pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
2036 let r_scc = self.constraint_sccs.scc(r);
2037 self.scc_values.contains(r_scc, upper)
2040 pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
2041 self.universal_regions.as_ref()
2044 /// Tries to find the best constraint to blame for the fact that
2045 /// `R: from_region`, where `R` is some region that meets
2046 /// `target_test`. This works by following the constraint graph,
2047 /// creating a constraint path that forces `R` to outlive
2048 /// `from_region`, and then finding the best choices within that
2050 pub(crate) fn best_blame_constraint(
2053 from_region: RegionVid,
2054 from_region_origin: NllRegionVariableOrigin,
2055 target_test: impl Fn(RegionVid) -> bool,
2056 ) -> BlameConstraint<'tcx> {
2058 "best_blame_constraint(from_region={:?}, from_region_origin={:?})",
2059 from_region, from_region_origin
2063 let (path, target_region) =
2064 self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
2066 "best_blame_constraint: path={:#?}",
2069 "{:?} ({:?}: {:?})",
2071 self.constraint_sccs.scc(c.sup),
2072 self.constraint_sccs.scc(c.sub),
2074 .collect::<Vec<_>>()
2077 // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
2078 // Instead, we use it to produce an improved `ObligationCauseCode`.
2079 // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
2080 // constraints. Currently, we just pick the first one.
2081 let cause_code = path
2083 .find_map(|constraint| {
2084 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
2085 // We currently do not store the `DefId` in the `ConstraintCategory`
2086 // for performances reasons. The error reporting code used by NLL only
2087 // uses the span, so this doesn't cause any problems at the moment.
2088 Some(ObligationCauseCode::BindingObligation(
2089 CRATE_DEF_ID.to_def_id(),
2096 .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2098 // Classify each of the constraints along the path.
2099 let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2102 if constraint.category == ConstraintCategory::ClosureBounds {
2103 self.retrieve_closure_constraint_info(body, &constraint)
2106 category: constraint.category,
2107 from_closure: false,
2108 cause: ObligationCause::new(
2113 variance_info: constraint.variance_info,
2118 debug!("best_blame_constraint: categorized_path={:#?}", categorized_path);
2120 // To find the best span to cite, we first try to look for the
2121 // final constraint that is interesting and where the `sup` is
2122 // not unified with the ultimate target region. The reason
2123 // for this is that we have a chain of constraints that lead
2124 // from the source to the target region, something like:
2126 // '0: '1 ('0 is the source)
2131 // '5: '6 ('6 is the target)
2133 // Some of those regions are unified with `'6` (in the same
2134 // SCC). We want to screen those out. After that point, the
2135 // "closest" constraint we have to the end is going to be the
2136 // most likely to be the point where the value escapes -- but
2137 // we still want to screen for an "interesting" point to
2138 // highlight (e.g., a call site or something).
2139 let target_scc = self.constraint_sccs.scc(target_region);
2140 let mut range = 0..path.len();
2142 // As noted above, when reporting an error, there is typically a chain of constraints
2143 // leading from some "source" region which must outlive some "target" region.
2144 // In most cases, we prefer to "blame" the constraints closer to the target --
2145 // but there is one exception. When constraints arise from higher-ranked subtyping,
2146 // we generally prefer to blame the source value,
2147 // as the "target" in this case tends to be some type annotation that the user gave.
2148 // Therefore, if we find that the region origin is some instantiation
2149 // of a higher-ranked region, we start our search from the "source" point
2150 // rather than the "target", and we also tweak a few other things.
2152 // An example might be this bit of Rust code:
2155 // let x: fn(&'static ()) = |_| {};
2156 // let y: for<'a> fn(&'a ()) = x;
2159 // In MIR, this will be converted into a combination of assignments and type ascriptions.
2160 // In particular, the 'static is imposed through a type ascription:
2164 // AscribeUserType(x, fn(&'static ())
2168 // We wind up ultimately with constraints like
2171 // !a: 'temp1 // from the `y = x` statement
2173 // 'temp2: 'static // from the AscribeUserType
2176 // and here we prefer to blame the source (the y = x statement).
2177 let blame_source = match from_region_origin {
2178 NllRegionVariableOrigin::FreeRegion
2179 | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2180 NllRegionVariableOrigin::Placeholder(_)
2181 | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2184 let find_region = |i: &usize| {
2185 let constraint = &path[*i];
2187 let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2190 match categorized_path[*i].category {
2191 ConstraintCategory::OpaqueType
2192 | ConstraintCategory::Boring
2193 | ConstraintCategory::BoringNoLocation
2194 | ConstraintCategory::Internal
2195 | ConstraintCategory::Predicate(_) => false,
2196 ConstraintCategory::TypeAnnotation
2197 | ConstraintCategory::Return(_)
2198 | ConstraintCategory::Yield => true,
2199 _ => constraint_sup_scc != target_scc,
2203 categorized_path[*i].category,
2204 ConstraintCategory::OpaqueType
2205 | ConstraintCategory::Boring
2206 | ConstraintCategory::BoringNoLocation
2207 | ConstraintCategory::Internal
2208 | ConstraintCategory::Predicate(_)
2214 if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2217 "best_blame_constraint: best_choice={:?} blame_source={}",
2218 best_choice, blame_source
2221 if let Some(i) = best_choice {
2222 if let Some(next) = categorized_path.get(i + 1) {
2223 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2224 && next.category == ConstraintCategory::OpaqueType
2226 // The return expression is being influenced by the return type being
2227 // impl Trait, point at the return type and not the return expr.
2228 return next.clone();
2232 if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2234 let field = categorized_path.iter().find_map(|p| {
2235 if let ConstraintCategory::ClosureUpvar(f) = p.category {
2242 if let Some(field) = field {
2243 categorized_path[i].category =
2244 ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2248 return categorized_path[i].clone();
2251 // If that search fails, that is.. unusual. Maybe everything
2252 // is in the same SCC or something. In that case, find what
2253 // appears to be the most interesting point to report to the
2254 // user via an even more ad-hoc guess.
2255 categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2256 debug!("best_blame_constraint: sorted_path={:#?}", categorized_path);
2258 categorized_path.remove(0)
2261 pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2262 self.universe_causes[&universe].clone()
2266 impl<'tcx> RegionDefinition<'tcx> {
2267 fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2268 // Create a new region definition. Note that, for free
2269 // regions, the `external_name` field gets updated later in
2270 // `init_universal_regions`.
2272 let origin = match rv_origin {
2273 RegionVariableOrigin::Nll(origin) => origin,
2274 _ => NllRegionVariableOrigin::Existential { from_forall: false },
2277 Self { origin, universe, external_name: None }
2281 pub trait ClosureRegionRequirementsExt<'tcx> {
2282 fn apply_requirements(
2285 closure_def_id: DefId,
2286 closure_substs: SubstsRef<'tcx>,
2287 ) -> Vec<QueryOutlivesConstraint<'tcx>>;
2290 impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> {
2291 /// Given an instance T of the closure type, this method
2292 /// instantiates the "extra" requirements that we computed for the
2293 /// closure into the inference context. This has the effect of
2294 /// adding new outlives obligations to existing variables.
2296 /// As described on `ClosureRegionRequirements`, the extra
2297 /// requirements are expressed in terms of regionvids that index
2298 /// into the free regions that appear on the closure type. So, to
2299 /// do this, we first copy those regions out from the type T into
2300 /// a vector. Then we can just index into that vector to extract
2301 /// out the corresponding region from T and apply the
2303 fn apply_requirements(
2306 closure_def_id: DefId,
2307 closure_substs: SubstsRef<'tcx>,
2308 ) -> Vec<QueryOutlivesConstraint<'tcx>> {
2310 "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
2311 closure_def_id, closure_substs
2314 // Extract the values of the free regions in `closure_substs`
2315 // into a vector. These are the regions that we will be
2316 // relating to one another.
2317 let closure_mapping = &UniversalRegions::closure_mapping(
2320 self.num_external_vids,
2321 tcx.typeck_root_def_id(closure_def_id),
2323 debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
2325 // Create the predicates.
2326 self.outlives_requirements
2328 .map(|outlives_requirement| {
2329 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
2331 match outlives_requirement.subject {
2332 ClosureOutlivesSubject::Region(region) => {
2333 let region = closure_mapping[region];
2335 "apply_requirements: region={:?} \
2336 outlived_region={:?} \
2337 outlives_requirement={:?}",
2338 region, outlived_region, outlives_requirement,
2340 ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
2343 ClosureOutlivesSubject::Ty(ty) => {
2345 "apply_requirements: ty={:?} \
2346 outlived_region={:?} \
2347 outlives_requirement={:?}",
2348 ty, outlived_region, outlives_requirement,
2350 ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
2358 #[derive(Clone, Debug)]
2359 pub struct BlameConstraint<'tcx> {
2360 pub category: ConstraintCategory<'tcx>,
2361 pub from_closure: bool,
2362 pub cause: ObligationCause<'tcx>,
2363 pub variance_info: ty::VarianceDiagInfo<'tcx>,