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::region_constraints::{GenericKind, VarInfos, VerifyBound};
14 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin};
15 use rustc_middle::mir::{
16 Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
17 ConstraintCategory, Local, Location, ReturnConstraint,
19 use rustc_middle::traits::ObligationCause;
20 use rustc_middle::traits::ObligationCauseCode;
21 use rustc_middle::ty::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable};
26 graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
28 diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
29 member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
30 nll::{PoloniusOutput, ToRegionVid},
31 region_infer::reverse_sccs::ReverseSccGraph,
32 region_infer::values::{
33 LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
36 type_check::{free_region_relations::UniversalRegionRelations, Locations},
37 universal_regions::UniversalRegions,
47 pub struct RegionInferenceContext<'tcx> {
48 /// Contains the definition for every region variable. Region
49 /// variables are identified by their index (`RegionVid`). The
50 /// definition contains information about where the region came
51 /// from as well as its final inferred value.
52 definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
54 /// The liveness constraints added to each region. For most
55 /// regions, these start out empty and steadily grow, though for
56 /// each universally quantified region R they start out containing
57 /// the entire CFG and `end(R)`.
58 liveness_constraints: LivenessValues<RegionVid>,
60 /// The outlives constraints computed by the type-check.
61 constraints: Frozen<OutlivesConstraintSet<'tcx>>,
63 /// The constraint-set, but in graph form, making it easy to traverse
64 /// the constraints adjacent to a particular region. Used to construct
65 /// the SCC (see `constraint_sccs`) and for error reporting.
66 constraint_graph: Frozen<NormalConstraintGraph>,
68 /// The SCC computed from `constraints` and the constraint
69 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
70 /// compute the values of each region.
71 constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
73 /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if
74 /// `B: A`. This is used to compute the universal regions that are required
75 /// to outlive a given SCC. Computed lazily.
76 rev_scc_graph: Option<Rc<ReverseSccGraph>>,
78 /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
79 member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
81 /// Records the member constraints that we applied to each scc.
82 /// This is useful for error reporting. Once constraint
83 /// propagation is done, this vector is sorted according to
84 /// `member_region_scc`.
85 member_constraints_applied: Vec<AppliedMemberConstraint>,
87 /// Map closure bounds to a `Span` that should be used for error reporting.
88 closure_bounds_mapping:
89 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
91 /// Map universe indexes to information on why we created it.
92 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
94 /// Contains the minimum universe of any variable within the same
95 /// SCC. We will ensure that no SCC contains values that are not
96 /// visible from this index.
97 scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
99 /// Contains a "representative" from each SCC. This will be the
100 /// minimal RegionVid belonging to that universe. It is used as a
101 /// kind of hacky way to manage checking outlives relationships,
102 /// since we can 'canonicalize' each region to the representative
103 /// of its SCC and be sure that -- if they have the same repr --
104 /// they *must* be equal (though not having the same repr does not
105 /// mean they are unequal).
106 scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
108 /// The final inferred values of the region variables; we compute
109 /// one value per SCC. To get the value for any given *region*,
110 /// you first find which scc it is a part of.
111 scc_values: RegionValues<ConstraintSccIndex>,
113 /// Type constraints that we check after solving.
114 type_tests: Vec<TypeTest<'tcx>>,
116 /// Information about the universally quantified regions in scope
117 /// on this function.
118 universal_regions: Rc<UniversalRegions<'tcx>>,
120 /// Information about how the universally quantified regions in
121 /// scope on this function relate to one another.
122 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
125 /// Each time that `apply_member_constraint` is successful, it appends
126 /// one of these structs to the `member_constraints_applied` field.
127 /// This is used in error reporting to trace out what happened.
129 /// The way that `apply_member_constraint` works is that it effectively
130 /// adds a new lower bound to the SCC it is analyzing: so you wind up
131 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
132 /// minimal viable option.
133 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
134 pub(crate) struct AppliedMemberConstraint {
135 /// The SCC that was affected. (The "member region".)
137 /// The vector if `AppliedMemberConstraint` elements is kept sorted
139 pub(crate) member_region_scc: ConstraintSccIndex,
141 /// The "best option" that `apply_member_constraint` found -- this was
142 /// added as an "ad-hoc" lower-bound to `member_region_scc`.
143 pub(crate) min_choice: ty::RegionVid,
145 /// The "member constraint index" -- we can find out details about
146 /// the constraint from
147 /// `set.member_constraints[member_constraint_index]`.
148 pub(crate) member_constraint_index: NllMemberConstraintIndex,
151 pub(crate) struct RegionDefinition<'tcx> {
152 /// What kind of variable is this -- a free region? existential
153 /// variable? etc. (See the `NllRegionVariableOrigin` for more
155 pub(crate) origin: NllRegionVariableOrigin,
157 /// Which universe is this region variable defined in? This is
158 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
159 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
160 /// the variable for `'a` in a fresh universe that extends ROOT.
161 pub(crate) universe: ty::UniverseIndex,
163 /// If this is 'static or an early-bound region, then this is
164 /// `Some(X)` where `X` is the name of the region.
165 pub(crate) external_name: Option<ty::Region<'tcx>>,
168 /// N.B., the variants in `Cause` are intentionally ordered. Lower
169 /// values are preferred when it comes to error messages. Do not
170 /// reorder willy nilly.
171 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
172 pub(crate) enum Cause {
173 /// point inserted because Local was live at the given Location
174 LiveVar(Local, Location),
176 /// point inserted because Local was dropped at the given Location
177 DropVar(Local, Location),
180 /// A "type test" corresponds to an outlives constraint between a type
181 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
182 /// translated from the `Verify` region constraints in the ordinary
183 /// inference context.
185 /// These sorts of constraints are handled differently than ordinary
186 /// constraints, at least at present. During type checking, the
187 /// `InferCtxt::process_registered_region_obligations` method will
188 /// attempt to convert a type test like `T: 'x` into an ordinary
189 /// outlives constraint when possible (for example, `&'a T: 'b` will
190 /// be converted into `'a: 'b` and registered as a `Constraint`).
192 /// In some cases, however, there are outlives relationships that are
193 /// not converted into a region constraint, but rather into one of
194 /// these "type tests". The distinction is that a type test does not
195 /// influence the inference result, but instead just examines the
196 /// values that we ultimately inferred for each region variable and
197 /// checks that they meet certain extra criteria. If not, an error
200 /// One reason for this is that these type tests typically boil down
201 /// to a check like `'a: 'x` where `'a` is a universally quantified
202 /// region -- and therefore not one whose value is really meant to be
203 /// *inferred*, precisely (this is not always the case: one can have a
204 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
205 /// inference variable). Another reason is that these type tests can
206 /// involve *disjunction* -- that is, they can be satisfied in more
209 /// For more information about this translation, see
210 /// `InferCtxt::process_registered_region_obligations` and
211 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
212 #[derive(Clone, Debug)]
213 pub struct TypeTest<'tcx> {
214 /// The type `T` that must outlive the region.
215 pub generic_kind: GenericKind<'tcx>,
217 /// The region `'x` that the type must outlive.
218 pub lower_bound: RegionVid,
220 /// Where did this constraint arise and why?
221 pub locations: Locations,
223 /// A test which, if met by the region `'x`, proves that this type
224 /// constraint is satisfied.
225 pub verify_bound: VerifyBound<'tcx>,
228 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
229 /// environment). If we can't, it is an error.
230 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
231 enum RegionRelationCheckResult {
237 #[derive(Clone, PartialEq, Eq, Debug)]
240 FromOutlivesConstraint(OutlivesConstraint<'tcx>),
244 impl<'tcx> RegionInferenceContext<'tcx> {
245 /// Creates a new region inference context with a total of
246 /// `num_region_variables` valid inference variables; the first N
247 /// of those will be constant regions representing the free
248 /// regions defined in `universal_regions`.
250 /// The `outlives_constraints` and `type_tests` are an initial set
251 /// of constraints produced by the MIR type check.
254 universal_regions: Rc<UniversalRegions<'tcx>>,
255 placeholder_indices: Rc<PlaceholderIndices>,
256 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
257 outlives_constraints: OutlivesConstraintSet<'tcx>,
258 member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
259 closure_bounds_mapping: FxHashMap<
261 FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>,
263 universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
264 type_tests: Vec<TypeTest<'tcx>>,
265 liveness_constraints: LivenessValues<RegionVid>,
266 elements: &Rc<RegionValueElements>,
268 // Create a RegionDefinition for each inference variable.
269 let definitions: IndexVec<_, _> = var_infos
271 .map(|info| RegionDefinition::new(info.universe, info.origin))
274 let constraints = Frozen::freeze(outlives_constraints);
275 let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
276 let fr_static = universal_regions.fr_static;
277 let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
280 RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
282 for region in liveness_constraints.rows() {
283 let scc = constraint_sccs.scc(region);
284 scc_values.merge_liveness(scc, region, &liveness_constraints);
287 let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
289 let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
291 let member_constraints =
292 Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
294 let mut result = Self {
296 liveness_constraints,
302 member_constraints_applied: Vec::new(),
303 closure_bounds_mapping,
310 universal_region_relations,
313 result.init_free_and_bound_regions();
318 /// Each SCC is the combination of many region variables which
319 /// have been equated. Therefore, we can associate a universe with
320 /// each SCC which is minimum of all the universes of its
321 /// constituent regions -- this is because whatever value the SCC
322 /// takes on must be a value that each of the regions within the
323 /// SCC could have as well. This implies that the SCC must have
324 /// the minimum, or narrowest, universe.
325 fn compute_scc_universes(
326 constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
327 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
328 ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
329 let num_sccs = constraint_sccs.num_sccs();
330 let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
332 debug!("compute_scc_universes()");
334 // For each region R in universe U, ensure that the universe for the SCC
335 // that contains R is "no bigger" than U. This effectively sets the universe
336 // for each SCC to be the minimum of the regions within.
337 for (region_vid, region_definition) in definitions.iter_enumerated() {
338 let scc = constraint_sccs.scc(region_vid);
339 let scc_universe = &mut scc_universes[scc];
340 let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
341 if scc_min != *scc_universe {
342 *scc_universe = scc_min;
344 "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
345 because it contains {region_vid:?} in {region_universe:?}",
348 region_vid = region_vid,
349 region_universe = region_definition.universe,
354 // Walk each SCC `A` and `B` such that `A: B`
355 // and ensure that universe(A) can see universe(B).
357 // This serves to enforce the 'empty/placeholder' hierarchy
358 // (described in more detail on `RegionKind`):
363 // empty(U0) placeholder(U1)
368 // In particular, imagine we have variables R0 in U0 and R1
369 // created in U1, and constraints like this;
372 // R1: !1 // R1 outlives the placeholder in U1
373 // R1: R0 // R1 outlives R0
376 // Here, we wish for R1 to be `'static`, because it
377 // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
379 // Thanks to this loop, what happens is that the `R1: R0`
380 // constraint lowers the universe of `R1` to `U0`, which in turn
381 // means that the `R1: !1` constraint will (later) cause
382 // `R1` to become `'static`.
383 for scc_a in constraint_sccs.all_sccs() {
384 for &scc_b in constraint_sccs.successors(scc_a) {
385 let scc_universe_a = scc_universes[scc_a];
386 let scc_universe_b = scc_universes[scc_b];
387 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
388 if scc_universe_a != scc_universe_min {
389 scc_universes[scc_a] = scc_universe_min;
392 "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
393 because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
396 scc_universe_min = scc_universe_min,
397 scc_universe_b = scc_universe_b
403 debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
408 /// For each SCC, we compute a unique `RegionVid` (in fact, the
409 /// minimal one that belongs to the SCC). See
410 /// `scc_representatives` field of `RegionInferenceContext` for
412 fn compute_scc_representatives(
413 constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
414 definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
415 ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
416 let num_sccs = constraints_scc.num_sccs();
417 let next_region_vid = definitions.next_index();
418 let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
420 for region_vid in definitions.indices() {
421 let scc = constraints_scc.scc(region_vid);
422 let prev_min = scc_representatives[scc];
423 scc_representatives[scc] = region_vid.min(prev_min);
429 /// Initializes the region variables for each universally
430 /// quantified region (lifetime parameter). The first N variables
431 /// always correspond to the regions appearing in the function
432 /// signature (both named and anonymous) and where-clauses. This
433 /// function iterates over those regions and initializes them with
438 /// fn foo<'a, 'b>(..) where 'a: 'b
440 /// would initialize two variables like so:
442 /// R0 = { CFG, R0 } // 'a
443 /// R1 = { CFG, R0, R1 } // 'b
445 /// Here, R0 represents `'a`, and it contains (a) the entire CFG
446 /// and (b) any universally quantified regions that it outlives,
447 /// which in this case is just itself. R1 (`'b`) in contrast also
448 /// outlives `'a` and hence contains R0 and R1.
449 fn init_free_and_bound_regions(&mut self) {
450 // Update the names (if any)
451 for (external_name, variable) in self.universal_regions.named_universal_regions() {
453 "init_universal_regions: region {:?} has external name {:?}",
454 variable, external_name
456 self.definitions[variable].external_name = Some(external_name);
459 for variable in self.definitions.indices() {
460 let scc = self.constraint_sccs.scc(variable);
462 match self.definitions[variable].origin {
463 NllRegionVariableOrigin::FreeRegion => {
464 // For each free, universally quantified region X:
466 // Add all nodes in the CFG to liveness constraints
467 self.liveness_constraints.add_all_points(variable);
468 self.scc_values.add_all_points(scc);
470 // Add `end(X)` into the set for X.
471 self.scc_values.add_element(scc, variable);
474 NllRegionVariableOrigin::Placeholder(placeholder) => {
475 // Each placeholder region is only visible from
476 // its universe `ui` and its extensions. So we
477 // can't just add it into `scc` unless the
478 // universe of the scc can name this region.
479 let scc_universe = self.scc_universes[scc];
480 if scc_universe.can_name(placeholder.universe) {
481 self.scc_values.add_element(scc, placeholder);
484 "init_free_and_bound_regions: placeholder {:?} is \
485 not compatible with universe {:?} of its SCC {:?}",
486 placeholder, scc_universe, scc,
488 self.add_incompatible_universe(scc);
492 NllRegionVariableOrigin::RootEmptyRegion
493 | NllRegionVariableOrigin::Existential { .. } => {
494 // For existential, regions, nothing to do.
500 /// Returns an iterator over all the region indices.
501 pub fn regions(&self) -> impl Iterator<Item = RegionVid> + '_ {
502 self.definitions.indices()
505 /// Given a universal region in scope on the MIR, returns the
506 /// corresponding index.
508 /// (Panics if `r` is not a registered universal region.)
509 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
510 self.universal_regions.to_region_vid(r)
513 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
514 crate fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
515 self.universal_regions.annotate(tcx, err)
518 /// Returns `true` if the region `r` contains the point `p`.
520 /// Panics if called before `solve()` executes,
521 crate fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
522 let scc = self.constraint_sccs.scc(r.to_region_vid());
523 self.scc_values.contains(scc, p)
526 /// Returns access to the value of `r` for debugging purposes.
527 crate fn region_value_str(&self, r: RegionVid) -> String {
528 let scc = self.constraint_sccs.scc(r.to_region_vid());
529 self.scc_values.region_value_str(scc)
532 /// Returns access to the value of `r` for debugging purposes.
533 crate fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
534 let scc = self.constraint_sccs.scc(r.to_region_vid());
535 self.scc_universes[scc]
538 /// Once region solving has completed, this function will return
539 /// the member constraints that were applied to the value of a given
540 /// region `r`. See `AppliedMemberConstraint`.
541 pub(crate) fn applied_member_constraints(
544 ) -> &[AppliedMemberConstraint] {
545 let scc = self.constraint_sccs.scc(r.to_region_vid());
546 binary_search_util::binary_search_slice(
547 &self.member_constraints_applied,
548 |applied| applied.member_region_scc,
553 /// Performs region inference and report errors if we see any
554 /// unsatisfiable constraints. If this is a closure, returns the
555 /// region requirements to propagate to our creator, if any.
556 #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
559 infcx: &InferCtxt<'_, 'tcx>,
561 polonius_output: Option<Rc<PoloniusOutput>>,
562 ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
563 let mir_def_id = body.source.def_id();
564 self.propagate_constraints(body);
566 let mut errors_buffer = RegionErrors::new();
568 // If this is a closure, we can propagate unsatisfied
569 // `outlives_requirements` to our creator, so create a vector
570 // to store those. Otherwise, we'll pass in `None` to the
571 // functions below, which will trigger them to report errors
573 let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
575 self.check_type_tests(infcx, body, outlives_requirements.as_mut(), &mut errors_buffer);
577 // In Polonius mode, the errors about missing universal region relations are in the output
578 // and need to be emitted or propagated. Otherwise, we need to check whether the
579 // constraints were too strong, and if so, emit or propagate those errors.
580 if infcx.tcx.sess.opts.debugging_opts.polonius {
581 self.check_polonius_subset_errors(
583 outlives_requirements.as_mut(),
585 polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"),
588 self.check_universal_regions(body, outlives_requirements.as_mut(), &mut errors_buffer);
591 if errors_buffer.is_empty() {
592 self.check_member_constraints(infcx, &mut errors_buffer);
595 let outlives_requirements = outlives_requirements.unwrap_or_default();
597 if outlives_requirements.is_empty() {
598 (None, errors_buffer)
600 let num_external_vids = self.universal_regions.num_global_and_external_regions();
602 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
608 /// Propagate the region constraints: this will grow the values
609 /// for each region variable until all the constraints are
610 /// satisfied. Note that some values may grow **too** large to be
611 /// feasible, but we check this later.
612 #[instrument(skip(self, _body), level = "debug")]
613 fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
614 debug!("constraints={:#?}", {
615 let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
616 constraints.sort_by_key(|c| (c.sup, c.sub));
619 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
623 // To propagate constraints, we walk the DAG induced by the
624 // SCC. For each SCC, we visit its successors and compute
625 // their values, then we union all those values to get our
627 let constraint_sccs = self.constraint_sccs.clone();
628 for scc in constraint_sccs.all_sccs() {
629 self.compute_value_for_scc(scc);
632 // Sort the applied member constraints so we can binary search
633 // through them later.
634 self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
637 /// Computes the value of the SCC `scc_a`, which has not yet been
638 /// computed, by unioning the values of its successors.
639 /// Assumes that all successors have been computed already
640 /// (which is assured by iterating over SCCs in dependency order).
641 #[instrument(skip(self), level = "debug")]
642 fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) {
643 let constraint_sccs = self.constraint_sccs.clone();
645 // Walk each SCC `B` such that `A: B`...
646 for &scc_b in constraint_sccs.successors(scc_a) {
649 // ...and add elements from `B` into `A`. One complication
650 // arises because of universes: If `B` contains something
651 // that `A` cannot name, then `A` can only contain `B` if
652 // it outlives static.
653 if self.universe_compatible(scc_b, scc_a) {
654 // `A` can name everything that is in `B`, so just
656 self.scc_values.add_region(scc_a, scc_b);
658 self.add_incompatible_universe(scc_a);
662 // Now take member constraints into account.
663 let member_constraints = self.member_constraints.clone();
664 for m_c_i in member_constraints.indices(scc_a) {
665 self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i));
668 debug!(value = ?self.scc_values.region_value_str(scc_a));
671 /// Invoked for each `R0 member of [R1..Rn]` constraint.
673 /// `scc` is the SCC containing R0, and `choice_regions` are the
674 /// `R1..Rn` regions -- they are always known to be universal
675 /// regions (and if that's not true, we just don't attempt to
676 /// enforce the constraint).
678 /// The current value of `scc` at the time the method is invoked
679 /// is considered a *lower bound*. If possible, we will modify
680 /// the constraint to set it equal to one of the option regions.
681 /// If we make any changes, returns true, else false.
682 #[instrument(skip(self, member_constraint_index), level = "debug")]
683 fn apply_member_constraint(
685 scc: ConstraintSccIndex,
686 member_constraint_index: NllMemberConstraintIndex,
687 choice_regions: &[ty::RegionVid],
689 // Create a mutable vector of the options. We'll try to winnow
691 let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
693 // Convert to the SCC representative: sometimes we have inference
694 // variables in the member constraint that wind up equated with
695 // universal regions. The scc representative is the minimal numbered
696 // one from the corresponding scc so it will be the universal region
698 for c_r in &mut choice_regions {
699 let scc = self.constraint_sccs.scc(*c_r);
700 *c_r = self.scc_representatives[scc];
703 // The 'member region' in a member constraint is part of the
704 // hidden type, which must be in the root universe. Therefore,
705 // it cannot have any placeholders in its value.
706 assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
708 self.scc_values.placeholders_contained_in(scc).next().is_none(),
709 "scc {:?} in a member constraint has placeholder value: {:?}",
711 self.scc_values.region_value_str(scc),
714 // The existing value for `scc` is a lower-bound. This will
715 // consist of some set `{P} + {LB}` of points `{P}` and
716 // lower-bound free regions `{LB}`. As each choice region `O`
717 // is a free region, it will outlive the points. But we can
718 // only consider the option `O` if `O: LB`.
719 choice_regions.retain(|&o_r| {
721 .universal_regions_outlived_by(scc)
722 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
724 debug!(?choice_regions, "after lb");
726 // Now find all the *upper bounds* -- that is, each UB is a
727 // free region that must outlive the member region `R0` (`UB:
728 // R0`). Therefore, we need only keep an option `O` if `UB: O`
730 let rev_scc_graph = self.reverse_scc_graph();
731 let universal_region_relations = &self.universal_region_relations;
732 for ub in rev_scc_graph.upper_bounds(scc) {
734 choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
736 debug!(?choice_regions, "after ub");
738 // If we ruled everything out, we're done.
739 if choice_regions.is_empty() {
743 // Otherwise, we need to find the minimum remaining choice, if
744 // any, and take that.
745 debug!("choice_regions remaining are {:#?}", choice_regions);
746 let min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> {
747 let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2);
748 let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1);
749 match (r1_outlives_r2, r2_outlives_r1) {
750 (true, true) => Some(r1.min(r2)),
751 (true, false) => Some(r2),
752 (false, true) => Some(r1),
753 (false, false) => None,
756 let mut min_choice = choice_regions[0];
757 for &other_option in &choice_regions[1..] {
758 debug!(?min_choice, ?other_option,);
759 match min(min_choice, other_option) {
760 Some(m) => min_choice = m,
762 debug!(?min_choice, ?other_option, "incomparable; no min choice",);
768 let min_choice_scc = self.constraint_sccs.scc(min_choice);
769 debug!(?min_choice, ?min_choice_scc);
770 if self.scc_values.add_region(scc, min_choice_scc) {
771 self.member_constraints_applied.push(AppliedMemberConstraint {
772 member_region_scc: scc,
774 member_constraint_index,
783 /// Returns `true` if all the elements in the value of `scc_b` are nameable
784 /// in `scc_a`. Used during constraint propagation, and only once
785 /// the value of `scc_b` has been computed.
786 fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
787 let universe_a = self.scc_universes[scc_a];
789 // Quick check: if scc_b's declared universe is a subset of
790 // scc_a's declared univese (typically, both are ROOT), then
791 // it cannot contain any problematic universe elements.
792 if universe_a.can_name(self.scc_universes[scc_b]) {
796 // Otherwise, we have to iterate over the universe elements in
797 // B's value, and check whether all of them are nameable
799 self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
802 /// Extend `scc` so that it can outlive some placeholder region
803 /// from a universe it can't name; at present, the only way for
804 /// this to be true is if `scc` outlives `'static`. This is
805 /// actually stricter than necessary: ideally, we'd support bounds
806 /// like `for<'a: 'b`>` that might then allow us to approximate
807 /// `'a` with `'b` and not `'static`. But it will have to do for
809 fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
810 debug!("add_incompatible_universe(scc={:?})", scc);
812 let fr_static = self.universal_regions.fr_static;
813 self.scc_values.add_all_points(scc);
814 self.scc_values.add_element(scc, fr_static);
817 /// Once regions have been propagated, this method is used to see
818 /// whether the "type tests" produced by typeck were satisfied;
819 /// type tests encode type-outlives relationships like `T:
820 /// 'a`. See `TypeTest` for more details.
823 infcx: &InferCtxt<'_, 'tcx>,
825 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
826 errors_buffer: &mut RegionErrors<'tcx>,
830 // Sometimes we register equivalent type-tests that would
831 // result in basically the exact same error being reported to
832 // the user. Avoid that.
833 let mut deduplicate_errors = FxHashSet::default();
835 for type_test in &self.type_tests {
836 debug!("check_type_test: {:?}", type_test);
838 let generic_ty = type_test.generic_kind.to_ty(tcx);
839 if self.eval_verify_bound(
843 type_test.lower_bound,
844 &type_test.verify_bound,
849 if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
850 if self.try_promote_type_test(
854 propagated_outlives_requirements,
860 // Type-test failed. Report the error.
861 let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
863 // Skip duplicate-ish errors.
864 if deduplicate_errors.insert((
866 type_test.lower_bound,
870 "check_type_test: reporting error for erased_generic_kind={:?}, \
871 lower_bound_region={:?}, \
872 type_test.locations={:?}",
873 erased_generic_kind, type_test.lower_bound, type_test.locations,
876 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
881 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
882 /// prove to be satisfied. If this is a closure, we will attempt to
883 /// "promote" this type-test into our `ClosureRegionRequirements` and
884 /// hence pass it up the creator. To do this, we have to phrase the
885 /// type-test in terms of external free regions, as local free
886 /// regions are not nameable by the closure's creator.
888 /// Promotion works as follows: we first check that the type `T`
889 /// contains only regions that the creator knows about. If this is
890 /// true, then -- as a consequence -- we know that all regions in
891 /// the type `T` are free regions that outlive the closure body. If
892 /// false, then promotion fails.
894 /// Once we've promoted T, we have to "promote" `'X` to some region
895 /// that is "external" to the closure. Generally speaking, a region
896 /// may be the union of some points in the closure body as well as
897 /// various free lifetimes. We can ignore the points in the closure
898 /// body: if the type T can be expressed in terms of external regions,
899 /// we know it outlives the points in the closure body. That
900 /// just leaves the free regions.
902 /// The idea then is to lower the `T: 'X` constraint into multiple
903 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
904 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
905 fn try_promote_type_test(
907 infcx: &InferCtxt<'_, 'tcx>,
909 type_test: &TypeTest<'tcx>,
910 propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
914 let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test;
916 let generic_ty = generic_kind.to_ty(tcx);
917 let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
921 // For each region outlived by lower_bound find a non-local,
922 // universal region (it may be the same region) and add it to
923 // `ClosureOutlivesRequirement`.
924 let r_scc = self.constraint_sccs.scc(*lower_bound);
925 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
926 // Check whether we can already prove that the "subject" outlives `ur`.
927 // If so, we don't have to propagate this requirement to our caller.
929 // To continue the example from the function, if we are trying to promote
930 // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
931 // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
932 // we check whether `T: '1` is something we *can* prove. If so, no need
933 // to propagate that requirement.
935 // This is needed because -- particularly in the case
936 // where `ur` is a local bound -- we are sometimes in a
937 // position to prove things that our caller cannot. See
938 // #53570 for an example.
939 if self.eval_verify_bound(tcx, body, generic_ty, ur, &type_test.verify_bound) {
943 debug!("try_promote_type_test: ur={:?}", ur);
945 let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
946 debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
948 // This is slightly too conservative. To show T: '1, given `'2: '1`
949 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
950 // avoid potential non-determinism we approximate this by requiring
952 for upper_bound in non_local_ub {
953 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
954 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
956 let requirement = ClosureOutlivesRequirement {
958 outlived_free_region: upper_bound,
959 blame_span: locations.span(body),
960 category: ConstraintCategory::Boring,
962 debug!("try_promote_type_test: pushing {:#?}", requirement);
963 propagated_outlives_requirements.push(requirement);
969 /// When we promote a type test `T: 'r`, we have to convert the
970 /// type `T` into something we can store in a query result (so
971 /// something allocated for `'tcx`). This is problematic if `ty`
972 /// contains regions. During the course of NLL region checking, we
973 /// will have replaced all of those regions with fresh inference
974 /// variables. To create a test subject, we want to replace those
975 /// inference variables with some region from the closure
976 /// signature -- this is not always possible, so this is a
977 /// fallible process. Presuming we do find a suitable region, we
978 /// will use it's *external name*, which will be a `RegionKind`
979 /// variant that can be used in query responses such as
981 fn try_promote_type_test_subject(
983 infcx: &InferCtxt<'_, 'tcx>,
985 ) -> Option<ClosureOutlivesSubject<'tcx>> {
988 debug!("try_promote_type_test_subject(ty = {:?})", ty);
990 let ty = tcx.fold_regions(ty, &mut false, |r, _depth| {
991 let region_vid = self.to_region_vid(r);
993 // The challenge if this. We have some region variable `r`
994 // whose value is a set of CFG points and universal
995 // regions. We want to find if that set is *equivalent* to
996 // any of the named regions found in the closure.
998 // To do so, we compute the
999 // `non_local_universal_upper_bound`. This will be a
1000 // non-local, universal region that is greater than `r`.
1001 // However, it might not be *contained* within `r`, so
1002 // then we further check whether this bound is contained
1003 // in `r`. If so, we can say that `r` is equivalent to the
1006 // Let's work through a few examples. For these, imagine
1007 // that we have 3 non-local regions (I'll denote them as
1008 // `'static`, `'a`, and `'b`, though of course in the code
1009 // they would be represented with indices) where:
1014 // First, let's assume that `r` is some existential
1015 // variable with an inferred value `{'a, 'static}` (plus
1016 // some CFG nodes). In this case, the non-local upper
1017 // bound is `'static`, since that outlives `'a`. `'static`
1018 // is also a member of `r` and hence we consider `r`
1019 // equivalent to `'static` (and replace it with
1022 // Now let's consider the inferred value `{'a, 'b}`. This
1023 // means `r` is effectively `'a | 'b`. I'm not sure if
1024 // this can come about, actually, but assuming it did, we
1025 // would get a non-local upper bound of `'static`. Since
1026 // `'static` is not contained in `r`, we would fail to
1027 // find an equivalent.
1028 let upper_bound = self.non_local_universal_upper_bound(region_vid);
1029 if self.region_contains(region_vid, upper_bound) {
1030 self.definitions[upper_bound].external_name.unwrap_or(r)
1032 // In the case of a failure, use a `ReVar` result. This will
1033 // cause the `needs_infer` later on to return `None`.
1038 debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1040 // `needs_infer` will only be true if we failed to promote some region.
1041 if ty.needs_infer() {
1045 Some(ClosureOutlivesSubject::Ty(ty))
1048 /// Given some universal or existential region `r`, finds a
1049 /// non-local, universal region `r+` that outlives `r` at entry to (and
1050 /// exit from) the closure. In the worst case, this will be
1053 /// This is used for two purposes. First, if we are propagated
1054 /// some requirement `T: r`, we can use this method to enlarge `r`
1055 /// to something we can encode for our creator (which only knows
1056 /// about non-local, universal regions). It is also used when
1057 /// encoding `T` as part of `try_promote_type_test_subject` (see
1058 /// that fn for details).
1060 /// This is based on the result `'y` of `universal_upper_bound`,
1061 /// except that it converts further takes the non-local upper
1062 /// bound of `'y`, so that the final result is non-local.
1063 fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1064 debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1066 let lub = self.universal_upper_bound(r);
1068 // Grow further to get smallest universal region known to
1070 let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1072 debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1077 /// Returns a universally quantified region that outlives the
1078 /// value of `r` (`r` may be existentially or universally
1081 /// Since `r` is (potentially) an existential region, it has some
1082 /// value which may include (a) any number of points in the CFG
1083 /// and (b) any number of `end('x)` elements of universally
1084 /// quantified regions. To convert this into a single universal
1085 /// region we do as follows:
1087 /// - Ignore the CFG points in `'r`. All universally quantified regions
1088 /// include the CFG anyhow.
1089 /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1091 #[instrument(skip(self), level = "debug")]
1092 pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1093 debug!(r = %self.region_value_str(r));
1095 // Find the smallest universal region that contains all other
1096 // universal regions within `region`.
1097 let mut lub = self.universal_regions.fr_fn_body;
1098 let r_scc = self.constraint_sccs.scc(r);
1099 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1100 lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1108 /// Like `universal_upper_bound`, but returns an approximation more suitable
1109 /// for diagnostics. If `r` contains multiple disjoint universal regions
1110 /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1111 /// This corresponds to picking named regions over unnamed regions
1112 /// (e.g. picking early-bound regions over a closure late-bound region).
1114 /// This means that the returned value may not be a true upper bound, since
1115 /// only 'static is known to outlive disjoint universal regions.
1116 /// Therefore, this method should only be used in diagnostic code,
1117 /// where displaying *some* named universal region is better than
1118 /// falling back to 'static.
1119 pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1120 debug!("approx_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1122 // Find the smallest universal region that contains all other
1123 // universal regions within `region`.
1124 let mut lub = self.universal_regions.fr_fn_body;
1125 let r_scc = self.constraint_sccs.scc(r);
1126 let static_r = self.universal_regions.fr_static;
1127 for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1128 let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1129 debug!("approx_universal_upper_bound: ur={:?} lub={:?} new_lub={:?}", ur, lub, new_lub);
1130 // The upper bound of two non-static regions is static: this
1131 // means we know nothing about the relationship between these
1132 // two regions. Pick a 'better' one to use when constructing
1134 if ur != static_r && lub != static_r && new_lub == static_r {
1135 // Prefer the region with an `external_name` - this
1136 // indicates that the region is early-bound, so working with
1137 // it can produce a nicer error.
1138 if self.region_definition(ur).external_name.is_some() {
1140 } else if self.region_definition(lub).external_name.is_some() {
1141 // Leave lub unchanged
1143 // If we get here, we don't have any reason to prefer
1144 // one region over the other. Just pick the
1145 // one with the lower index for now.
1146 lub = std::cmp::min(ur, lub);
1153 debug!("approx_universal_upper_bound: r={:?} lub={:?}", r, lub);
1158 /// Tests if `test` is true when applied to `lower_bound` at
1160 fn eval_verify_bound(
1164 generic_ty: Ty<'tcx>,
1165 lower_bound: RegionVid,
1166 verify_bound: &VerifyBound<'tcx>,
1168 debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1170 match verify_bound {
1171 VerifyBound::IfEq(test_ty, verify_bound1) => {
1172 self.eval_if_eq(tcx, body, generic_ty, lower_bound, *test_ty, verify_bound1)
1175 VerifyBound::IsEmpty => {
1176 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1177 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1180 VerifyBound::OutlivedBy(r) => {
1181 let r_vid = self.to_region_vid(*r);
1182 self.eval_outlives(r_vid, lower_bound)
1185 VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1186 self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1189 VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1190 self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1199 generic_ty: Ty<'tcx>,
1200 lower_bound: RegionVid,
1202 verify_bound: &VerifyBound<'tcx>,
1204 let generic_ty_normalized = self.normalize_to_scc_representatives(tcx, generic_ty);
1205 let test_ty_normalized = self.normalize_to_scc_representatives(tcx, test_ty);
1206 if generic_ty_normalized == test_ty_normalized {
1207 self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1213 /// This is a conservative normalization procedure. It takes every
1214 /// free region in `value` and replaces it with the
1215 /// "representative" of its SCC (see `scc_representatives` field).
1216 /// We are guaranteed that if two values normalize to the same
1217 /// thing, then they are equal; this is a conservative check in
1218 /// that they could still be equal even if they normalize to
1219 /// different results. (For example, there might be two regions
1220 /// with the same value that are not in the same SCC).
1222 /// N.B., this is not an ideal approach and I would like to revisit
1223 /// it. However, it works pretty well in practice. In particular,
1224 /// this is needed to deal with projection outlives bounds like
1227 /// <T as Foo<'0>>::Item: '1
1230 /// In particular, this routine winds up being important when
1231 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1232 /// environment. In this case, if we can show that `'0 == 'a`,
1233 /// and that `'b: '1`, then we know that the clause is
1234 /// satisfied. In such cases, particularly due to limitations of
1235 /// the trait solver =), we usually wind up with a where-clause like
1236 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1237 /// a constraint, and thus ensures that they are in the same SCC.
1239 /// So why can't we do a more correct routine? Well, we could
1240 /// *almost* use the `relate_tys` code, but the way it is
1241 /// currently setup it creates inference variables to deal with
1242 /// higher-ranked things and so forth, and right now the inference
1243 /// context is not permitted to make more inference variables. So
1244 /// we use this kind of hacky solution.
1245 fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1247 T: TypeFoldable<'tcx>,
1249 tcx.fold_regions(value, &mut false, |r, _db| {
1250 let vid = self.to_region_vid(r);
1251 let scc = self.constraint_sccs.scc(vid);
1252 let repr = self.scc_representatives[scc];
1253 tcx.mk_region(ty::ReVar(repr))
1257 // Evaluate whether `sup_region == sub_region`.
1258 fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1259 self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1262 // Evaluate whether `sup_region: sub_region`.
1263 #[instrument(skip(self), level = "debug")]
1264 fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1266 "eval_outlives: sup_region's value = {:?} universal={:?}",
1267 self.region_value_str(sup_region),
1268 self.universal_regions.is_universal_region(sup_region),
1271 "eval_outlives: sub_region's value = {:?} universal={:?}",
1272 self.region_value_str(sub_region),
1273 self.universal_regions.is_universal_region(sub_region),
1276 let sub_region_scc = self.constraint_sccs.scc(sub_region);
1277 let sup_region_scc = self.constraint_sccs.scc(sup_region);
1279 // Both the `sub_region` and `sup_region` consist of the union
1280 // of some number of universal regions (along with the union
1281 // of various points in the CFG; ignore those points for
1282 // now). Therefore, the sup-region outlives the sub-region if,
1283 // for each universal region R1 in the sub-region, there
1284 // exists some region R2 in the sup-region that outlives R1.
1285 let universal_outlives =
1286 self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1288 .universal_regions_outlived_by(sup_region_scc)
1289 .any(|r2| self.universal_region_relations.outlives(r2, r1))
1292 if !universal_outlives {
1296 // Now we have to compare all the points in the sub region and make
1297 // sure they exist in the sup region.
1299 if self.universal_regions.is_universal_region(sup_region) {
1300 // Micro-opt: universal regions contain all points.
1304 self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1307 /// Once regions have been propagated, this method is used to see
1308 /// whether any of the constraints were too strong. In particular,
1309 /// we want to check for a case where a universally quantified
1310 /// region exceeded its bounds. Consider:
1312 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1314 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1315 /// and hence we establish (transitively) a constraint that
1316 /// `'a: 'b`. The `propagate_constraints` code above will
1317 /// therefore add `end('a)` into the region for `'b` -- but we
1318 /// have no evidence that `'b` outlives `'a`, so we want to report
1321 /// If `propagated_outlives_requirements` is `Some`, then we will
1322 /// push unsatisfied obligations into there. Otherwise, we'll
1323 /// report them as errors.
1324 fn check_universal_regions(
1327 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1328 errors_buffer: &mut RegionErrors<'tcx>,
1330 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1331 match fr_definition.origin {
1332 NllRegionVariableOrigin::FreeRegion => {
1333 // Go through each of the universal regions `fr` and check that
1334 // they did not grow too large, accumulating any requirements
1335 // for our caller into the `outlives_requirements` vector.
1336 self.check_universal_region(
1339 &mut propagated_outlives_requirements,
1344 NllRegionVariableOrigin::Placeholder(placeholder) => {
1345 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1348 NllRegionVariableOrigin::RootEmptyRegion
1349 | NllRegionVariableOrigin::Existential { .. } => {
1350 // nothing to check here
1356 /// Checks if Polonius has found any unexpected free region relations.
1358 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1359 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1360 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1361 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1363 /// More details can be found in this blog post by Niko:
1364 /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1366 /// In the canonical example
1368 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1370 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1371 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1372 /// constraint holds.
1374 /// If `propagated_outlives_requirements` is `Some`, then we will
1375 /// push unsatisfied obligations into there. Otherwise, we'll
1376 /// report them as errors.
1377 fn check_polonius_subset_errors(
1380 mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1381 errors_buffer: &mut RegionErrors<'tcx>,
1382 polonius_output: Rc<PoloniusOutput>,
1385 "check_polonius_subset_errors: {} subset_errors",
1386 polonius_output.subset_errors.len()
1389 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1390 // declared ("known") was found by Polonius, so emit an error, or propagate the
1391 // requirements for our caller into the `propagated_outlives_requirements` vector.
1393 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1394 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1395 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1396 // and the "superset origin" is the outlived "shorter free region".
1398 // Note: Polonius will produce a subset error at every point where the unexpected
1399 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1400 // for diagnostics in the future, e.g. to point more precisely at the key locations
1401 // requiring this constraint to hold. However, the error and diagnostics code downstream
1402 // expects that these errors are not duplicated (and that they are in a certain order).
1403 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1404 // anonymous lifetimes for example, could give these names differently, while others like
1405 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1406 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1407 // CFG-location ordering.
1408 let mut subset_errors: Vec<_> = polonius_output
1411 .flat_map(|(_location, subset_errors)| subset_errors.iter())
1413 subset_errors.sort();
1414 subset_errors.dedup();
1416 for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1418 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1420 longer_fr, shorter_fr
1423 let propagated = self.try_propagate_universal_region_error(
1427 &mut propagated_outlives_requirements,
1429 if propagated == RegionRelationCheckResult::Error {
1430 errors_buffer.push(RegionErrorKind::RegionError {
1431 longer_fr: *longer_fr,
1432 shorter_fr: *shorter_fr,
1433 fr_origin: NllRegionVariableOrigin::FreeRegion,
1439 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1440 // a more complete picture on how to separate this responsibility.
1441 for (fr, fr_definition) in self.definitions.iter_enumerated() {
1442 match fr_definition.origin {
1443 NllRegionVariableOrigin::FreeRegion => {
1444 // handled by polonius above
1447 NllRegionVariableOrigin::Placeholder(placeholder) => {
1448 self.check_bound_universal_region(fr, placeholder, errors_buffer);
1451 NllRegionVariableOrigin::RootEmptyRegion
1452 | NllRegionVariableOrigin::Existential { .. } => {
1453 // nothing to check here
1459 /// Checks the final value for the free region `fr` to see if it
1460 /// grew too large. In particular, examine what `end(X)` points
1461 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1462 /// fr`, we want to check that `fr: X`. If not, that's either an
1463 /// error, or something we have to propagate to our creator.
1465 /// Things that are to be propagated are accumulated into the
1466 /// `outlives_requirements` vector.
1468 skip(self, body, propagated_outlives_requirements, errors_buffer),
1471 fn check_universal_region(
1474 longer_fr: RegionVid,
1475 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1476 errors_buffer: &mut RegionErrors<'tcx>,
1478 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1480 // Because this free region must be in the ROOT universe, we
1481 // know it cannot contain any bound universes.
1482 assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1483 debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1485 // Only check all of the relations for the main representative of each
1486 // SCC, otherwise just check that we outlive said representative. This
1487 // reduces the number of redundant relations propagated out of
1489 // Note that the representative will be a universal region if there is
1490 // one in this SCC, so we will always check the representative here.
1491 let representative = self.scc_representatives[longer_fr_scc];
1492 if representative != longer_fr {
1493 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1497 propagated_outlives_requirements,
1499 errors_buffer.push(RegionErrorKind::RegionError {
1501 shorter_fr: representative,
1502 fr_origin: NllRegionVariableOrigin::FreeRegion,
1509 // Find every region `o` such that `fr: o`
1510 // (because `fr` includes `end(o)`).
1511 let mut error_reported = false;
1512 for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1513 if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1517 propagated_outlives_requirements,
1519 // We only report the first region error. Subsequent errors are hidden so as
1520 // not to overwhelm the user, but we do record them so as to potentially print
1521 // better diagnostics elsewhere...
1522 errors_buffer.push(RegionErrorKind::RegionError {
1525 fr_origin: NllRegionVariableOrigin::FreeRegion,
1526 is_reported: !error_reported,
1529 error_reported = true;
1534 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1535 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1537 fn check_universal_region_relation(
1539 longer_fr: RegionVid,
1540 shorter_fr: RegionVid,
1542 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1543 ) -> RegionRelationCheckResult {
1544 // If it is known that `fr: o`, carry on.
1545 if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1546 RegionRelationCheckResult::Ok
1548 // If we are not in a context where we can't propagate errors, or we
1549 // could not shrink `fr` to something smaller, then just report an
1552 // Note: in this case, we use the unapproximated regions to report the
1553 // error. This gives better error messages in some cases.
1554 self.try_propagate_universal_region_error(
1558 propagated_outlives_requirements,
1563 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1564 /// creator. If we cannot, then the caller should report an error to the user.
1565 fn try_propagate_universal_region_error(
1567 longer_fr: RegionVid,
1568 shorter_fr: RegionVid,
1570 propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1571 ) -> RegionRelationCheckResult {
1572 if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1573 // Shrink `longer_fr` until we find a non-local region (if we do).
1574 // We'll call it `fr-` -- it's ever so slightly smaller than
1576 if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1578 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1580 let blame_span_category = self.find_outlives_blame_span(
1583 NllRegionVariableOrigin::FreeRegion,
1587 // Grow `shorter_fr` until we find some non-local regions. (We
1588 // always will.) We'll call them `shorter_fr+` -- they're ever
1589 // so slightly larger than `shorter_fr`.
1590 let shorter_fr_plus =
1591 self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1593 "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1596 for fr in shorter_fr_plus {
1597 // Push the constraint `fr-: shorter_fr+`
1598 propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1599 subject: ClosureOutlivesSubject::Region(fr_minus),
1600 outlived_free_region: fr,
1601 blame_span: blame_span_category.1.span,
1602 category: blame_span_category.0,
1605 return RegionRelationCheckResult::Propagated;
1609 RegionRelationCheckResult::Error
1612 fn check_bound_universal_region(
1614 longer_fr: RegionVid,
1615 placeholder: ty::PlaceholderRegion,
1616 errors_buffer: &mut RegionErrors<'tcx>,
1618 debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1620 let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1621 debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1623 // If we have some bound universal region `'a`, then the only
1624 // elements it can contain is itself -- we don't know anything
1626 let Some(error_element) = ({
1627 self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element {
1628 RegionElement::Location(_) => true,
1629 RegionElement::RootUniversalRegion(_) => true,
1630 RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1635 debug!("check_bound_universal_region: error_element = {:?}", error_element);
1637 // Find the region that introduced this `error_element`.
1638 errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1645 fn check_member_constraints(
1647 infcx: &InferCtxt<'_, 'tcx>,
1648 errors_buffer: &mut RegionErrors<'tcx>,
1650 let member_constraints = self.member_constraints.clone();
1651 for m_c_i in member_constraints.all_indices() {
1652 debug!("check_member_constraint(m_c_i={:?})", m_c_i);
1653 let m_c = &member_constraints[m_c_i];
1654 let member_region_vid = m_c.member_region_vid;
1656 "check_member_constraint: member_region_vid={:?} with value {}",
1658 self.region_value_str(member_region_vid),
1660 let choice_regions = member_constraints.choice_regions(m_c_i);
1661 debug!("check_member_constraint: choice_regions={:?}", choice_regions);
1663 // Did the member region wind up equal to any of the option regions?
1665 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1667 debug!("check_member_constraint: evaluated as equal to {:?}", o);
1671 // If not, report an error.
1672 let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1673 errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1674 span: m_c.definition_span,
1675 hidden_ty: m_c.hidden_ty,
1681 /// We have a constraint `fr1: fr2` that is not satisfied, where
1682 /// `fr2` represents some universal region. Here, `r` is some
1683 /// region where we know that `fr1: r` and this function has the
1684 /// job of determining whether `r` is "to blame" for the fact that
1685 /// `fr1: fr2` is required.
1687 /// This is true under two conditions:
1690 /// - `fr2` is `'static` and `r` is some placeholder in a universe
1691 /// that cannot be named by `fr1`; in that case, we will require
1692 /// that `fr1: 'static` because it is the only way to `fr1: r` to
1693 /// be satisfied. (See `add_incompatible_universe`.)
1694 crate fn provides_universal_region(
1700 debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1703 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1706 debug!("provides_universal_region: result = {:?}", result);
1710 /// If `r2` represents a placeholder region, then this returns
1711 /// `true` if `r1` cannot name that placeholder in its
1712 /// value; otherwise, returns `false`.
1713 crate fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1714 debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1716 match self.definitions[r2].origin {
1717 NllRegionVariableOrigin::Placeholder(placeholder) => {
1718 let universe1 = self.definitions[r1].universe;
1720 "cannot_name_value_of: universe1={:?} placeholder={:?}",
1721 universe1, placeholder
1723 universe1.cannot_name(placeholder.universe)
1726 NllRegionVariableOrigin::RootEmptyRegion
1727 | NllRegionVariableOrigin::FreeRegion
1728 | NllRegionVariableOrigin::Existential { .. } => false,
1732 crate fn retrieve_closure_constraint_info(
1735 constraint: &OutlivesConstraint<'tcx>,
1736 ) -> BlameConstraint<'tcx> {
1737 let loc = match constraint.locations {
1738 Locations::All(span) => {
1739 return BlameConstraint {
1740 category: constraint.category,
1741 from_closure: false,
1742 cause: ObligationCause::dummy_with_span(span),
1743 variance_info: constraint.variance_info,
1746 Locations::Single(loc) => loc,
1749 let opt_span_category =
1750 self.closure_bounds_mapping[&loc].get(&(constraint.sup, constraint.sub));
1752 .map(|&(category, span)| BlameConstraint {
1755 cause: ObligationCause::dummy_with_span(span),
1756 variance_info: constraint.variance_info,
1758 .unwrap_or(BlameConstraint {
1759 category: constraint.category,
1760 from_closure: false,
1761 cause: ObligationCause::dummy_with_span(body.source_info(loc).span),
1762 variance_info: constraint.variance_info,
1766 /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1767 crate fn find_outlives_blame_span(
1771 fr1_origin: NllRegionVariableOrigin,
1773 ) -> (ConstraintCategory, ObligationCause<'tcx>) {
1774 let BlameConstraint { category, cause, .. } =
1775 self.best_blame_constraint(body, fr1, fr1_origin, |r| {
1776 self.provides_universal_region(r, fr1, fr2)
1781 /// Walks the graph of constraints (where `'a: 'b` is considered
1782 /// an edge `'a -> 'b`) to find all paths from `from_region` to
1783 /// `to_region`. The paths are accumulated into the vector
1784 /// `results`. The paths are stored as a series of
1785 /// `ConstraintIndex` values -- in other words, a list of *edges*.
1787 /// Returns: a series of constraints as well as the region `R`
1788 /// that passed the target test.
1789 crate fn find_constraint_paths_between_regions(
1791 from_region: RegionVid,
1792 target_test: impl Fn(RegionVid) -> bool,
1793 ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1794 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1795 context[from_region] = Trace::StartRegion;
1797 // Use a deque so that we do a breadth-first search. We will
1798 // stop at the first match, which ought to be the shortest
1799 // path (fewest constraints).
1800 let mut deque = VecDeque::new();
1801 deque.push_back(from_region);
1803 while let Some(r) = deque.pop_front() {
1805 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1808 self.region_value_str(r),
1811 // Check if we reached the region we were looking for. If so,
1812 // we can reconstruct the path that led to it and return it.
1814 let mut result = vec![];
1817 match context[p].clone() {
1818 Trace::NotVisited => {
1819 bug!("found unvisited region {:?} on path to {:?}", p, r)
1822 Trace::FromOutlivesConstraint(c) => {
1827 Trace::StartRegion => {
1829 return Some((result, r));
1835 // Otherwise, walk over the outgoing constraints and
1836 // enqueue any regions we find, keeping track of how we
1839 // A constraint like `'r: 'x` can come from our constraint
1841 let fr_static = self.universal_regions.fr_static;
1842 let outgoing_edges_from_graph =
1843 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1845 // Always inline this closure because it can be hot.
1846 let mut handle_constraint = #[inline(always)]
1847 |constraint: OutlivesConstraint<'tcx>| {
1848 debug_assert_eq!(constraint.sup, r);
1849 let sub_region = constraint.sub;
1850 if let Trace::NotVisited = context[sub_region] {
1851 context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1852 deque.push_back(sub_region);
1856 // This loop can be hot.
1857 for constraint in outgoing_edges_from_graph {
1858 handle_constraint(constraint);
1861 // Member constraints can also give rise to `'r: 'x` edges that
1862 // were not part of the graph initially, so watch out for those.
1863 // (But they are extremely rare; this loop is very cold.)
1864 for constraint in self.applied_member_constraints(r) {
1865 let p_c = &self.member_constraints[constraint.member_constraint_index];
1866 let constraint = OutlivesConstraint {
1868 sub: constraint.min_choice,
1869 locations: Locations::All(p_c.definition_span),
1870 category: ConstraintCategory::OpaqueType,
1871 variance_info: ty::VarianceDiagInfo::default(),
1873 handle_constraint(constraint);
1880 /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1881 #[instrument(skip(self), level = "trace")]
1882 crate fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1883 trace!(scc = ?self.constraint_sccs.scc(fr1));
1884 trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1885 self.find_constraint_paths_between_regions(fr1, |r| {
1886 // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1887 trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1888 self.liveness_constraints.contains(r, elem)
1891 // If we fail to find that, we may find some `r` such that
1892 // `fr1: r` and `r` is a placeholder from some universe
1893 // `fr1` cannot name. This would force `fr1` to be
1895 self.find_constraint_paths_between_regions(fr1, |r| {
1896 self.cannot_name_placeholder(fr1, r)
1900 // If we fail to find THAT, it may be that `fr1` is a
1901 // placeholder that cannot "fit" into its SCC. In that
1902 // case, there should be some `r` where `fr1: r` and `fr1` is a
1903 // placeholder that `r` cannot name. We can blame that
1906 // Remember that if `R1: R2`, then the universe of R1
1907 // must be able to name the universe of R2, because R2 will
1908 // be at least `'empty(Universe(R2))`, and `R1` must be at
1909 // larger than that.
1910 self.find_constraint_paths_between_regions(fr1, |r| {
1911 self.cannot_name_placeholder(r, fr1)
1914 .map(|(_path, r)| r)
1918 /// Get the region outlived by `longer_fr` and live at `element`.
1919 crate fn region_from_element(
1921 longer_fr: RegionVid,
1922 element: &RegionElement,
1925 RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1926 RegionElement::RootUniversalRegion(r) => r,
1927 RegionElement::PlaceholderRegion(error_placeholder) => self
1930 .find_map(|(r, definition)| match definition.origin {
1931 NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1938 /// Get the region definition of `r`.
1939 crate fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1940 &self.definitions[r]
1943 /// Check if the SCC of `r` contains `upper`.
1944 crate fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1945 let r_scc = self.constraint_sccs.scc(r);
1946 self.scc_values.contains(r_scc, upper)
1949 crate fn universal_regions(&self) -> &UniversalRegions<'tcx> {
1950 self.universal_regions.as_ref()
1953 /// Tries to find the best constraint to blame for the fact that
1954 /// `R: from_region`, where `R` is some region that meets
1955 /// `target_test`. This works by following the constraint graph,
1956 /// creating a constraint path that forces `R` to outlive
1957 /// `from_region`, and then finding the best choices within that
1959 crate fn best_blame_constraint(
1962 from_region: RegionVid,
1963 from_region_origin: NllRegionVariableOrigin,
1964 target_test: impl Fn(RegionVid) -> bool,
1965 ) -> BlameConstraint<'tcx> {
1967 "best_blame_constraint(from_region={:?}, from_region_origin={:?})",
1968 from_region, from_region_origin
1972 let (path, target_region) =
1973 self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
1975 "best_blame_constraint: path={:#?}",
1978 "{:?} ({:?}: {:?})",
1980 self.constraint_sccs.scc(c.sup),
1981 self.constraint_sccs.scc(c.sub),
1983 .collect::<Vec<_>>()
1986 // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
1987 // Instead, we use it to produce an improved `ObligationCauseCode`.
1988 // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
1989 // constraints. Currently, we just pick the first one.
1990 let cause_code = path
1992 .find_map(|constraint| {
1993 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
1994 // We currentl'y doesn't store the `DefId` in the `ConstraintCategory`
1995 // for performances reasons. The error reporting code used by NLL only
1996 // uses the span, so this doesn't cause any problems at the moment.
1997 Some(ObligationCauseCode::BindingObligation(
1998 CRATE_DEF_ID.to_def_id(),
2005 .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2007 // Classify each of the constraints along the path.
2008 let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2011 if constraint.category == ConstraintCategory::ClosureBounds {
2012 self.retrieve_closure_constraint_info(body, &constraint)
2015 category: constraint.category,
2016 from_closure: false,
2017 cause: ObligationCause::new(
2018 constraint.locations.span(body),
2022 variance_info: constraint.variance_info,
2027 debug!("best_blame_constraint: categorized_path={:#?}", categorized_path);
2029 // To find the best span to cite, we first try to look for the
2030 // final constraint that is interesting and where the `sup` is
2031 // not unified with the ultimate target region. The reason
2032 // for this is that we have a chain of constraints that lead
2033 // from the source to the target region, something like:
2035 // '0: '1 ('0 is the source)
2040 // '5: '6 ('6 is the target)
2042 // Some of those regions are unified with `'6` (in the same
2043 // SCC). We want to screen those out. After that point, the
2044 // "closest" constraint we have to the end is going to be the
2045 // most likely to be the point where the value escapes -- but
2046 // we still want to screen for an "interesting" point to
2047 // highlight (e.g., a call site or something).
2048 let target_scc = self.constraint_sccs.scc(target_region);
2049 let mut range = 0..path.len();
2051 // As noted above, when reporting an error, there is typically a chain of constraints
2052 // leading from some "source" region which must outlive some "target" region.
2053 // In most cases, we prefer to "blame" the constraints closer to the target --
2054 // but there is one exception. When constraints arise from higher-ranked subtyping,
2055 // we generally prefer to blame the source value,
2056 // as the "target" in this case tends to be some type annotation that the user gave.
2057 // Therefore, if we find that the region origin is some instantiation
2058 // of a higher-ranked region, we start our search from the "source" point
2059 // rather than the "target", and we also tweak a few other things.
2061 // An example might be this bit of Rust code:
2064 // let x: fn(&'static ()) = |_| {};
2065 // let y: for<'a> fn(&'a ()) = x;
2068 // In MIR, this will be converted into a combination of assignments and type ascriptions.
2069 // In particular, the 'static is imposed through a type ascription:
2073 // AscribeUserType(x, fn(&'static ())
2077 // We wind up ultimately with constraints like
2080 // !a: 'temp1 // from the `y = x` statement
2082 // 'temp2: 'static // from the AscribeUserType
2085 // and here we prefer to blame the source (the y = x statement).
2086 let blame_source = match from_region_origin {
2087 NllRegionVariableOrigin::FreeRegion
2088 | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2089 NllRegionVariableOrigin::RootEmptyRegion
2090 | NllRegionVariableOrigin::Placeholder(_)
2091 | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2094 let find_region = |i: &usize| {
2095 let constraint = &path[*i];
2097 let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2100 match categorized_path[*i].category {
2101 ConstraintCategory::OpaqueType
2102 | ConstraintCategory::Boring
2103 | ConstraintCategory::BoringNoLocation
2104 | ConstraintCategory::Internal
2105 | ConstraintCategory::Predicate(_) => false,
2106 ConstraintCategory::TypeAnnotation
2107 | ConstraintCategory::Return(_)
2108 | ConstraintCategory::Yield => true,
2109 _ => constraint_sup_scc != target_scc,
2113 categorized_path[*i].category,
2114 ConstraintCategory::OpaqueType
2115 | ConstraintCategory::Boring
2116 | ConstraintCategory::BoringNoLocation
2117 | ConstraintCategory::Internal
2118 | ConstraintCategory::Predicate(_)
2124 if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2127 "best_blame_constraint: best_choice={:?} blame_source={}",
2128 best_choice, blame_source
2131 if let Some(i) = best_choice {
2132 if let Some(next) = categorized_path.get(i + 1) {
2133 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2134 && next.category == ConstraintCategory::OpaqueType
2136 // The return expression is being influenced by the return type being
2137 // impl Trait, point at the return type and not the return expr.
2138 return next.clone();
2142 if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2144 let field = categorized_path.iter().find_map(|p| {
2145 if let ConstraintCategory::ClosureUpvar(f) = p.category {
2152 if let Some(field) = field {
2153 categorized_path[i].category =
2154 ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2158 return categorized_path[i].clone();
2161 // If that search fails, that is.. unusual. Maybe everything
2162 // is in the same SCC or something. In that case, find what
2163 // appears to be the most interesting point to report to the
2164 // user via an even more ad-hoc guess.
2165 categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2166 debug!("best_blame_constraint: sorted_path={:#?}", categorized_path);
2168 categorized_path.remove(0)
2171 crate fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2172 self.universe_causes[&universe].clone()
2176 impl<'tcx> RegionDefinition<'tcx> {
2177 fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2178 // Create a new region definition. Note that, for free
2179 // regions, the `external_name` field gets updated later in
2180 // `init_universal_regions`.
2182 let origin = match rv_origin {
2183 RegionVariableOrigin::Nll(origin) => origin,
2184 _ => NllRegionVariableOrigin::Existential { from_forall: false },
2187 Self { origin, universe, external_name: None }
2191 pub trait ClosureRegionRequirementsExt<'tcx> {
2192 fn apply_requirements(
2195 closure_def_id: DefId,
2196 closure_substs: SubstsRef<'tcx>,
2197 ) -> Vec<QueryOutlivesConstraint<'tcx>>;
2200 impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> {
2201 /// Given an instance T of the closure type, this method
2202 /// instantiates the "extra" requirements that we computed for the
2203 /// closure into the inference context. This has the effect of
2204 /// adding new outlives obligations to existing variables.
2206 /// As described on `ClosureRegionRequirements`, the extra
2207 /// requirements are expressed in terms of regionvids that index
2208 /// into the free regions that appear on the closure type. So, to
2209 /// do this, we first copy those regions out from the type T into
2210 /// a vector. Then we can just index into that vector to extract
2211 /// out the corresponding region from T and apply the
2213 fn apply_requirements(
2216 closure_def_id: DefId,
2217 closure_substs: SubstsRef<'tcx>,
2218 ) -> Vec<QueryOutlivesConstraint<'tcx>> {
2220 "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
2221 closure_def_id, closure_substs
2224 // Extract the values of the free regions in `closure_substs`
2225 // into a vector. These are the regions that we will be
2226 // relating to one another.
2227 let closure_mapping = &UniversalRegions::closure_mapping(
2230 self.num_external_vids,
2231 tcx.typeck_root_def_id(closure_def_id),
2233 debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
2235 // Create the predicates.
2236 self.outlives_requirements
2238 .map(|outlives_requirement| {
2239 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
2241 match outlives_requirement.subject {
2242 ClosureOutlivesSubject::Region(region) => {
2243 let region = closure_mapping[region];
2245 "apply_requirements: region={:?} \
2246 outlived_region={:?} \
2247 outlives_requirement={:?}",
2248 region, outlived_region, outlives_requirement,
2250 ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
2253 ClosureOutlivesSubject::Ty(ty) => {
2255 "apply_requirements: ty={:?} \
2256 outlived_region={:?} \
2257 outlives_requirement={:?}",
2258 ty, outlived_region, outlives_requirement,
2260 ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
2268 #[derive(Clone, Debug)]
2269 pub struct BlameConstraint<'tcx> {
2270 pub category: ConstraintCategory,
2271 pub from_closure: bool,
2272 pub cause: ObligationCause<'tcx>,
2273 pub variance_info: ty::VarianceDiagInfo<'tcx>,