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::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable};
27 graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
29 diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
30 member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
31 nll::{PoloniusOutput, ToRegionVid},
32 region_infer::reverse_sccs::ReverseSccGraph,
33 region_infer::values::{
34 LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
37 type_check::{free_region_relations::UniversalRegionRelations, Locations},
38 universal_regions::UniversalRegions,
48 pub struct RegionInferenceContext<'tcx> {
49 pub var_infos: VarInfos,
51 /// Contains the definition for every region variable. Region
52 /// variables are identified by their index (`RegionVid`). The
53 /// definition contains information about where the region came
54 /// from as well as its final inferred value.
55 definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
57 /// The liveness constraints added to each region. For most
58 /// regions, these start out empty and steadily grow, though for
59 /// each universally quantified region R they start out containing
60 /// the entire CFG and `end(R)`.
61 liveness_constraints: LivenessValues<RegionVid>,
63 /// The outlives constraints computed by the type-check.
64 constraints: Frozen<OutlivesConstraintSet<'tcx>>,
66 /// The constraint-set, but in graph form, making it easy to traverse
67 /// the constraints adjacent to a particular region. Used to construct
68 /// the SCC (see `constraint_sccs`) and for error reporting.
69 constraint_graph: Frozen<NormalConstraintGraph>,
71 /// The SCC computed from `constraints` and the constraint
72 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
73 /// compute the values of each region.
74 constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
76 /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if
77 /// `B: A`. This is used to compute the universal regions that are required
78 /// to outlive a given SCC. Computed lazily.
79 rev_scc_graph: Option<Rc<ReverseSccGraph>>,
81 /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
82 member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
84 /// Records the member constraints that we applied to each scc.
85 /// This is useful for error reporting. Once constraint
86 /// propagation is done, this vector is sorted according to
87 /// `member_region_scc`.
88 member_constraints_applied: Vec<AppliedMemberConstraint>,
90 /// Map closure bounds to a `Span` that should be used for error reporting.
91 closure_bounds_mapping:
92 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>>,
94 /// Map universe indexes to information on why we created it.
95 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
97 /// Contains the minimum universe of any variable within the same
98 /// SCC. We will ensure that no SCC contains values that are not
99 /// visible from this index.
100 scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
102 /// Contains a "representative" from each SCC. This will be the
103 /// minimal RegionVid belonging to that universe. It is used as a
104 /// kind of hacky way to manage checking outlives relationships,
105 /// since we can 'canonicalize' each region to the representative
106 /// of its SCC and be sure that -- if they have the same repr --
107 /// they *must* be equal (though not having the same repr does not
108 /// mean they are unequal).
109 scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
111 /// The final inferred values of the region variables; we compute
112 /// one value per SCC. To get the value for any given *region*,
113 /// you first find which scc it is a part of.
114 scc_values: RegionValues<ConstraintSccIndex>,
116 /// Type constraints that we check after solving.
117 type_tests: Vec<TypeTest<'tcx>>,
119 /// Information about the universally quantified regions in scope
120 /// on this function.
121 universal_regions: Rc<UniversalRegions<'tcx>>,
123 /// Information about how the universally quantified regions in
124 /// scope on this function relate to one another.
125 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
128 /// Each time that `apply_member_constraint` is successful, it appends
129 /// one of these structs to the `member_constraints_applied` field.
130 /// This is used in error reporting to trace out what happened.
132 /// The way that `apply_member_constraint` works is that it effectively
133 /// adds a new lower bound to the SCC it is analyzing: so you wind up
134 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
135 /// minimal viable option.
136 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
137 pub(crate) struct AppliedMemberConstraint {
138 /// The SCC that was affected. (The "member region".)
140 /// The vector if `AppliedMemberConstraint` elements is kept sorted
142 pub(crate) member_region_scc: ConstraintSccIndex,
144 /// The "best option" that `apply_member_constraint` found -- this was
145 /// added as an "ad-hoc" lower-bound to `member_region_scc`.
146 pub(crate) min_choice: ty::RegionVid,
148 /// The "member constraint index" -- we can find out details about
149 /// the constraint from
150 /// `set.member_constraints[member_constraint_index]`.
151 pub(crate) member_constraint_index: NllMemberConstraintIndex,
154 pub(crate) struct RegionDefinition<'tcx> {
155 /// What kind of variable is this -- a free region? existential
156 /// variable? etc. (See the `NllRegionVariableOrigin` for more
158 pub(crate) origin: NllRegionVariableOrigin,
160 /// Which universe is this region variable defined in? This is
161 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
162 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
163 /// the variable for `'a` in a fresh universe that extends ROOT.
164 pub(crate) universe: ty::UniverseIndex,
166 /// If this is 'static or an early-bound region, then this is
167 /// `Some(X)` where `X` is the name of the region.
168 pub(crate) external_name: Option<ty::Region<'tcx>>,
171 /// N.B., the variants in `Cause` are intentionally ordered. Lower
172 /// values are preferred when it comes to error messages. Do not
173 /// reorder willy nilly.
174 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
175 pub(crate) enum Cause {
176 /// point inserted because Local was live at the given Location
177 LiveVar(Local, Location),
179 /// point inserted because Local was dropped at the given Location
180 DropVar(Local, Location),
183 /// A "type test" corresponds to an outlives constraint between a type
184 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
185 /// translated from the `Verify` region constraints in the ordinary
186 /// inference context.
188 /// These sorts of constraints are handled differently than ordinary
189 /// constraints, at least at present. During type checking, the
190 /// `InferCtxt::process_registered_region_obligations` method will
191 /// attempt to convert a type test like `T: 'x` into an ordinary
192 /// outlives constraint when possible (for example, `&'a T: 'b` will
193 /// be converted into `'a: 'b` and registered as a `Constraint`).
195 /// In some cases, however, there are outlives relationships that are
196 /// not converted into a region constraint, but rather into one of
197 /// these "type tests". The distinction is that a type test does not
198 /// influence the inference result, but instead just examines the
199 /// values that we ultimately inferred for each region variable and
200 /// checks that they meet certain extra criteria. If not, an error
203 /// One reason for this is that these type tests typically boil down
204 /// to a check like `'a: 'x` where `'a` is a universally quantified
205 /// region -- and therefore not one whose value is really meant to be
206 /// *inferred*, precisely (this is not always the case: one can have a
207 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
208 /// inference variable). Another reason is that these type tests can
209 /// involve *disjunction* -- that is, they can be satisfied in more
212 /// For more information about this translation, see
213 /// `InferCtxt::process_registered_region_obligations` and
214 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
215 #[derive(Clone, Debug)]
216 pub struct TypeTest<'tcx> {
217 /// The type `T` that must outlive the region.
218 pub generic_kind: GenericKind<'tcx>,
220 /// The region `'x` that the type must outlive.
221 pub lower_bound: RegionVid,
223 /// Where did this constraint arise and why?
224 pub locations: Locations,
226 /// A test which, if met by the region `'x`, proves that this type
227 /// constraint is satisfied.
228 pub verify_bound: VerifyBound<'tcx>,
231 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
232 /// environment). If we can't, it is an error.
233 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
234 enum RegionRelationCheckResult {
240 #[derive(Clone, PartialEq, Eq, Debug)]
243 FromOutlivesConstraint(OutlivesConstraint<'tcx>),
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 closure_bounds_mapping: FxHashMap<
264 FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>,
266 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
267 type_tests: Vec<TypeTest<'tcx>>,
268 liveness_constraints: LivenessValues<RegionVid>,
269 elements: &Rc<RegionValueElements>,
271 // Create a RegionDefinition for each inference variable.
272 let definitions: IndexVec<_, _> = var_infos
274 .map(|info| RegionDefinition::new(info.universe, info.origin))
277 let constraints = Frozen::freeze(outlives_constraints);
278 let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
279 let fr_static = universal_regions.fr_static;
280 let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
283 RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
285 for region in liveness_constraints.rows() {
286 let scc = constraint_sccs.scc(region);
287 scc_values.merge_liveness(scc, region, &liveness_constraints);
290 let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
292 let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
294 let member_constraints =
295 Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
297 let mut result = Self {
300 liveness_constraints,
306 member_constraints_applied: Vec::new(),
307 closure_bounds_mapping,
314 universal_region_relations,
317 result.init_free_and_bound_regions();
322 /// Each SCC is the combination of many region variables which
323 /// have been equated. Therefore, we can associate a universe with
324 /// each SCC which is minimum of all the universes of its
325 /// constituent regions -- this is because whatever value the SCC
326 /// takes on must be a value that each of the regions within the
327 /// SCC could have as well. This implies that the SCC must have
328 /// the minimum, or narrowest, universe.
329 fn compute_scc_universes(
330 constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
331 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
332 ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
333 let num_sccs = constraint_sccs.num_sccs();
334 let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
336 debug!("compute_scc_universes()");
338 // For each region R in universe U, ensure that the universe for the SCC
339 // that contains R is "no bigger" than U. This effectively sets the universe
340 // for each SCC to be the minimum of the regions within.
341 for (region_vid, region_definition) in definitions.iter_enumerated() {
342 let scc = constraint_sccs.scc(region_vid);
343 let scc_universe = &mut scc_universes[scc];
344 let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
345 if scc_min != *scc_universe {
346 *scc_universe = scc_min;
348 "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
349 because it contains {region_vid:?} in {region_universe:?}",
352 region_vid = region_vid,
353 region_universe = region_definition.universe,
358 // Walk each SCC `A` and `B` such that `A: B`
359 // and ensure that universe(A) can see universe(B).
361 // This serves to enforce the 'empty/placeholder' hierarchy
362 // (described in more detail on `RegionKind`):
367 // empty(U0) placeholder(U1)
372 // In particular, imagine we have variables R0 in U0 and R1
373 // created in U1, and constraints like this;
376 // R1: !1 // R1 outlives the placeholder in U1
377 // R1: R0 // R1 outlives R0
380 // Here, we wish for R1 to be `'static`, because it
381 // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
383 // Thanks to this loop, what happens is that the `R1: R0`
384 // constraint lowers the universe of `R1` to `U0`, which in turn
385 // means that the `R1: !1` constraint will (later) cause
386 // `R1` to become `'static`.
387 for scc_a in constraint_sccs.all_sccs() {
388 for &scc_b in constraint_sccs.successors(scc_a) {
389 let scc_universe_a = scc_universes[scc_a];
390 let scc_universe_b = scc_universes[scc_b];
391 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
392 if scc_universe_a != scc_universe_min {
393 scc_universes[scc_a] = scc_universe_min;
396 "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
397 because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
400 scc_universe_min = scc_universe_min,
401 scc_universe_b = scc_universe_b
407 debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
412 /// For each SCC, we compute a unique `RegionVid` (in fact, the
413 /// minimal one that belongs to the SCC). See
414 /// `scc_representatives` field of `RegionInferenceContext` for
416 fn compute_scc_representatives(
417 constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
418 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
419 ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
420 let num_sccs = constraints_scc.num_sccs();
421 let next_region_vid = definitions.next_index();
422 let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
424 for region_vid in definitions.indices() {
425 let scc = constraints_scc.scc(region_vid);
426 let prev_min = scc_representatives[scc];
427 scc_representatives[scc] = region_vid.min(prev_min);
433 /// Initializes the region variables for each universally
434 /// quantified region (lifetime parameter). The first N variables
435 /// always correspond to the regions appearing in the function
436 /// signature (both named and anonymous) and where-clauses. This
437 /// function iterates over those regions and initializes them with
442 /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
444 /// would initialize two variables like so:
445 /// ```ignore (illustrative)
446 /// R0 = { CFG, R0 } // 'a
447 /// R1 = { CFG, R0, R1 } // 'b
449 /// Here, R0 represents `'a`, and it contains (a) the entire CFG
450 /// and (b) any universally quantified regions that it outlives,
451 /// which in this case is just itself. R1 (`'b`) in contrast also
452 /// outlives `'a` and hence contains R0 and R1.
453 fn init_free_and_bound_regions(&mut self) {
454 // Update the names (if any)
455 for (external_name, variable) in self.universal_regions.named_universal_regions() {
457 "init_universal_regions: region {:?} has external name {:?}",
458 variable, external_name
460 self.definitions[variable].external_name = Some(external_name);
463 for variable in self.definitions.indices() {
464 let scc = self.constraint_sccs.scc(variable);
466 match self.definitions[variable].origin {
467 NllRegionVariableOrigin::FreeRegion => {
468 // For each free, universally quantified region X:
470 // Add all nodes in the CFG to liveness constraints
471 self.liveness_constraints.add_all_points(variable);
472 self.scc_values.add_all_points(scc);
474 // Add `end(X)` into the set for X.
475 self.scc_values.add_element(scc, variable);
478 NllRegionVariableOrigin::Placeholder(placeholder) => {
479 // Each placeholder region is only visible from
480 // its universe `ui` and its extensions. So we
481 // can't just add it into `scc` unless the
482 // universe of the scc can name this region.
483 let scc_universe = self.scc_universes[scc];
484 if scc_universe.can_name(placeholder.universe) {
485 self.scc_values.add_element(scc, placeholder);
488 "init_free_and_bound_regions: placeholder {:?} is \
489 not compatible with universe {:?} of its SCC {:?}",
490 placeholder, scc_universe, scc,
492 self.add_incompatible_universe(scc);
496 NllRegionVariableOrigin::RootEmptyRegion
497 | NllRegionVariableOrigin::Existential { .. } => {
498 // For existential, regions, nothing to do.
504 /// Returns an iterator over all the region indices.
505 pub fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
506 self.definitions.indices()
509 /// Given a universal region in scope on the MIR, returns the
510 /// corresponding index.
512 /// (Panics if `r` is not a registered universal region.)
513 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
514 self.universal_regions.to_region_vid(r)
517 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
518 pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
519 self.universal_regions.annotate(tcx, err)
522 /// Returns `true` if the region `r` contains the point `p`.
524 /// Panics if called before `solve()` executes,
525 pub(crate) fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
526 let scc = self.constraint_sccs.scc(r.to_region_vid());
527 self.scc_values.contains(scc, p)
530 /// Returns access to the value of `r` for debugging purposes.
531 pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
532 let scc = self.constraint_sccs.scc(r.to_region_vid());
533 self.scc_values.region_value_str(scc)
536 /// Returns access to the value of `r` for debugging purposes.
537 pub(crate) fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
538 let scc = self.constraint_sccs.scc(r.to_region_vid());
539 self.scc_universes[scc]
542 /// Once region solving has completed, this function will return
543 /// the member constraints that were applied to the value of a given
544 /// region `r`. See `AppliedMemberConstraint`.
545 pub(crate) fn applied_member_constraints(
548 ) -> &[AppliedMemberConstraint] {
549 let scc = self.constraint_sccs.scc(r.to_region_vid());
550 binary_search_util::binary_search_slice(
551 &self.member_constraints_applied,
552 |applied| applied.member_region_scc,
557 /// Performs region inference and report errors if we see any
558 /// unsatisfiable constraints. If this is a closure, returns the
559 /// region requirements to propagate to our creator, if any.
560 #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
563 infcx: &InferCtxt<'_, 'tcx>,
564 param_env: ty::ParamEnv<'tcx>,
566 polonius_output: Option<Rc<PoloniusOutput>>,
567 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
568 let mir_def_id = body.source.def_id();
569 self.propagate_constraints(body);
571 let mut errors_buffer = RegionErrors::new();
573 // If this is a closure, we can propagate unsatisfied
574 // `outlives_requirements` to our creator, so create a vector
575 // to store those. Otherwise, we'll pass in `None` to the
576 // functions below, which will trigger them to report errors
578 let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
580 self.check_type_tests(
584 outlives_requirements.as_mut(),
588 // In Polonius mode, the errors about missing universal region relations are in the output
589 // and need to be emitted or propagated. Otherwise, we need to check whether the
590 // constraints were too strong, and if so, emit or propagate those errors.
591 if infcx.tcx.sess.opts.debugging_opts.polonius {
592 self.check_polonius_subset_errors(
594 outlives_requirements.as_mut(),
596 polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"),
599 self.check_universal_regions(body, outlives_requirements.as_mut(), &mut errors_buffer);
602 if errors_buffer.is_empty() {
603 self.check_member_constraints(infcx, &mut errors_buffer);
606 let outlives_requirements = outlives_requirements.unwrap_or_default();
608 if outlives_requirements.is_empty() {
609 (None, errors_buffer)
611 let num_external_vids = self.universal_regions.num_global_and_external_regions();
613 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
619 /// Propagate the region constraints: this will grow the values
620 /// for each region variable until all the constraints are
621 /// satisfied. Note that some values may grow **too** large to be
622 /// feasible, but we check this later.
623 #[instrument(skip(self, _body), level = "debug")]
624 fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
625 debug!("constraints={:#?}", {
626 let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
627 constraints.sort_by_key(|c| (c.sup, c.sub));
630 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
634 // To propagate constraints, we walk the DAG induced by the
635 // SCC. For each SCC, we visit its successors and compute
636 // their values, then we union all those values to get our
638 let constraint_sccs = self.constraint_sccs.clone();
639 for scc in constraint_sccs.all_sccs() {
640 self.compute_value_for_scc(scc);
643 // Sort the applied member constraints so we can binary search
644 // through them later.
645 self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
648 /// Computes the value of the SCC `scc_a`, which has not yet been
649 /// computed, by unioning the values of its successors.
650 /// Assumes that all successors have been computed already
651 /// (which is assured by iterating over SCCs in dependency order).
652 #[instrument(skip(self), level = "debug")]
653 fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) {
654 let constraint_sccs = self.constraint_sccs.clone();
656 // Walk each SCC `B` such that `A: B`...
657 for &scc_b in constraint_sccs.successors(scc_a) {
660 // ...and add elements from `B` into `A`. One complication
661 // arises because of universes: If `B` contains something
662 // that `A` cannot name, then `A` can only contain `B` if
663 // it outlives static.
664 if self.universe_compatible(scc_b, scc_a) {
665 // `A` can name everything that is in `B`, so just
667 self.scc_values.add_region(scc_a, scc_b);
669 self.add_incompatible_universe(scc_a);
673 // Now take member constraints into account.
674 let member_constraints = self.member_constraints.clone();
675 for m_c_i in member_constraints.indices(scc_a) {
676 self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i));
679 debug!(value = ?self.scc_values.region_value_str(scc_a));
682 /// Invoked for each `R0 member of [R1..Rn]` constraint.
684 /// `scc` is the SCC containing R0, and `choice_regions` are the
685 /// `R1..Rn` regions -- they are always known to be universal
686 /// regions (and if that's not true, we just don't attempt to
687 /// enforce the constraint).
689 /// The current value of `scc` at the time the method is invoked
690 /// is considered a *lower bound*. If possible, we will modify
691 /// the constraint to set it equal to one of the option regions.
692 /// If we make any changes, returns true, else false.
693 #[instrument(skip(self, member_constraint_index), level = "debug")]
694 fn apply_member_constraint(
696 scc: ConstraintSccIndex,
697 member_constraint_index: NllMemberConstraintIndex,
698 choice_regions: &[ty::RegionVid],
700 // Create a mutable vector of the options. We'll try to winnow
702 let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
704 // Convert to the SCC representative: sometimes we have inference
705 // variables in the member constraint that wind up equated with
706 // universal regions. The scc representative is the minimal numbered
707 // one from the corresponding scc so it will be the universal region
709 for c_r in &mut choice_regions {
710 let scc = self.constraint_sccs.scc(*c_r);
711 *c_r = self.scc_representatives[scc];
714 // The 'member region' in a member constraint is part of the
715 // hidden type, which must be in the root universe. Therefore,
716 // it cannot have any placeholders in its value.
717 assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
719 self.scc_values.placeholders_contained_in(scc).next().is_none(),
720 "scc {:?} in a member constraint has placeholder value: {:?}",
722 self.scc_values.region_value_str(scc),
725 // The existing value for `scc` is a lower-bound. This will
726 // consist of some set `{P} + {LB}` of points `{P}` and
727 // lower-bound free regions `{LB}`. As each choice region `O`
728 // is a free region, it will outlive the points. But we can
729 // only consider the option `O` if `O: LB`.
730 choice_regions.retain(|&o_r| {
732 .universal_regions_outlived_by(scc)
733 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
735 debug!(?choice_regions, "after lb");
737 // Now find all the *upper bounds* -- that is, each UB is a
738 // free region that must outlive the member region `R0` (`UB:
739 // R0`). Therefore, we need only keep an option `O` if `UB: O`
741 let rev_scc_graph = self.reverse_scc_graph();
742 let universal_region_relations = &self.universal_region_relations;
743 for ub in rev_scc_graph.upper_bounds(scc) {
745 choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
747 debug!(?choice_regions, "after ub");
749 // If we ruled everything out, we're done.
750 if choice_regions.is_empty() {
754 // Otherwise, we need to find the minimum remaining choice, if
755 // any, and take that.
756 debug!("choice_regions remaining are {:#?}", choice_regions);
757 let min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> {
758 let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2);
759 let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1);
760 match (r1_outlives_r2, r2_outlives_r1) {
761 (true, true) => Some(r1.min(r2)),
762 (true, false) => Some(r2),
763 (false, true) => Some(r1),
764 (false, false) => None,
767 let mut min_choice = choice_regions[0];
768 for &other_option in &choice_regions[1..] {
769 debug!(?min_choice, ?other_option,);
770 match min(min_choice, other_option) {
771 Some(m) => min_choice = m,
773 debug!(?min_choice, ?other_option, "incomparable; no min choice",);
779 let min_choice_scc = self.constraint_sccs.scc(min_choice);
780 debug!(?min_choice, ?min_choice_scc);
781 if self.scc_values.add_region(scc, min_choice_scc) {
782 self.member_constraints_applied.push(AppliedMemberConstraint {
783 member_region_scc: scc,
785 member_constraint_index,
794 /// Returns `true` if all the elements in the value of `scc_b` are nameable
795 /// in `scc_a`. Used during constraint propagation, and only once
796 /// the value of `scc_b` has been computed.
797 fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
798 let universe_a = self.scc_universes[scc_a];
800 // Quick check: if scc_b's declared universe is a subset of
801 // scc_a's declared universe (typically, both are ROOT), then
802 // it cannot contain any problematic universe elements.
803 if universe_a.can_name(self.scc_universes[scc_b]) {
807 // Otherwise, we have to iterate over the universe elements in
808 // B's value, and check whether all of them are nameable
810 self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
813 /// Extend `scc` so that it can outlive some placeholder region
814 /// from a universe it can't name; at present, the only way for
815 /// this to be true is if `scc` outlives `'static`. This is
816 /// actually stricter than necessary: ideally, we'd support bounds
817 /// like `for<'a: 'b`>` that might then allow us to approximate
818 /// `'a` with `'b` and not `'static`. But it will have to do for
820 fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
821 debug!("add_incompatible_universe(scc={:?})", scc);
823 let fr_static = self.universal_regions.fr_static;
824 self.scc_values.add_all_points(scc);
825 self.scc_values.add_element(scc, fr_static);
828 /// Once regions have been propagated, this method is used to see
829 /// whether the "type tests" produced by typeck were satisfied;
830 /// type tests encode type-outlives relationships like `T:
831 /// 'a`. See `TypeTest` for more details.
834 infcx: &InferCtxt<'_, 'tcx>,
835 param_env: ty::ParamEnv<'tcx>,
837 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
838 errors_buffer: &mut RegionErrors<'tcx>,
842 // Sometimes we register equivalent type-tests that would
843 // result in basically the exact same error being reported to
844 // the user. Avoid that.
845 let mut deduplicate_errors = FxHashSet::default();
847 for type_test in &self.type_tests {
848 debug!("check_type_test: {:?}", type_test);
850 let generic_ty = type_test.generic_kind.to_ty(tcx);
851 if self.eval_verify_bound(
856 type_test.lower_bound,
857 &type_test.verify_bound,
862 if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
863 if self.try_promote_type_test(
868 propagated_outlives_requirements,
874 // Type-test failed. Report the error.
875 let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
877 // Skip duplicate-ish errors.
878 if deduplicate_errors.insert((
880 type_test.lower_bound,
884 "check_type_test: reporting error for erased_generic_kind={:?}, \
885 lower_bound_region={:?}, \
886 type_test.locations={:?}",
887 erased_generic_kind, type_test.lower_bound, type_test.locations,
890 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
895 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
896 /// prove to be satisfied. If this is a closure, we will attempt to
897 /// "promote" this type-test into our `ClosureRegionRequirements` and
898 /// hence pass it up the creator. To do this, we have to phrase the
899 /// type-test in terms of external free regions, as local free
900 /// regions are not nameable by the closure's creator.
902 /// Promotion works as follows: we first check that the type `T`
903 /// contains only regions that the creator knows about. If this is
904 /// true, then -- as a consequence -- we know that all regions in
905 /// the type `T` are free regions that outlive the closure body. If
906 /// false, then promotion fails.
908 /// Once we've promoted T, we have to "promote" `'X` to some region
909 /// that is "external" to the closure. Generally speaking, a region
910 /// may be the union of some points in the closure body as well as
911 /// various free lifetimes. We can ignore the points in the closure
912 /// body: if the type T can be expressed in terms of external regions,
913 /// we know it outlives the points in the closure body. That
914 /// just leaves the free regions.
916 /// The idea then is to lower the `T: 'X` constraint into multiple
917 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
918 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
919 fn try_promote_type_test(
921 infcx: &InferCtxt<'_, 'tcx>,
922 param_env: ty::ParamEnv<'tcx>,
924 type_test: &TypeTest<'tcx>,
925 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
929 let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test;
931 let generic_ty = generic_kind.to_ty(tcx);
932 let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
936 // For each region outlived by lower_bound find a non-local,
937 // universal region (it may be the same region) and add it to
938 // `ClosureOutlivesRequirement`.
939 let r_scc = self.constraint_sccs.scc(*lower_bound);
940 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
941 // Check whether we can already prove that the "subject" outlives `ur`.
942 // If so, we don't have to propagate this requirement to our caller.
944 // To continue the example from the function, if we are trying to promote
945 // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
946 // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
947 // we check whether `T: '1` is something we *can* prove. If so, no need
948 // to propagate that requirement.
950 // This is needed because -- particularly in the case
951 // where `ur` is a local bound -- we are sometimes in a
952 // position to prove things that our caller cannot. See
953 // #53570 for an example.
954 if self.eval_verify_bound(
960 &type_test.verify_bound,
965 debug!("try_promote_type_test: ur={:?}", ur);
967 let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
968 debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
970 // This is slightly too conservative. To show T: '1, given `'2: '1`
971 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
972 // avoid potential non-determinism we approximate this by requiring
974 for upper_bound in non_local_ub {
975 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
976 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
978 let requirement = ClosureOutlivesRequirement {
980 outlived_free_region: upper_bound,
981 blame_span: locations.span(body),
982 category: ConstraintCategory::Boring,
984 debug!("try_promote_type_test: pushing {:#?}", requirement);
985 propagated_outlives_requirements.push(requirement);
991 /// When we promote a type test `T: 'r`, we have to convert the
992 /// type `T` into something we can store in a query result (so
993 /// something allocated for `'tcx`). This is problematic if `ty`
994 /// contains regions. During the course of NLL region checking, we
995 /// will have replaced all of those regions with fresh inference
996 /// variables. To create a test subject, we want to replace those
997 /// inference variables with some region from the closure
998 /// signature -- this is not always possible, so this is a
999 /// fallible process. Presuming we do find a suitable region, we
1000 /// will use it's *external name*, which will be a `RegionKind`
1001 /// variant that can be used in query responses such as
1003 fn try_promote_type_test_subject(
1005 infcx: &InferCtxt<'_, 'tcx>,
1007 ) -> Option<ClosureOutlivesSubject<'tcx>> {
1008 let tcx = infcx.tcx;
1010 debug!("try_promote_type_test_subject(ty = {:?})", ty);
1012 let ty = tcx.fold_regions(ty, |r, _depth| {
1013 let region_vid = self.to_region_vid(r);
1015 // The challenge if this. We have some region variable `r`
1016 // whose value is a set of CFG points and universal
1017 // regions. We want to find if that set is *equivalent* to
1018 // any of the named regions found in the closure.
1020 // To do so, we compute the
1021 // `non_local_universal_upper_bound`. This will be a
1022 // non-local, universal region that is greater than `r`.
1023 // However, it might not be *contained* within `r`, so
1024 // then we further check whether this bound is contained
1025 // in `r`. If so, we can say that `r` is equivalent to the
1028 // Let's work through a few examples. For these, imagine
1029 // that we have 3 non-local regions (I'll denote them as
1030 // `'static`, `'a`, and `'b`, though of course in the code
1031 // they would be represented with indices) where:
1036 // First, let's assume that `r` is some existential
1037 // variable with an inferred value `{'a, 'static}` (plus
1038 // some CFG nodes). In this case, the non-local upper
1039 // bound is `'static`, since that outlives `'a`. `'static`
1040 // is also a member of `r` and hence we consider `r`
1041 // equivalent to `'static` (and replace it with
1044 // Now let's consider the inferred value `{'a, 'b}`. This
1045 // means `r` is effectively `'a | 'b`. I'm not sure if
1046 // this can come about, actually, but assuming it did, we
1047 // would get a non-local upper bound of `'static`. Since
1048 // `'static` is not contained in `r`, we would fail to
1049 // find an equivalent.
1050 let upper_bound = self.non_local_universal_upper_bound(region_vid);
1051 if self.region_contains(region_vid, upper_bound) {
1052 self.definitions[upper_bound].external_name.unwrap_or(r)
1054 // In the case of a failure, use a `ReVar` result. This will
1055 // cause the `needs_infer` later on to return `None`.
1060 debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1062 // `needs_infer` will only be true if we failed to promote some region.
1063 if ty.needs_infer() {
1067 Some(ClosureOutlivesSubject::Ty(ty))
1070 /// Given some universal or existential region `r`, finds a
1071 /// non-local, universal region `r+` that outlives `r` at entry to (and
1072 /// exit from) the closure. In the worst case, this will be
1075 /// This is used for two purposes. First, if we are propagated
1076 /// some requirement `T: r`, we can use this method to enlarge `r`
1077 /// to something we can encode for our creator (which only knows
1078 /// about non-local, universal regions). It is also used when
1079 /// encoding `T` as part of `try_promote_type_test_subject` (see
1080 /// that fn for details).
1082 /// This is based on the result `'y` of `universal_upper_bound`,
1083 /// except that it converts further takes the non-local upper
1084 /// bound of `'y`, so that the final result is non-local.
1085 fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1086 debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1088 let lub = self.universal_upper_bound(r);
1090 // Grow further to get smallest universal region known to
1092 let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1094 debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1099 /// Returns a universally quantified region that outlives the
1100 /// value of `r` (`r` may be existentially or universally
1103 /// Since `r` is (potentially) an existential region, it has some
1104 /// value which may include (a) any number of points in the CFG
1105 /// and (b) any number of `end('x)` elements of universally
1106 /// quantified regions. To convert this into a single universal
1107 /// region we do as follows:
1109 /// - Ignore the CFG points in `'r`. All universally quantified regions
1110 /// include the CFG anyhow.
1111 /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1113 #[instrument(skip(self), level = "debug")]
1114 pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1115 debug!(r = %self.region_value_str(r));
1117 // Find the smallest universal region that contains all other
1118 // universal regions within `region`.
1119 let mut lub = self.universal_regions.fr_fn_body;
1120 let r_scc = self.constraint_sccs.scc(r);
1121 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1122 lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1130 /// Like `universal_upper_bound`, but returns an approximation more suitable
1131 /// for diagnostics. If `r` contains multiple disjoint universal regions
1132 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1133 /// This corresponds to picking named regions over unnamed regions
1134 /// (e.g. picking early-bound regions over a closure late-bound region).
1136 /// This means that the returned value may not be a true upper bound, since
1137 /// only 'static is known to outlive disjoint universal regions.
1138 /// Therefore, this method should only be used in diagnostic code,
1139 /// where displaying *some* named universal region is better than
1140 /// falling back to 'static.
1141 pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1142 debug!("approx_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1144 // Find the smallest universal region that contains all other
1145 // universal regions within `region`.
1146 let mut lub = self.universal_regions.fr_fn_body;
1147 let r_scc = self.constraint_sccs.scc(r);
1148 let static_r = self.universal_regions.fr_static;
1149 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1150 let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1151 debug!("approx_universal_upper_bound: ur={:?} lub={:?} new_lub={:?}", ur, lub, new_lub);
1152 // The upper bound of two non-static regions is static: this
1153 // means we know nothing about the relationship between these
1154 // two regions. Pick a 'better' one to use when constructing
1156 if ur != static_r && lub != static_r && new_lub == static_r {
1157 // Prefer the region with an `external_name` - this
1158 // indicates that the region is early-bound, so working with
1159 // it can produce a nicer error.
1160 if self.region_definition(ur).external_name.is_some() {
1162 } else if self.region_definition(lub).external_name.is_some() {
1163 // Leave lub unchanged
1165 // If we get here, we don't have any reason to prefer
1166 // one region over the other. Just pick the
1167 // one with the lower index for now.
1168 lub = std::cmp::min(ur, lub);
1175 debug!("approx_universal_upper_bound: r={:?} lub={:?}", r, lub);
1180 /// Tests if `test` is true when applied to `lower_bound` at
1182 fn eval_verify_bound(
1184 infcx: &InferCtxt<'_, 'tcx>,
1185 param_env: ty::ParamEnv<'tcx>,
1187 generic_ty: Ty<'tcx>,
1188 lower_bound: RegionVid,
1189 verify_bound: &VerifyBound<'tcx>,
1191 debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1193 match verify_bound {
1194 VerifyBound::IfEq(verify_if_eq_b) => {
1195 self.eval_if_eq(infcx, param_env, generic_ty, lower_bound, *verify_if_eq_b)
1198 VerifyBound::IsEmpty => {
1199 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1200 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1203 VerifyBound::OutlivedBy(r) => {
1204 let r_vid = self.to_region_vid(*r);
1205 self.eval_outlives(r_vid, lower_bound)
1208 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1209 self.eval_verify_bound(
1219 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1220 self.eval_verify_bound(
1234 infcx: &InferCtxt<'_, 'tcx>,
1235 param_env: ty::ParamEnv<'tcx>,
1236 generic_ty: Ty<'tcx>,
1237 lower_bound: RegionVid,
1238 verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
1240 let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
1241 let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
1242 match test_type_match::extract_verify_if_eq(
1249 let r_vid = self.to_region_vid(r);
1250 self.eval_outlives(r_vid, lower_bound)
1256 /// This is a conservative normalization procedure. It takes every
1257 /// free region in `value` and replaces it with the
1258 /// "representative" of its SCC (see `scc_representatives` field).
1259 /// We are guaranteed that if two values normalize to the same
1260 /// thing, then they are equal; this is a conservative check in
1261 /// that they could still be equal even if they normalize to
1262 /// different results. (For example, there might be two regions
1263 /// with the same value that are not in the same SCC).
1265 /// N.B., this is not an ideal approach and I would like to revisit
1266 /// it. However, it works pretty well in practice. In particular,
1267 /// this is needed to deal with projection outlives bounds like
1270 /// <T as Foo<'0>>::Item: '1
1273 /// In particular, this routine winds up being important when
1274 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1275 /// environment. In this case, if we can show that `'0 == 'a`,
1276 /// and that `'b: '1`, then we know that the clause is
1277 /// satisfied. In such cases, particularly due to limitations of
1278 /// the trait solver =), we usually wind up with a where-clause like
1279 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1280 /// a constraint, and thus ensures that they are in the same SCC.
1282 /// So why can't we do a more correct routine? Well, we could
1283 /// *almost* use the `relate_tys` code, but the way it is
1284 /// currently setup it creates inference variables to deal with
1285 /// higher-ranked things and so forth, and right now the inference
1286 /// context is not permitted to make more inference variables. So
1287 /// we use this kind of hacky solution.
1288 fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1290 T: TypeFoldable<'tcx>,
1292 tcx.fold_regions(value, |r, _db| {
1293 let vid = self.to_region_vid(r);
1294 let scc = self.constraint_sccs.scc(vid);
1295 let repr = self.scc_representatives[scc];
1296 tcx.mk_region(ty::ReVar(repr))
1300 // Evaluate whether `sup_region == sub_region`.
1301 fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1302 self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1305 // Evaluate whether `sup_region: sub_region`.
1306 #[instrument(skip(self), level = "debug")]
1307 fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1309 "eval_outlives: sup_region's value = {:?} universal={:?}",
1310 self.region_value_str(sup_region),
1311 self.universal_regions.is_universal_region(sup_region),
1314 "eval_outlives: sub_region's value = {:?} universal={:?}",
1315 self.region_value_str(sub_region),
1316 self.universal_regions.is_universal_region(sub_region),
1319 let sub_region_scc = self.constraint_sccs.scc(sub_region);
1320 let sup_region_scc = self.constraint_sccs.scc(sup_region);
1322 // If we are checking that `'sup: 'sub`, and `'sub` contains
1323 // some placeholder that `'sup` cannot name, then this is only
1324 // true if `'sup` outlives static.
1325 if !self.universe_compatible(sub_region_scc, sup_region_scc) {
1327 "eval_outlives: sub universe `{sub_region_scc:?}` is not nameable \
1328 by super `{sup_region_scc:?}`, promoting to static",
1331 return self.eval_outlives(sup_region, self.universal_regions.fr_static);
1334 // Both the `sub_region` and `sup_region` consist of the union
1335 // of some number of universal regions (along with the union
1336 // of various points in the CFG; ignore those points for
1337 // now). Therefore, the sup-region outlives the sub-region if,
1338 // for each universal region R1 in the sub-region, there
1339 // exists some region R2 in the sup-region that outlives R1.
1340 let universal_outlives =
1341 self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1343 .universal_regions_outlived_by(sup_region_scc)
1344 .any(|r2| self.universal_region_relations.outlives(r2, r1))
1347 if !universal_outlives {
1349 "eval_outlives: returning false because sub region contains a universal region not present in super"
1354 // Now we have to compare all the points in the sub region and make
1355 // sure they exist in the sup region.
1357 if self.universal_regions.is_universal_region(sup_region) {
1358 // Micro-opt: universal regions contain all points.
1360 "eval_outlives: returning true because super is universal and hence contains all points"
1365 let result = self.scc_values.contains_points(sup_region_scc, sub_region_scc);
1366 debug!("returning {} because of comparison between points in sup/sub", result);
1370 /// Once regions have been propagated, this method is used to see
1371 /// whether any of the constraints were too strong. In particular,
1372 /// we want to check for a case where a universally quantified
1373 /// region exceeded its bounds. Consider:
1374 /// ```compile_fail,E0312
1375 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1377 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1378 /// and hence we establish (transitively) a constraint that
1379 /// `'a: 'b`. The `propagate_constraints` code above will
1380 /// therefore add `end('a)` into the region for `'b` -- but we
1381 /// have no evidence that `'b` outlives `'a`, so we want to report
1384 /// If `propagated_outlives_requirements` is `Some`, then we will
1385 /// push unsatisfied obligations into there. Otherwise, we'll
1386 /// report them as errors.
1387 fn check_universal_regions(
1390 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1391 errors_buffer: &mut RegionErrors<'tcx>,
1393 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1394 match fr_definition.origin {
1395 NllRegionVariableOrigin::FreeRegion => {
1396 // Go through each of the universal regions `fr` and check that
1397 // they did not grow too large, accumulating any requirements
1398 // for our caller into the `outlives_requirements` vector.
1399 self.check_universal_region(
1402 &mut propagated_outlives_requirements,
1407 NllRegionVariableOrigin::Placeholder(placeholder) => {
1408 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1411 NllRegionVariableOrigin::RootEmptyRegion
1412 | NllRegionVariableOrigin::Existential { .. } => {
1413 // nothing to check here
1419 /// Checks if Polonius has found any unexpected free region relations.
1421 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1422 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1423 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1424 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1426 /// More details can be found in this blog post by Niko:
1427 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1429 /// In the canonical example
1430 /// ```compile_fail,E0312
1431 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1433 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1434 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1435 /// constraint holds.
1437 /// If `propagated_outlives_requirements` is `Some`, then we will
1438 /// push unsatisfied obligations into there. Otherwise, we'll
1439 /// report them as errors.
1440 fn check_polonius_subset_errors(
1443 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1444 errors_buffer: &mut RegionErrors<'tcx>,
1445 polonius_output: Rc<PoloniusOutput>,
1448 "check_polonius_subset_errors: {} subset_errors",
1449 polonius_output.subset_errors.len()
1452 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1453 // declared ("known") was found by Polonius, so emit an error, or propagate the
1454 // requirements for our caller into the `propagated_outlives_requirements` vector.
1456 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1457 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1458 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1459 // and the "superset origin" is the outlived "shorter free region".
1461 // Note: Polonius will produce a subset error at every point where the unexpected
1462 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1463 // for diagnostics in the future, e.g. to point more precisely at the key locations
1464 // requiring this constraint to hold. However, the error and diagnostics code downstream
1465 // expects that these errors are not duplicated (and that they are in a certain order).
1466 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1467 // anonymous lifetimes for example, could give these names differently, while others like
1468 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1469 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1470 // CFG-location ordering.
1471 let mut subset_errors: Vec<_> = polonius_output
1474 .flat_map(|(_location, subset_errors)| subset_errors.iter())
1476 subset_errors.sort();
1477 subset_errors.dedup();
1479 for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1481 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1483 longer_fr, shorter_fr
1486 let propagated = self.try_propagate_universal_region_error(
1490 &mut propagated_outlives_requirements,
1492 if propagated == RegionRelationCheckResult::Error {
1493 errors_buffer.push(RegionErrorKind::RegionError {
1494 longer_fr: *longer_fr,
1495 shorter_fr: *shorter_fr,
1496 fr_origin: NllRegionVariableOrigin::FreeRegion,
1502 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1503 // a more complete picture on how to separate this responsibility.
1504 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1505 match fr_definition.origin {
1506 NllRegionVariableOrigin::FreeRegion => {
1507 // handled by polonius above
1510 NllRegionVariableOrigin::Placeholder(placeholder) => {
1511 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1514 NllRegionVariableOrigin::RootEmptyRegion
1515 | NllRegionVariableOrigin::Existential { .. } => {
1516 // nothing to check here
1522 /// Checks the final value for the free region `fr` to see if it
1523 /// grew too large. In particular, examine what `end(X)` points
1524 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1525 /// fr`, we want to check that `fr: X`. If not, that's either an
1526 /// error, or something we have to propagate to our creator.
1528 /// Things that are to be propagated are accumulated into the
1529 /// `outlives_requirements` vector.
1531 skip(self, body, propagated_outlives_requirements, errors_buffer),
1534 fn check_universal_region(
1537 longer_fr: RegionVid,
1538 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1539 errors_buffer: &mut RegionErrors<'tcx>,
1541 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1543 // Because this free region must be in the ROOT universe, we
1544 // know it cannot contain any bound universes.
1545 assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1546 debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1548 // Only check all of the relations for the main representative of each
1549 // SCC, otherwise just check that we outlive said representative. This
1550 // reduces the number of redundant relations propagated out of
1552 // Note that the representative will be a universal region if there is
1553 // one in this SCC, so we will always check the representative here.
1554 let representative = self.scc_representatives[longer_fr_scc];
1555 if representative != longer_fr {
1556 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1560 propagated_outlives_requirements,
1562 errors_buffer.push(RegionErrorKind::RegionError {
1564 shorter_fr: representative,
1565 fr_origin: NllRegionVariableOrigin::FreeRegion,
1572 // Find every region `o` such that `fr: o`
1573 // (because `fr` includes `end(o)`).
1574 let mut error_reported = false;
1575 for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1576 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1580 propagated_outlives_requirements,
1582 // We only report the first region error. Subsequent errors are hidden so as
1583 // not to overwhelm the user, but we do record them so as to potentially print
1584 // better diagnostics elsewhere...
1585 errors_buffer.push(RegionErrorKind::RegionError {
1588 fr_origin: NllRegionVariableOrigin::FreeRegion,
1589 is_reported: !error_reported,
1592 error_reported = true;
1597 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1598 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1600 fn check_universal_region_relation(
1602 longer_fr: RegionVid,
1603 shorter_fr: RegionVid,
1605 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1606 ) -> RegionRelationCheckResult {
1607 // If it is known that `fr: o`, carry on.
1608 if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1609 RegionRelationCheckResult::Ok
1611 // If we are not in a context where we can't propagate errors, or we
1612 // could not shrink `fr` to something smaller, then just report an
1615 // Note: in this case, we use the unapproximated regions to report the
1616 // error. This gives better error messages in some cases.
1617 self.try_propagate_universal_region_error(
1621 propagated_outlives_requirements,
1626 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1627 /// creator. If we cannot, then the caller should report an error to the user.
1628 fn try_propagate_universal_region_error(
1630 longer_fr: RegionVid,
1631 shorter_fr: RegionVid,
1633 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1634 ) -> RegionRelationCheckResult {
1635 if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1636 // Shrink `longer_fr` until we find a non-local region (if we do).
1637 // We'll call it `fr-` -- it's ever so slightly smaller than
1639 if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1641 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1643 let blame_span_category = self.find_outlives_blame_span(
1646 NllRegionVariableOrigin::FreeRegion,
1650 // Grow `shorter_fr` until we find some non-local regions. (We
1651 // always will.) We'll call them `shorter_fr+` -- they're ever
1652 // so slightly larger than `shorter_fr`.
1653 let shorter_fr_plus =
1654 self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1656 "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1659 for fr in shorter_fr_plus {
1660 // Push the constraint `fr-: shorter_fr+`
1661 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1662 subject: ClosureOutlivesSubject::Region(fr_minus),
1663 outlived_free_region: fr,
1664 blame_span: blame_span_category.1.span,
1665 category: blame_span_category.0,
1668 return RegionRelationCheckResult::Propagated;
1672 RegionRelationCheckResult::Error
1675 fn check_bound_universal_region(
1677 longer_fr: RegionVid,
1678 placeholder: ty::PlaceholderRegion,
1679 errors_buffer: &mut RegionErrors<'tcx>,
1681 debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1683 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1684 debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1686 // If we have some bound universal region `'a`, then the only
1687 // elements it can contain is itself -- we don't know anything
1689 let Some(error_element) = ({
1690 self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element {
1691 RegionElement::Location(_) => true,
1692 RegionElement::RootUniversalRegion(_) => true,
1693 RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1698 debug!("check_bound_universal_region: error_element = {:?}", error_element);
1700 // Find the region that introduced this `error_element`.
1701 errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1708 fn check_member_constraints(
1710 infcx: &InferCtxt<'_, 'tcx>,
1711 errors_buffer: &mut RegionErrors<'tcx>,
1713 let member_constraints = self.member_constraints.clone();
1714 for m_c_i in member_constraints.all_indices() {
1715 debug!("check_member_constraint(m_c_i={:?})", m_c_i);
1716 let m_c = &member_constraints[m_c_i];
1717 let member_region_vid = m_c.member_region_vid;
1719 "check_member_constraint: member_region_vid={:?} with value {}",
1721 self.region_value_str(member_region_vid),
1723 let choice_regions = member_constraints.choice_regions(m_c_i);
1724 debug!("check_member_constraint: choice_regions={:?}", choice_regions);
1726 // Did the member region wind up equal to any of the option regions?
1728 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1730 debug!("check_member_constraint: evaluated as equal to {:?}", o);
1734 // If not, report an error.
1735 let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1736 errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1737 span: m_c.definition_span,
1738 hidden_ty: m_c.hidden_ty,
1744 /// We have a constraint `fr1: fr2` that is not satisfied, where
1745 /// `fr2` represents some universal region. Here, `r` is some
1746 /// region where we know that `fr1: r` and this function has the
1747 /// job of determining whether `r` is "to blame" for the fact that
1748 /// `fr1: fr2` is required.
1750 /// This is true under two conditions:
1753 /// - `fr2` is `'static` and `r` is some placeholder in a universe
1754 /// that cannot be named by `fr1`; in that case, we will require
1755 /// that `fr1: 'static` because it is the only way to `fr1: r` to
1756 /// be satisfied. (See `add_incompatible_universe`.)
1757 pub(crate) fn provides_universal_region(
1763 debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1766 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1769 debug!("provides_universal_region: result = {:?}", result);
1773 /// If `r2` represents a placeholder region, then this returns
1774 /// `true` if `r1` cannot name that placeholder in its
1775 /// value; otherwise, returns `false`.
1776 pub(crate) fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1777 debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1779 match self.definitions[r2].origin {
1780 NllRegionVariableOrigin::Placeholder(placeholder) => {
1781 let universe1 = self.definitions[r1].universe;
1783 "cannot_name_value_of: universe1={:?} placeholder={:?}",
1784 universe1, placeholder
1786 universe1.cannot_name(placeholder.universe)
1789 NllRegionVariableOrigin::RootEmptyRegion
1790 | NllRegionVariableOrigin::FreeRegion
1791 | NllRegionVariableOrigin::Existential { .. } => false,
1795 pub(crate) fn retrieve_closure_constraint_info(
1798 constraint: &OutlivesConstraint<'tcx>,
1799 ) -> BlameConstraint<'tcx> {
1800 let loc = match constraint.locations {
1801 Locations::All(span) => {
1802 return BlameConstraint {
1803 category: constraint.category,
1804 from_closure: false,
1805 cause: ObligationCause::dummy_with_span(span),
1806 variance_info: constraint.variance_info,
1809 Locations::Single(loc) => loc,
1812 let opt_span_category =
1813 self.closure_bounds_mapping[&loc].get(&(constraint.sup, constraint.sub));
1815 .map(|&(category, span)| BlameConstraint {
1818 cause: ObligationCause::dummy_with_span(span),
1819 variance_info: constraint.variance_info,
1821 .unwrap_or(BlameConstraint {
1822 category: constraint.category,
1823 from_closure: false,
1824 cause: ObligationCause::dummy_with_span(constraint.span),
1825 variance_info: constraint.variance_info,
1829 /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1830 pub(crate) fn find_outlives_blame_span(
1834 fr1_origin: NllRegionVariableOrigin,
1836 ) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
1837 let BlameConstraint { category, cause, .. } =
1838 self.best_blame_constraint(body, fr1, fr1_origin, |r| {
1839 self.provides_universal_region(r, fr1, fr2)
1844 /// Walks the graph of constraints (where `'a: 'b` is considered
1845 /// an edge `'a -> 'b`) to find all paths from `from_region` to
1846 /// `to_region`. The paths are accumulated into the vector
1847 /// `results`. The paths are stored as a series of
1848 /// `ConstraintIndex` values -- in other words, a list of *edges*.
1850 /// Returns: a series of constraints as well as the region `R`
1851 /// that passed the target test.
1852 pub(crate) fn find_constraint_paths_between_regions(
1854 from_region: RegionVid,
1855 target_test: impl Fn(RegionVid) -> bool,
1856 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1857 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1858 context[from_region] = Trace::StartRegion;
1860 // Use a deque so that we do a breadth-first search. We will
1861 // stop at the first match, which ought to be the shortest
1862 // path (fewest constraints).
1863 let mut deque = VecDeque::new();
1864 deque.push_back(from_region);
1866 while let Some(r) = deque.pop_front() {
1868 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1871 self.region_value_str(r),
1874 // Check if we reached the region we were looking for. If so,
1875 // we can reconstruct the path that led to it and return it.
1877 let mut result = vec![];
1880 match context[p].clone() {
1881 Trace::NotVisited => {
1882 bug!("found unvisited region {:?} on path to {:?}", p, r)
1885 Trace::FromOutlivesConstraint(c) => {
1890 Trace::StartRegion => {
1892 return Some((result, r));
1898 // Otherwise, walk over the outgoing constraints and
1899 // enqueue any regions we find, keeping track of how we
1902 // A constraint like `'r: 'x` can come from our constraint
1904 let fr_static = self.universal_regions.fr_static;
1905 let outgoing_edges_from_graph =
1906 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1908 // Always inline this closure because it can be hot.
1909 let mut handle_constraint = #[inline(always)]
1910 |constraint: OutlivesConstraint<'tcx>| {
1911 debug_assert_eq!(constraint.sup, r);
1912 let sub_region = constraint.sub;
1913 if let Trace::NotVisited = context[sub_region] {
1914 context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1915 deque.push_back(sub_region);
1919 // This loop can be hot.
1920 for constraint in outgoing_edges_from_graph {
1921 handle_constraint(constraint);
1924 // Member constraints can also give rise to `'r: 'x` edges that
1925 // were not part of the graph initially, so watch out for those.
1926 // (But they are extremely rare; this loop is very cold.)
1927 for constraint in self.applied_member_constraints(r) {
1928 let p_c = &self.member_constraints[constraint.member_constraint_index];
1929 let constraint = OutlivesConstraint {
1931 sub: constraint.min_choice,
1932 locations: Locations::All(p_c.definition_span),
1933 span: p_c.definition_span,
1934 category: ConstraintCategory::OpaqueType,
1935 variance_info: ty::VarianceDiagInfo::default(),
1937 handle_constraint(constraint);
1944 /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1945 #[instrument(skip(self), level = "trace")]
1946 pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1947 trace!(scc = ?self.constraint_sccs.scc(fr1));
1948 trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1949 self.find_constraint_paths_between_regions(fr1, |r| {
1950 // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1951 trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1952 self.liveness_constraints.contains(r, elem)
1955 // If we fail to find that, we may find some `r` such that
1956 // `fr1: r` and `r` is a placeholder from some universe
1957 // `fr1` cannot name. This would force `fr1` to be
1959 self.find_constraint_paths_between_regions(fr1, |r| {
1960 self.cannot_name_placeholder(fr1, r)
1964 // If we fail to find THAT, it may be that `fr1` is a
1965 // placeholder that cannot "fit" into its SCC. In that
1966 // case, there should be some `r` where `fr1: r` and `fr1` is a
1967 // placeholder that `r` cannot name. We can blame that
1970 // Remember that if `R1: R2`, then the universe of R1
1971 // must be able to name the universe of R2, because R2 will
1972 // be at least `'empty(Universe(R2))`, and `R1` must be at
1973 // larger than that.
1974 self.find_constraint_paths_between_regions(fr1, |r| {
1975 self.cannot_name_placeholder(r, fr1)
1978 .map(|(_path, r)| r)
1982 /// Get the region outlived by `longer_fr` and live at `element`.
1983 pub(crate) fn region_from_element(
1985 longer_fr: RegionVid,
1986 element: &RegionElement,
1989 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1990 RegionElement::RootUniversalRegion(r) => r,
1991 RegionElement::PlaceholderRegion(error_placeholder) => self
1994 .find_map(|(r, definition)| match definition.origin {
1995 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
2002 /// Get the region definition of `r`.
2003 pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
2004 &self.definitions[r]
2007 /// Check if the SCC of `r` contains `upper`.
2008 pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
2009 let r_scc = self.constraint_sccs.scc(r);
2010 self.scc_values.contains(r_scc, upper)
2013 pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
2014 self.universal_regions.as_ref()
2017 /// Tries to find the best constraint to blame for the fact that
2018 /// `R: from_region`, where `R` is some region that meets
2019 /// `target_test`. This works by following the constraint graph,
2020 /// creating a constraint path that forces `R` to outlive
2021 /// `from_region`, and then finding the best choices within that
2023 pub(crate) fn best_blame_constraint(
2026 from_region: RegionVid,
2027 from_region_origin: NllRegionVariableOrigin,
2028 target_test: impl Fn(RegionVid) -> bool,
2029 ) -> BlameConstraint<'tcx> {
2031 "best_blame_constraint(from_region={:?}, from_region_origin={:?})",
2032 from_region, from_region_origin
2036 let (path, target_region) =
2037 self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
2039 "best_blame_constraint: path={:#?}",
2042 "{:?} ({:?}: {:?})",
2044 self.constraint_sccs.scc(c.sup),
2045 self.constraint_sccs.scc(c.sub),
2047 .collect::<Vec<_>>()
2050 // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
2051 // Instead, we use it to produce an improved `ObligationCauseCode`.
2052 // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
2053 // constraints. Currently, we just pick the first one.
2054 let cause_code = path
2056 .find_map(|constraint| {
2057 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
2058 // We currently do not store the `DefId` in the `ConstraintCategory`
2059 // for performances reasons. The error reporting code used by NLL only
2060 // uses the span, so this doesn't cause any problems at the moment.
2061 Some(ObligationCauseCode::BindingObligation(
2062 CRATE_DEF_ID.to_def_id(),
2069 .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2071 // Classify each of the constraints along the path.
2072 let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2075 if constraint.category == ConstraintCategory::ClosureBounds {
2076 self.retrieve_closure_constraint_info(body, &constraint)
2079 category: constraint.category,
2080 from_closure: false,
2081 cause: ObligationCause::new(
2086 variance_info: constraint.variance_info,
2091 debug!("best_blame_constraint: categorized_path={:#?}", categorized_path);
2093 // To find the best span to cite, we first try to look for the
2094 // final constraint that is interesting and where the `sup` is
2095 // not unified with the ultimate target region. The reason
2096 // for this is that we have a chain of constraints that lead
2097 // from the source to the target region, something like:
2099 // '0: '1 ('0 is the source)
2104 // '5: '6 ('6 is the target)
2106 // Some of those regions are unified with `'6` (in the same
2107 // SCC). We want to screen those out. After that point, the
2108 // "closest" constraint we have to the end is going to be the
2109 // most likely to be the point where the value escapes -- but
2110 // we still want to screen for an "interesting" point to
2111 // highlight (e.g., a call site or something).
2112 let target_scc = self.constraint_sccs.scc(target_region);
2113 let mut range = 0..path.len();
2115 // As noted above, when reporting an error, there is typically a chain of constraints
2116 // leading from some "source" region which must outlive some "target" region.
2117 // In most cases, we prefer to "blame" the constraints closer to the target --
2118 // but there is one exception. When constraints arise from higher-ranked subtyping,
2119 // we generally prefer to blame the source value,
2120 // as the "target" in this case tends to be some type annotation that the user gave.
2121 // Therefore, if we find that the region origin is some instantiation
2122 // of a higher-ranked region, we start our search from the "source" point
2123 // rather than the "target", and we also tweak a few other things.
2125 // An example might be this bit of Rust code:
2128 // let x: fn(&'static ()) = |_| {};
2129 // let y: for<'a> fn(&'a ()) = x;
2132 // In MIR, this will be converted into a combination of assignments and type ascriptions.
2133 // In particular, the 'static is imposed through a type ascription:
2137 // AscribeUserType(x, fn(&'static ())
2141 // We wind up ultimately with constraints like
2144 // !a: 'temp1 // from the `y = x` statement
2146 // 'temp2: 'static // from the AscribeUserType
2149 // and here we prefer to blame the source (the y = x statement).
2150 let blame_source = match from_region_origin {
2151 NllRegionVariableOrigin::FreeRegion
2152 | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2153 NllRegionVariableOrigin::RootEmptyRegion
2154 | NllRegionVariableOrigin::Placeholder(_)
2155 | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2158 let find_region = |i: &usize| {
2159 let constraint = &path[*i];
2161 let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2164 match categorized_path[*i].category {
2165 ConstraintCategory::OpaqueType
2166 | ConstraintCategory::Boring
2167 | ConstraintCategory::BoringNoLocation
2168 | ConstraintCategory::Internal
2169 | ConstraintCategory::Predicate(_) => false,
2170 ConstraintCategory::TypeAnnotation
2171 | ConstraintCategory::Return(_)
2172 | ConstraintCategory::Yield => true,
2173 _ => constraint_sup_scc != target_scc,
2177 categorized_path[*i].category,
2178 ConstraintCategory::OpaqueType
2179 | ConstraintCategory::Boring
2180 | ConstraintCategory::BoringNoLocation
2181 | ConstraintCategory::Internal
2182 | ConstraintCategory::Predicate(_)
2188 if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2191 "best_blame_constraint: best_choice={:?} blame_source={}",
2192 best_choice, blame_source
2195 if let Some(i) = best_choice {
2196 if let Some(next) = categorized_path.get(i + 1) {
2197 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2198 && next.category == ConstraintCategory::OpaqueType
2200 // The return expression is being influenced by the return type being
2201 // impl Trait, point at the return type and not the return expr.
2202 return next.clone();
2206 if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2208 let field = categorized_path.iter().find_map(|p| {
2209 if let ConstraintCategory::ClosureUpvar(f) = p.category {
2216 if let Some(field) = field {
2217 categorized_path[i].category =
2218 ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2222 return categorized_path[i].clone();
2225 // If that search fails, that is.. unusual. Maybe everything
2226 // is in the same SCC or something. In that case, find what
2227 // appears to be the most interesting point to report to the
2228 // user via an even more ad-hoc guess.
2229 categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2230 debug!("best_blame_constraint: sorted_path={:#?}", categorized_path);
2232 categorized_path.remove(0)
2235 pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2236 self.universe_causes[&universe].clone()
2240 impl<'tcx> RegionDefinition<'tcx> {
2241 fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2242 // Create a new region definition. Note that, for free
2243 // regions, the `external_name` field gets updated later in
2244 // `init_universal_regions`.
2246 let origin = match rv_origin {
2247 RegionVariableOrigin::Nll(origin) => origin,
2248 _ => NllRegionVariableOrigin::Existential { from_forall: false },
2251 Self { origin, universe, external_name: None }
2255 pub trait ClosureRegionRequirementsExt<'tcx> {
2256 fn apply_requirements(
2259 closure_def_id: DefId,
2260 closure_substs: SubstsRef<'tcx>,
2261 ) -> Vec<QueryOutlivesConstraint<'tcx>>;
2264 impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> {
2265 /// Given an instance T of the closure type, this method
2266 /// instantiates the "extra" requirements that we computed for the
2267 /// closure into the inference context. This has the effect of
2268 /// adding new outlives obligations to existing variables.
2270 /// As described on `ClosureRegionRequirements`, the extra
2271 /// requirements are expressed in terms of regionvids that index
2272 /// into the free regions that appear on the closure type. So, to
2273 /// do this, we first copy those regions out from the type T into
2274 /// a vector. Then we can just index into that vector to extract
2275 /// out the corresponding region from T and apply the
2277 fn apply_requirements(
2280 closure_def_id: DefId,
2281 closure_substs: SubstsRef<'tcx>,
2282 ) -> Vec<QueryOutlivesConstraint<'tcx>> {
2284 "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
2285 closure_def_id, closure_substs
2288 // Extract the values of the free regions in `closure_substs`
2289 // into a vector. These are the regions that we will be
2290 // relating to one another.
2291 let closure_mapping = &UniversalRegions::closure_mapping(
2294 self.num_external_vids,
2295 tcx.typeck_root_def_id(closure_def_id),
2297 debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
2299 // Create the predicates.
2300 self.outlives_requirements
2302 .map(|outlives_requirement| {
2303 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
2305 match outlives_requirement.subject {
2306 ClosureOutlivesSubject::Region(region) => {
2307 let region = closure_mapping[region];
2309 "apply_requirements: region={:?} \
2310 outlived_region={:?} \
2311 outlives_requirement={:?}",
2312 region, outlived_region, outlives_requirement,
2314 ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
2317 ClosureOutlivesSubject::Ty(ty) => {
2319 "apply_requirements: ty={:?} \
2320 outlived_region={:?} \
2321 outlives_requirement={:?}",
2322 ty, outlived_region, outlives_requirement,
2324 ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
2332 #[derive(Clone, Debug)]
2333 pub struct BlameConstraint<'tcx> {
2334 pub category: ConstraintCategory<'tcx>,
2335 pub from_closure: bool,
2336 pub cause: ObligationCause<'tcx>,
2337 pub variance_info: ty::VarianceDiagInfo<'tcx>,