1 //! Lexical region resolution.
3 use crate::infer::region_constraints::Constraint;
4 use crate::infer::region_constraints::GenericKind;
5 use crate::infer::region_constraints::RegionConstraintData;
6 use crate::infer::region_constraints::VarInfos;
7 use crate::infer::region_constraints::VerifyBound;
8 use crate::infer::RegionRelations;
9 use crate::infer::RegionVariableOrigin;
10 use crate::infer::SubregionOrigin;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::graph::implementation::{
13 Direction, Graph, NodeIndex, INCOMING, OUTGOING,
15 use rustc_data_structures::intern::Interned;
16 use rustc_index::vec::{Idx, IndexVec};
17 use rustc_middle::ty::fold::TypeFoldable;
18 use rustc_middle::ty::PlaceholderRegion;
19 use rustc_middle::ty::{self, Ty, TyCtxt};
20 use rustc_middle::ty::{ReEarlyBound, ReErased, ReFree, ReStatic};
21 use rustc_middle::ty::{ReLateBound, RePlaceholder, ReVar};
22 use rustc_middle::ty::{Region, RegionVid};
26 use super::outlives::test_type_match;
28 /// This function performs lexical region resolution given a complete
29 /// set of constraints and variable origins. It performs a fixed-point
30 /// iteration to find region values which satisfy all constraints,
31 /// assuming such values can be found. It returns the final values of
32 /// all the variables as well as a set of errors that must be reported.
33 #[instrument(level = "debug", skip(region_rels, var_infos, data))]
34 pub(crate) fn resolve<'tcx>(
35 param_env: ty::ParamEnv<'tcx>,
36 region_rels: &RegionRelations<'_, 'tcx>,
38 data: RegionConstraintData<'tcx>,
39 ) -> (LexicalRegionResolutions<'tcx>, Vec<RegionResolutionError<'tcx>>) {
40 let mut errors = vec![];
41 let mut resolver = LexicalResolver { param_env, region_rels, var_infos, data };
42 let values = resolver.infer_variable_values(&mut errors);
46 /// Contains the result of lexical region resolution. Offers methods
47 /// to lookup up the final value of a region variable.
49 pub struct LexicalRegionResolutions<'tcx> {
50 pub(crate) values: IndexVec<RegionVid, VarValue<'tcx>>,
53 #[derive(Copy, Clone, Debug)]
54 pub(crate) enum VarValue<'tcx> {
55 /// Empty lifetime is for data that is never accessed. We tag the
56 /// empty lifetime with a universe -- the idea is that we don't
57 /// want `exists<'a> { forall<'b> { 'b: 'a } }` to be satisfiable.
58 /// Therefore, the `'empty` in a universe `U` is less than all
59 /// regions visible from `U`, but not less than regions not visible
61 Empty(ty::UniverseIndex),
66 #[derive(Clone, Debug)]
67 pub enum RegionResolutionError<'tcx> {
68 /// `ConcreteFailure(o, a, b)`:
70 /// `o` requires that `a <= b`, but this does not hold
71 ConcreteFailure(SubregionOrigin<'tcx>, Region<'tcx>, Region<'tcx>),
73 /// `GenericBoundFailure(p, s, a)
75 /// The parameter/associated-type `p` must be known to outlive the lifetime
76 /// `a` (but none of the known bounds are sufficient).
77 GenericBoundFailure(SubregionOrigin<'tcx>, GenericKind<'tcx>, Region<'tcx>),
79 /// `SubSupConflict(v, v_origin, sub_origin, sub_r, sup_origin, sup_r)`:
81 /// Could not infer a value for `v` (which has origin `v_origin`)
82 /// because `sub_r <= v` (due to `sub_origin`) but `v <= sup_r` (due to `sup_origin`) and
83 /// `sub_r <= sup_r` does not hold.
87 SubregionOrigin<'tcx>,
89 SubregionOrigin<'tcx>,
91 Vec<Span>, // All the influences on a given value that didn't meet its constraints.
94 /// Indicates a `'b: 'a` constraint where `'a` is in a universe that
95 /// cannot name the placeholder `'b`.
96 UpperBoundUniverseConflict(
99 ty::UniverseIndex, // the universe index of the region variable
100 SubregionOrigin<'tcx>, // cause of the constraint
101 Region<'tcx>, // the placeholder `'b`
105 struct RegionAndOrigin<'tcx> {
106 region: Region<'tcx>,
107 origin: SubregionOrigin<'tcx>,
110 type RegionGraph<'tcx> = Graph<(), Constraint<'tcx>>;
112 struct LexicalResolver<'cx, 'tcx> {
113 param_env: ty::ParamEnv<'tcx>,
114 region_rels: &'cx RegionRelations<'cx, 'tcx>,
116 data: RegionConstraintData<'tcx>,
119 impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
120 fn tcx(&self) -> TyCtxt<'tcx> {
124 fn infer_variable_values(
126 errors: &mut Vec<RegionResolutionError<'tcx>>,
127 ) -> LexicalRegionResolutions<'tcx> {
128 let mut var_data = self.construct_var_data();
130 if cfg!(debug_assertions) {
131 self.dump_constraints();
134 let graph = self.construct_graph();
135 self.expand_givens(&graph);
136 self.expansion(&mut var_data);
137 self.collect_errors(&mut var_data, errors);
138 self.collect_var_errors(&var_data, &graph, errors);
142 fn num_vars(&self) -> usize {
146 /// Initially, the value for all variables is set to `'empty`, the
147 /// empty region. The `expansion` phase will grow this larger.
148 fn construct_var_data(&self) -> LexicalRegionResolutions<'tcx> {
149 LexicalRegionResolutions {
150 values: IndexVec::from_fn_n(
152 let vid_universe = self.var_infos[vid].universe;
153 VarValue::Empty(vid_universe)
160 #[instrument(level = "debug", skip(self))]
161 fn dump_constraints(&self) {
162 for (idx, (constraint, _)) in self.data.constraints.iter().enumerate() {
163 debug!("Constraint {} => {:?}", idx, constraint);
167 fn expand_givens(&mut self, graph: &RegionGraph<'_>) {
168 // Givens are a kind of horrible hack to account for
169 // constraints like 'c <= '0 that are known to hold due to
170 // closure signatures (see the comment above on the `givens`
171 // field). They should go away. But until they do, the role
172 // of this fn is to account for the transitive nature:
178 let seeds: Vec<_> = self.data.givens.iter().cloned().collect();
179 for (r, vid) in seeds {
180 // While all things transitively reachable in the graph
181 // from the variable (`'0` in the example above).
182 let seed_index = NodeIndex(vid.index() as usize);
183 for succ_index in graph.depth_traverse(seed_index, OUTGOING) {
184 let succ_index = succ_index.0;
186 // The first N nodes correspond to the region
187 // variables. Other nodes correspond to constant
189 if succ_index < self.num_vars() {
190 let succ_vid = RegionVid::new(succ_index);
193 self.data.givens.insert((r, succ_vid));
199 /// Gets the LUb of a given region and the empty region
200 fn lub_empty(&self, a_region: Region<'tcx>) -> Result<Region<'tcx>, PlaceholderRegion> {
202 ReLateBound(..) | ReErased => {
203 bug!("cannot relate region: {:?}", a_region);
208 self.var_infos[v_id].origin.span(),
209 "lub invoked with non-concrete regions: {:?}",
215 // nothing lives longer than `'static`
216 Ok(self.tcx().lifetimes.re_static)
219 ReEarlyBound(_) | ReFree(_) => {
220 // All empty regions are less than early-bound, free,
221 // and scope regions.
225 RePlaceholder(placeholder) => Err(placeholder),
229 fn expansion(&self, var_values: &mut LexicalRegionResolutions<'tcx>) {
230 // In the first pass, we expand region vids according to constraints we
231 // have previously found. In the second pass, we loop through the region
232 // vids we expanded and expand *across* region vids (effectively
233 // "expanding" new `RegSubVar` constraints).
235 // Tracks the `VarSubVar` constraints generated for each region vid. We
236 // later use this to expand across vids.
237 let mut constraints = IndexVec::from_elem_n(Vec::new(), var_values.values.len());
238 // Tracks the changed region vids.
239 let mut changes = Vec::new();
240 for constraint in self.data.constraints.keys() {
242 Constraint::RegSubVar(a_region, b_vid) => {
243 let b_data = var_values.value_mut(b_vid);
245 if self.expand_node(a_region, b_vid, b_data) {
249 Constraint::VarSubVar(a_vid, b_vid) => match *var_values.value(a_vid) {
250 VarValue::ErrorValue => continue,
251 VarValue::Empty(a_universe) => {
252 let b_data = var_values.value_mut(b_vid);
254 let changed = (|| match *b_data {
255 VarValue::Empty(b_universe) => {
256 // Empty regions are ordered according to the universe
257 // they are associated with.
258 let ui = a_universe.min(b_universe);
261 "Expanding value of {:?} \
262 from empty lifetime with universe {:?} \
263 to empty lifetime with universe {:?}",
264 b_vid, b_universe, ui
267 *b_data = VarValue::Empty(ui);
270 VarValue::Value(cur_region) => {
271 let lub = match self.lub_empty(cur_region) {
273 // If the empty and placeholder regions are in the same universe,
274 // then the LUB is the Placeholder region (which is the cur_region).
275 // If they are not in the same universe, the LUB is the Static lifetime.
276 Err(placeholder) if a_universe == placeholder.universe => {
279 Err(_) => self.tcx().lifetimes.re_static,
282 if lub == cur_region {
287 "Expanding value of {:?} from {:?} to {:?}",
288 b_vid, cur_region, lub
291 *b_data = VarValue::Value(lub);
295 VarValue::ErrorValue => false,
302 VarValue::Value(Region(Interned(ReStatic, _)))
303 | VarValue::ErrorValue => (),
305 constraints[a_vid].push((a_vid, b_vid));
306 constraints[b_vid].push((a_vid, b_vid));
310 VarValue::Value(a_region) => {
311 let b_data = var_values.value_mut(b_vid);
313 if self.expand_node(a_region, b_vid, b_data) {
317 VarValue::Value(Region(Interned(ReStatic, _)))
318 | VarValue::ErrorValue => (),
320 constraints[a_vid].push((a_vid, b_vid));
321 constraints[b_vid].push((a_vid, b_vid));
326 Constraint::RegSubReg(..) | Constraint::VarSubReg(..) => {
327 // These constraints are checked after expansion
328 // is done, in `collect_errors`.
334 while let Some(vid) = changes.pop() {
335 constraints[vid].retain(|&(a_vid, b_vid)| {
336 let VarValue::Value(a_region) = *var_values.value(a_vid) else {
339 let b_data = var_values.value_mut(b_vid);
340 if self.expand_node(a_region, b_vid, b_data) {
345 VarValue::Value(Region(Interned(ReStatic, _))) | VarValue::ErrorValue
351 /// Expands the value of the region represented with `b_vid` with current
352 /// value `b_data` to the lub of `b_data` and `a_region`. The corresponds
353 /// with the constraint `'?b: 'a` (`'a <: '?b`), where `'a` is some known
354 /// region and `'?b` is some region variable.
357 a_region: Region<'tcx>,
359 b_data: &mut VarValue<'tcx>,
361 debug!("expand_node({:?}, {:?} == {:?})", a_region, b_vid, b_data);
364 // Check if this relationship is implied by a given.
365 ty::ReEarlyBound(_) | ty::ReFree(_) => {
366 if self.data.givens.contains(&(a_region, b_vid)) {
376 VarValue::Empty(empty_ui) => {
377 let lub = match self.lub_empty(a_region) {
379 // If this empty region is from a universe that can
380 // name the placeholder, then the placeholder is
381 // larger; otherwise, the only ancestor is `'static`.
382 Err(placeholder) if empty_ui.can_name(placeholder.universe) => {
383 self.tcx().mk_region(RePlaceholder(placeholder))
385 Err(_) => self.tcx().lifetimes.re_static,
388 debug!("Expanding value of {:?} from empty lifetime to {:?}", b_vid, lub);
390 *b_data = VarValue::Value(lub);
393 VarValue::Value(cur_region) => {
394 // This is a specialized version of the `lub_concrete_regions`
395 // check below for a common case, here purely as an
397 let b_universe = self.var_infos[b_vid].universe;
399 let mut lub = self.lub_concrete_regions(a_region, cur_region);
400 if lub == cur_region {
404 // Watch out for `'b: !1` relationships, where the
405 // universe of `'b` can't name the placeholder `!1`. In
406 // that case, we have to grow `'b` to be `'static` for the
407 // relationship to hold. This is obviously a kind of sub-optimal
408 // choice -- in the future, when we incorporate a knowledge
409 // of the parameter environment, we might be able to find a
410 // tighter bound than `'static`.
412 // (This might e.g. arise from being asked to prove `for<'a> { 'b: 'a }`.)
413 if let ty::RePlaceholder(p) = *lub && b_universe.cannot_name(p.universe) {
414 lub = self.tcx().lifetimes.re_static;
417 debug!("Expanding value of {:?} from {:?} to {:?}", b_vid, cur_region, lub);
419 *b_data = VarValue::Value(lub);
423 VarValue::ErrorValue => false,
427 /// True if `a <= b`.
428 fn sub_region_values(&self, a: VarValue<'tcx>, b: VarValue<'tcx>) -> bool {
430 // Error region is `'static`
431 (VarValue::ErrorValue, _) | (_, VarValue::ErrorValue) => return true,
432 (VarValue::Empty(a_ui), VarValue::Empty(b_ui)) => {
433 // Empty regions are ordered according to the universe
434 // they are associated with.
435 a_ui.min(b_ui) == b_ui
437 (VarValue::Value(a), VarValue::Empty(_)) => {
439 ReLateBound(..) | ReErased => {
440 bug!("cannot relate region: {:?}", a);
445 self.var_infos[v_id].origin.span(),
446 "lub_concrete_regions invoked with non-concrete region: {:?}",
451 ReStatic | ReEarlyBound(_) | ReFree(_) => {
452 // nothing lives longer than `'static`
454 // All empty regions are less than early-bound, free,
455 // and scope regions.
460 RePlaceholder(_) => {
461 // The LUB is either `a` or `'static`
466 (VarValue::Empty(a_ui), VarValue::Value(b)) => {
468 ReLateBound(..) | ReErased => {
469 bug!("cannot relate region: {:?}", b);
474 self.var_infos[v_id].origin.span(),
475 "lub_concrete_regions invoked with non-concrete regions: {:?}",
480 ReStatic | ReEarlyBound(_) | ReFree(_) => {
481 // nothing lives longer than `'static`
482 // All empty regions are less than early-bound, free,
483 // and scope regions.
487 RePlaceholder(placeholder) => {
488 // If this empty region is from a universe that can
489 // name the placeholder, then the placeholder is
490 // larger; otherwise, the only ancestor is `'static`.
491 return a_ui.can_name(placeholder.universe);
495 (VarValue::Value(a), VarValue::Value(b)) => self.sub_concrete_regions(a, b),
499 /// True if `a <= b`, but not defined over inference variables.
500 #[instrument(level = "trace", skip(self))]
501 fn sub_concrete_regions(&self, a: Region<'tcx>, b: Region<'tcx>) -> bool {
502 let tcx = self.tcx();
503 let sub_free_regions = |r1, r2| self.region_rels.free_regions.sub_free_regions(tcx, r1, r2);
505 // Check for the case where we know that `'b: 'static` -- in that case,
506 // `a <= b` for all `a`.
507 let b_free_or_static = b.is_free_or_static();
508 if b_free_or_static && sub_free_regions(tcx.lifetimes.re_static, b) {
512 // If both `a` and `b` are free, consult the declared
513 // relationships. Note that this can be more precise than the
514 // `lub` relationship defined below, since sometimes the "lub"
515 // is actually the `postdom_upper_bound` (see
516 // `TransitiveRelation` for more details).
517 let a_free_or_static = a.is_free_or_static();
518 if a_free_or_static && b_free_or_static {
519 return sub_free_regions(a, b);
522 // For other cases, leverage the LUB code to find the LUB and
523 // check if it is equal to `b`.
524 self.lub_concrete_regions(a, b) == b
527 /// Returns the least-upper-bound of `a` and `b`; i.e., the
528 /// smallest region `c` such that `a <= c` and `b <= c`.
530 /// Neither `a` nor `b` may be an inference variable (hence the
531 /// term "concrete regions").
532 #[instrument(level = "trace", skip(self), ret)]
533 fn lub_concrete_regions(&self, a: Region<'tcx>, b: Region<'tcx>) -> Region<'tcx> {
535 (ReLateBound(..), _) | (_, ReLateBound(..)) | (ReErased, _) | (_, ReErased) => {
536 bug!("cannot relate region: LUB({:?}, {:?})", a, b);
539 (ReVar(v_id), _) | (_, ReVar(v_id)) => {
541 self.var_infos[v_id].origin.span(),
542 "lub_concrete_regions invoked with non-concrete \
543 regions: {:?}, {:?}",
549 (ReStatic, _) | (_, ReStatic) => {
550 // nothing lives longer than `'static`
551 self.tcx().lifetimes.re_static
554 (ReEarlyBound(_) | ReFree(_), ReEarlyBound(_) | ReFree(_)) => {
555 self.region_rels.lub_free_regions(a, b)
558 // For these types, we cannot define any additional
560 (RePlaceholder(..), _) | (_, RePlaceholder(..)) => {
564 self.tcx().lifetimes.re_static
570 /// After expansion is complete, go and check upper bounds (i.e.,
571 /// cases where the region cannot grow larger than a fixed point)
572 /// and check that they are satisfied.
573 #[instrument(skip(self, var_data, errors))]
576 var_data: &mut LexicalRegionResolutions<'tcx>,
577 errors: &mut Vec<RegionResolutionError<'tcx>>,
579 for (constraint, origin) in &self.data.constraints {
580 debug!(?constraint, ?origin);
582 Constraint::RegSubVar(..) | Constraint::VarSubVar(..) => {
583 // Expansion will ensure that these constraints hold. Ignore.
586 Constraint::RegSubReg(sub, sup) => {
587 if self.sub_concrete_regions(sub, sup) {
592 "region error at {:?}: \
593 cannot verify that {:?} <= {:?}",
597 errors.push(RegionResolutionError::ConcreteFailure(
604 Constraint::VarSubReg(a_vid, b_region) => {
605 let a_data = var_data.value_mut(a_vid);
606 debug!("contraction: {:?} == {:?}, {:?}", a_vid, a_data, b_region);
608 let VarValue::Value(a_region) = *a_data else {
612 // Do not report these errors immediately:
613 // instead, set the variable value to error and
614 // collect them later.
615 if !self.sub_concrete_regions(a_region, b_region) {
617 "region error at {:?}: \
618 cannot verify that {:?}={:?} <= {:?}",
619 origin, a_vid, a_region, b_region
621 *a_data = VarValue::ErrorValue;
627 for verify in &self.data.verifys {
628 debug!("collect_errors: verify={:?}", verify);
629 let sub = var_data.normalize(self.tcx(), verify.region);
631 let verify_kind_ty = verify.kind.to_ty(self.tcx());
632 let verify_kind_ty = var_data.normalize(self.tcx(), verify_kind_ty);
633 if self.bound_is_met(&verify.bound, var_data, verify_kind_ty, sub) {
638 "collect_errors: region error at {:?}: \
639 cannot verify that {:?} <= {:?}",
640 verify.origin, verify.region, verify.bound
643 errors.push(RegionResolutionError::GenericBoundFailure(
644 verify.origin.clone(),
651 /// Go over the variables that were declared to be error variables
652 /// and create a `RegionResolutionError` for each of them.
653 fn collect_var_errors(
655 var_data: &LexicalRegionResolutions<'tcx>,
656 graph: &RegionGraph<'tcx>,
657 errors: &mut Vec<RegionResolutionError<'tcx>>,
659 debug!("collect_var_errors, var_data = {:#?}", var_data.values);
661 // This is the best way that I have found to suppress
662 // duplicate and related errors. Basically we keep a set of
663 // flags for every node. Whenever an error occurs, we will
664 // walk some portion of the graph looking to find pairs of
665 // conflicting regions to report to the user. As we walk, we
666 // trip the flags from false to true, and if we find that
667 // we've already reported an error involving any particular
668 // node we just stop and don't report the current error. The
669 // idea is to report errors that derive from independent
670 // regions of the graph, but not those that derive from
671 // overlapping locations.
672 let mut dup_vec = IndexVec::from_elem_n(None, self.num_vars());
674 for (node_vid, value) in var_data.values.iter_enumerated() {
676 VarValue::Empty(_) | VarValue::Value(_) => { /* Inference successful */ }
677 VarValue::ErrorValue => {
678 // Inference impossible: this value contains
679 // inconsistent constraints.
681 // I think that in this case we should report an
682 // error now -- unlike the case above, we can't
683 // wait to see whether the user needs the result
684 // of this variable. The reason is that the mere
685 // existence of this variable implies that the
686 // region graph is inconsistent, whether or not it
689 // For example, we may have created a region
690 // variable that is the GLB of two other regions
691 // which do not have a GLB. Even if that variable
692 // is not used, it implies that those two regions
693 // *should* have a GLB.
695 // At least I think this is true. It may be that
696 // the mere existence of a conflict in a region
697 // variable that is not used is not a problem, so
698 // if this rule starts to create problems we'll
699 // have to revisit this portion of the code and
700 // think hard about it. =) -- nikomatsakis
702 // Obtain the spans for all the places that can
703 // influence the constraints on this value for
704 // richer diagnostics in `static_impl_trait`.
706 self.collect_error_for_expanding_node(graph, &mut dup_vec, node_vid, errors);
712 fn construct_graph(&self) -> RegionGraph<'tcx> {
713 let num_vars = self.num_vars();
715 let mut graph = Graph::new();
717 for _ in 0..num_vars {
721 // Issue #30438: two distinct dummy nodes, one for incoming
722 // edges (dummy_source) and another for outgoing edges
723 // (dummy_sink). In `dummy -> a -> b -> dummy`, using one
724 // dummy node leads one to think (erroneously) there exists a
725 // path from `b` to `a`. Two dummy nodes sidesteps the issue.
726 let dummy_source = graph.add_node(());
727 let dummy_sink = graph.add_node(());
729 for constraint in self.data.constraints.keys() {
731 Constraint::VarSubVar(a_id, b_id) => {
733 NodeIndex(a_id.index() as usize),
734 NodeIndex(b_id.index() as usize),
738 Constraint::RegSubVar(_, b_id) => {
739 graph.add_edge(dummy_source, NodeIndex(b_id.index() as usize), *constraint);
741 Constraint::VarSubReg(a_id, _) => {
742 graph.add_edge(NodeIndex(a_id.index() as usize), dummy_sink, *constraint);
744 Constraint::RegSubReg(..) => {
745 // this would be an edge from `dummy_source` to
746 // `dummy_sink`; just ignore it.
754 fn collect_error_for_expanding_node(
756 graph: &RegionGraph<'tcx>,
757 dup_vec: &mut IndexVec<RegionVid, Option<RegionVid>>,
759 errors: &mut Vec<RegionResolutionError<'tcx>>,
761 // Errors in expanding nodes result from a lower-bound that is
762 // not contained by an upper-bound.
763 let (mut lower_bounds, lower_vid_bounds, lower_dup) =
764 self.collect_bounding_regions(graph, node_idx, INCOMING, Some(dup_vec));
765 let (mut upper_bounds, _, upper_dup) =
766 self.collect_bounding_regions(graph, node_idx, OUTGOING, Some(dup_vec));
768 if lower_dup || upper_dup {
772 // We place free regions first because we are special casing
773 // SubSupConflict(ReFree, ReFree) when reporting error, and so
774 // the user will more likely get a specific suggestion.
775 fn region_order_key(x: &RegionAndOrigin<'_>) -> u8 {
777 ReEarlyBound(_) => 0,
782 lower_bounds.sort_by_key(region_order_key);
783 upper_bounds.sort_by_key(region_order_key);
785 let node_universe = self.var_infos[node_idx].universe;
787 for lower_bound in &lower_bounds {
788 let effective_lower_bound = if let ty::RePlaceholder(p) = *lower_bound.region {
789 if node_universe.cannot_name(p.universe) {
790 self.tcx().lifetimes.re_static
798 for upper_bound in &upper_bounds {
799 if !self.sub_concrete_regions(effective_lower_bound, upper_bound.region) {
800 let origin = self.var_infos[node_idx].origin;
802 "region inference error at {:?} for {:?}: SubSupConflict sub: {:?} \
804 origin, node_idx, lower_bound.region, upper_bound.region
807 errors.push(RegionResolutionError::SubSupConflict(
810 lower_bound.origin.clone(),
812 upper_bound.origin.clone(),
821 // If we have a scenario like `exists<'a> { forall<'b> { 'b:
822 // 'a } }`, we wind up without any lower-bound -- all we have
823 // are placeholders as upper bounds, but the universe of the
824 // variable `'a`, or some variable that `'a` has to outlive, doesn't
825 // permit those placeholders.
827 // We only iterate to find the min, which means it doesn't cause reproducibility issues
828 #[allow(rustc::potential_query_instability)]
829 let min_universe = lower_vid_bounds
831 .map(|vid| self.var_infos[vid].universe)
833 .expect("lower_vid_bounds should at least include `node_idx`");
835 for upper_bound in &upper_bounds {
836 if let ty::RePlaceholder(p) = *upper_bound.region {
837 if min_universe.cannot_name(p.universe) {
838 let origin = self.var_infos[node_idx].origin;
839 errors.push(RegionResolutionError::UpperBoundUniverseConflict(
843 upper_bound.origin.clone(),
851 // Errors in earlier passes can yield error variables without
852 // resolution errors here; delay ICE in favor of those errors.
853 self.tcx().sess.delay_span_bug(
854 self.var_infos[node_idx].origin.span(),
856 "collect_error_for_expanding_node() could not find \
857 error for var {:?} in universe {:?}, lower_bounds={:#?}, \
859 node_idx, node_universe, lower_bounds, upper_bounds
864 /// Collects all regions that "bound" the variable `orig_node_idx` in the
867 /// If `dup_vec` is `Some` it's used to track duplicates between successive
868 /// calls of this function.
870 /// The return tuple fields are:
871 /// - a list of all concrete regions bounding the given region.
872 /// - the set of all region variables bounding the given region.
873 /// - a `bool` that's true if the returned region variables overlap with
874 /// those returned by a previous call for another region.
875 fn collect_bounding_regions(
877 graph: &RegionGraph<'tcx>,
878 orig_node_idx: RegionVid,
880 mut dup_vec: Option<&mut IndexVec<RegionVid, Option<RegionVid>>>,
881 ) -> (Vec<RegionAndOrigin<'tcx>>, FxHashSet<RegionVid>, bool) {
882 struct WalkState<'tcx> {
883 set: FxHashSet<RegionVid>,
884 stack: Vec<RegionVid>,
885 result: Vec<RegionAndOrigin<'tcx>>,
888 let mut state = WalkState {
889 set: Default::default(),
890 stack: vec![orig_node_idx],
894 state.set.insert(orig_node_idx);
896 // to start off the process, walk the source node in the
897 // direction specified
898 process_edges(&self.data, &mut state, graph, orig_node_idx, dir);
900 while let Some(node_idx) = state.stack.pop() {
901 // check whether we've visited this node on some previous walk
902 if let Some(dup_vec) = &mut dup_vec {
903 if dup_vec[node_idx].is_none() {
904 dup_vec[node_idx] = Some(orig_node_idx);
905 } else if dup_vec[node_idx] != Some(orig_node_idx) {
906 state.dup_found = true;
910 "collect_concrete_regions(orig_node_idx={:?}, node_idx={:?})",
911 orig_node_idx, node_idx
915 process_edges(&self.data, &mut state, graph, node_idx, dir);
918 let WalkState { result, dup_found, set, .. } = state;
919 return (result, set, dup_found);
921 fn process_edges<'tcx>(
922 this: &RegionConstraintData<'tcx>,
923 state: &mut WalkState<'tcx>,
924 graph: &RegionGraph<'tcx>,
925 source_vid: RegionVid,
928 debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir);
930 let source_node_index = NodeIndex(source_vid.index() as usize);
931 for (_, edge) in graph.adjacent_edges(source_node_index, dir) {
933 Constraint::VarSubVar(from_vid, to_vid) => {
934 let opp_vid = if from_vid == source_vid { to_vid } else { from_vid };
935 if state.set.insert(opp_vid) {
936 state.stack.push(opp_vid);
940 Constraint::RegSubVar(region, _) | Constraint::VarSubReg(_, region) => {
941 state.result.push(RegionAndOrigin {
943 origin: this.constraints.get(&edge.data).unwrap().clone(),
947 Constraint::RegSubReg(..) => panic!(
948 "cannot reach reg-sub-reg edge in region inference \
958 bound: &VerifyBound<'tcx>,
959 var_values: &LexicalRegionResolutions<'tcx>,
960 generic_ty: Ty<'tcx>,
961 min: ty::Region<'tcx>,
964 VerifyBound::IfEq(verify_if_eq_b) => {
965 let verify_if_eq_b = var_values.normalize(self.region_rels.tcx, *verify_if_eq_b);
966 match test_type_match::extract_verify_if_eq(
973 self.bound_is_met(&VerifyBound::OutlivedBy(r), var_values, generic_ty, min)
980 VerifyBound::OutlivedBy(r) => {
982 ty::ReVar(rid) => var_values.values[rid],
983 _ => VarValue::Value(min),
986 ty::ReVar(rid) => var_values.values[rid],
987 _ => VarValue::Value(*r),
989 self.sub_region_values(a, b)
992 VerifyBound::IsEmpty => match *min {
993 ty::ReVar(rid) => match var_values.values[rid] {
994 VarValue::ErrorValue => false,
995 VarValue::Empty(_) => true,
996 VarValue::Value(_) => false,
1001 VerifyBound::AnyBound(bs) => {
1002 bs.iter().any(|b| self.bound_is_met(b, var_values, generic_ty, min))
1005 VerifyBound::AllBounds(bs) => {
1006 bs.iter().all(|b| self.bound_is_met(b, var_values, generic_ty, min))
1012 impl<'tcx> fmt::Debug for RegionAndOrigin<'tcx> {
1013 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1014 write!(f, "RegionAndOrigin({:?},{:?})", self.region, self.origin)
1018 impl<'tcx> LexicalRegionResolutions<'tcx> {
1019 fn normalize<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1021 T: TypeFoldable<'tcx>,
1023 tcx.fold_regions(value, |r, _db| self.resolve_region(tcx, r))
1026 fn value(&self, rid: RegionVid) -> &VarValue<'tcx> {
1030 fn value_mut(&mut self, rid: RegionVid) -> &mut VarValue<'tcx> {
1031 &mut self.values[rid]
1034 pub(crate) fn resolve_region(
1037 r: ty::Region<'tcx>,
1038 ) -> ty::Region<'tcx> {
1039 let result = match *r {
1040 ty::ReVar(rid) => match self.values[rid] {
1041 VarValue::Empty(_) => r,
1042 VarValue::Value(r) => r,
1043 VarValue::ErrorValue => tcx.lifetimes.re_static,
1047 debug!("resolve_region({:?}) = {:?}", r, result);