3 use self::CombineMapType::*;
7 use super::{MiscVariable, RegionVariableOrigin, SubregionOrigin};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_data_structures::indexed_vec::IndexVec;
11 use rustc_data_structures::unify as ut;
12 use crate::ty::ReStatic;
13 use crate::ty::{self, Ty, TyCtxt};
14 use crate::ty::{BrFresh, ReLateBound, ReVar};
15 use crate::ty::{Region, RegionVid};
17 use std::collections::BTreeMap;
18 use std::{cmp, fmt, mem, u32};
21 pub struct RegionConstraintCollector<'tcx> {
22 /// For each `RegionVid`, the corresponding `RegionVariableOrigin`.
23 var_infos: IndexVec<RegionVid, RegionVariableInfo>,
25 data: RegionConstraintData<'tcx>,
27 /// For a given pair of regions (R1, R2), maps to a region R3 that
28 /// is designated as their LUB (edges R1 <= R3 and R2 <= R3
29 /// exist). This prevents us from making many such regions.
30 lubs: CombineMap<'tcx>,
32 /// For a given pair of regions (R1, R2), maps to a region R3 that
33 /// is designated as their GLB (edges R3 <= R1 and R3 <= R2
34 /// exist). This prevents us from making many such regions.
35 glbs: CombineMap<'tcx>,
37 /// Global counter used during the GLB algorithm to create unique
38 /// names for fresh bound regions
41 /// The undo log records actions that might later be undone.
43 /// Note: `num_open_snapshots` is used to track if we are actively
44 /// snapshotting. When the `start_snapshot()` method is called, we
45 /// increment `num_open_snapshots` to indicate that we are now actively
46 /// snapshotting. The reason for this is that otherwise we end up adding
47 /// entries for things like the lower bound on a variable and so forth,
48 /// which can never be rolled back.
49 undo_log: Vec<UndoLog<'tcx>>,
51 /// The number of open snapshots, i.e., those that haven't been committed or
53 num_open_snapshots: usize,
55 /// When we add a R1 == R2 constriant, we currently add (a) edges
56 /// R1 <= R2 and R2 <= R1 and (b) we unify the two regions in this
57 /// table. You can then call `opportunistic_resolve_var` early
58 /// which will map R1 and R2 to some common region (i.e., either
59 /// R1 or R2). This is important when dropck and other such code
60 /// is iterating to a fixed point, because otherwise we sometimes
61 /// would wind up with a fresh stream of region variables that
62 /// have been equated but appear distinct.
63 unification_table: ut::UnificationTable<ut::InPlace<ty::RegionVid>>,
65 /// a flag set to true when we perform any unifications; this is used
66 /// to micro-optimize `take_and_reset_data`
67 any_unifications: bool,
70 pub type VarInfos = IndexVec<RegionVid, RegionVariableInfo>;
72 /// The full set of region constraints gathered up by the collector.
73 /// Describes constraints between the region variables and other
74 /// regions, as well as other conditions that must be verified, or
75 /// assumptions that can be made.
76 #[derive(Debug, Default, Clone)]
77 pub struct RegionConstraintData<'tcx> {
78 /// Constraints of the form `A <= B`, where either `A` or `B` can
79 /// be a region variable (or neither, as it happens).
80 pub constraints: BTreeMap<Constraint<'tcx>, SubregionOrigin<'tcx>>,
82 /// A "verify" is something that we need to verify after inference
83 /// is done, but which does not directly affect inference in any
86 /// An example is a `A <= B` where neither `A` nor `B` are
87 /// inference variables.
88 pub verifys: Vec<Verify<'tcx>>,
90 /// A "given" is a relationship that is known to hold. In
91 /// particular, we often know from closure fn signatures that a
92 /// particular free region must be a subregion of a region
95 /// foo.iter().filter(<'a> |x: &'a &'b T| ...)
97 /// In situations like this, `'b` is in fact a region variable
98 /// introduced by the call to `iter()`, and `'a` is a bound region
99 /// on the closure (as indicated by the `<'a>` prefix). If we are
100 /// naive, we wind up inferring that `'b` must be `'static`,
101 /// because we require that it be greater than `'a` and we do not
102 /// know what `'a` is precisely.
104 /// This hashmap is used to avoid that naive scenario. Basically
105 /// we record the fact that `'a <= 'b` is implied by the fn
106 /// signature, and then ignore the constraint when solving
107 /// equations. This is a bit of a hack but seems to work.
108 pub givens: FxHashSet<(Region<'tcx>, ty::RegionVid)>,
111 /// Represents a constraint that influences the inference process.
112 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
113 pub enum Constraint<'tcx> {
114 /// A region variable is a subregion of another.
115 VarSubVar(RegionVid, RegionVid),
117 /// A concrete region is a subregion of region variable.
118 RegSubVar(Region<'tcx>, RegionVid),
120 /// A region variable is a subregion of a concrete region. This does not
121 /// directly affect inference, but instead is checked after
122 /// inference is complete.
123 VarSubReg(RegionVid, Region<'tcx>),
125 /// A constraint where neither side is a variable. This does not
126 /// directly affect inference, but instead is checked after
127 /// inference is complete.
128 RegSubReg(Region<'tcx>, Region<'tcx>),
131 impl Constraint<'_> {
132 pub fn involves_placeholders(&self) -> bool {
134 Constraint::VarSubVar(_, _) => false,
135 Constraint::VarSubReg(_, r) | Constraint::RegSubVar(r, _) => r.is_placeholder(),
136 Constraint::RegSubReg(r, s) => r.is_placeholder() || s.is_placeholder(),
141 /// `VerifyGenericBound(T, _, R, RS)`: the parameter type `T` (or
142 /// associated type) must outlive the region `R`. `T` is known to
143 /// outlive `RS`. Therefore, verify that `R <= RS[i]` for some
144 /// `i`. Inference variables may be involved (but this verification
145 /// step doesn't influence inference).
146 #[derive(Debug, Clone)]
147 pub struct Verify<'tcx> {
148 pub kind: GenericKind<'tcx>,
149 pub origin: SubregionOrigin<'tcx>,
150 pub region: Region<'tcx>,
151 pub bound: VerifyBound<'tcx>,
154 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
155 pub enum GenericKind<'tcx> {
157 Projection(ty::ProjectionTy<'tcx>),
160 EnumTypeFoldableImpl! {
161 impl<'tcx> TypeFoldable<'tcx> for GenericKind<'tcx> {
162 (GenericKind::Param)(a),
163 (GenericKind::Projection)(a),
167 /// Describes the things that some `GenericKind` value `G` is known to
168 /// outlive. Each variant of `VerifyBound` can be thought of as a
171 /// fn(min: Region) -> bool { .. }
173 /// where `true` means that the region `min` meets that `G: min`.
174 /// (False means nothing.)
176 /// So, for example, if we have the type `T` and we have in scope that
177 /// `T: 'a` and `T: 'b`, then the verify bound might be:
179 /// fn(min: Region) -> bool {
180 /// ('a: min) || ('b: min)
183 /// This is described with a `AnyRegion('a, 'b)` node.
184 #[derive(Debug, Clone)]
185 pub enum VerifyBound<'tcx> {
186 /// Given a kind K and a bound B, expands to a function like the
187 /// following, where `G` is the generic for which this verify
188 /// bound was created:
191 /// fn(min) -> bool {
200 /// In other words, if the generic `G` that we are checking is
201 /// equal to `K`, then check the associated verify bound
202 /// (otherwise, false).
204 /// This is used when we have something in the environment that
205 /// may or may not be relevant, depending on the region inference
206 /// results. For example, we may have `where <T as
207 /// Trait<'a>>::Item: 'b` in our where-clauses. If we are
208 /// generating the verify-bound for `<T as Trait<'0>>::Item`, then
209 /// this where-clause is only relevant if `'0` winds up inferred
212 /// So we would compile to a verify-bound like
215 /// IfEq(<T as Trait<'a>>::Item, AnyRegion('a))
218 /// meaning, if the subject G is equal to `<T as Trait<'a>>::Item`
219 /// (after inference), and `'a: min`, then `G: min`.
220 IfEq(Ty<'tcx>, Box<VerifyBound<'tcx>>),
222 /// Given a region `R`, expands to the function:
225 /// fn(min) -> bool {
230 /// This is used when we can establish that `G: R` -- therefore,
231 /// if `R: min`, then by transitivity `G: min`.
232 OutlivedBy(Region<'tcx>),
234 /// Given a set of bounds `B`, expands to the function:
237 /// fn(min) -> bool {
238 /// exists (b in B) { b(min) }
242 /// In other words, if we meet some bound in `B`, that suffices.
243 /// This is used when all the bounds in `B` are known to apply to `G`.
244 AnyBound(Vec<VerifyBound<'tcx>>),
246 /// Given a set of bounds `B`, expands to the function:
249 /// fn(min) -> bool {
250 /// forall (b in B) { b(min) }
254 /// In other words, if we meet *all* bounds in `B`, that suffices.
255 /// This is used when *some* bound in `B` is known to suffice, but
256 /// we don't know which.
257 AllBounds(Vec<VerifyBound<'tcx>>),
260 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
261 struct TwoRegions<'tcx> {
266 #[derive(Copy, Clone, PartialEq)]
268 /// We added `RegionVid`.
271 /// We added the given `constraint`.
272 AddConstraint(Constraint<'tcx>),
274 /// We added the given `verify`.
277 /// We added the given `given`.
278 AddGiven(Region<'tcx>, ty::RegionVid),
280 /// We added a GLB/LUB "combination variable".
281 AddCombination(CombineMapType, TwoRegions<'tcx>),
283 /// During skolemization, we sometimes purge entries from the undo
284 /// log in a kind of minisnapshot (unlike other snapshots, this
285 /// purging actually takes place *on success*). In that case, we
286 /// replace the corresponding entry with `Noop` so as to avoid the
287 /// need to do a bunch of swapping. (We can't use `swap_remove` as
288 /// the order of the vector is important.)
292 #[derive(Copy, Clone, PartialEq)]
293 enum CombineMapType {
298 type CombineMap<'tcx> = FxHashMap<TwoRegions<'tcx>, RegionVid>;
300 #[derive(Debug, Clone, Copy)]
301 pub struct RegionVariableInfo {
302 pub origin: RegionVariableOrigin,
303 pub universe: ty::UniverseIndex,
306 pub struct RegionSnapshot {
308 region_snapshot: ut::Snapshot<ut::InPlace<ty::RegionVid>>,
309 any_unifications: bool,
312 /// When working with placeholder regions, we often wish to find all of
313 /// the regions that are either reachable from a placeholder region, or
314 /// which can reach a placeholder region, or both. We call such regions
315 /// *tainted* regions. This struct allows you to decide what set of
316 /// tainted regions you want.
318 pub struct TaintDirections {
323 impl TaintDirections {
324 pub fn incoming() -> Self {
331 pub fn outgoing() -> Self {
338 pub fn both() -> Self {
346 pub struct ConstraintInfo {}
348 impl<'tcx> RegionConstraintCollector<'tcx> {
349 pub fn new() -> Self {
353 pub fn num_region_vars(&self) -> usize {
357 pub fn region_constraint_data(&self) -> &RegionConstraintData<'tcx> {
361 /// Once all the constraints have been gathered, extract out the final data.
363 /// Not legal during a snapshot.
364 pub fn into_infos_and_data(self) -> (VarInfos, RegionConstraintData<'tcx>) {
365 assert!(!self.in_snapshot());
366 (self.var_infos, self.data)
369 /// Takes (and clears) the current set of constraints. Note that
370 /// the set of variables remains intact, but all relationships
371 /// between them are reset. This is used during NLL checking to
372 /// grab the set of constraints that arose from a particular
375 /// We don't want to leak relationships between variables between
376 /// points because just because (say) `r1 == r2` was true at some
377 /// point P in the graph doesn't imply that it will be true at
378 /// some other point Q, in NLL.
380 /// Not legal during a snapshot.
381 pub fn take_and_reset_data(&mut self) -> RegionConstraintData<'tcx> {
382 assert!(!self.in_snapshot());
384 // If you add a new field to `RegionConstraintCollector`, you
385 // should think carefully about whether it needs to be cleared
386 // or updated in some way.
387 let RegionConstraintCollector {
394 num_open_snapshots: _,
399 // Clear the tables of (lubs, glbs), so that we will create
400 // fresh regions if we do a LUB operation. As it happens,
401 // LUB/GLB are not performed by the MIR type-checker, which is
402 // the one that uses this method, but it's good to be correct.
406 // Clear all unifications and recreate the variables a "now
407 // un-unified" state. Note that when we unify `a` and `b`, we
408 // also insert `a <= b` and a `b <= a` edges, so the
409 // `RegionConstraintData` contains the relationship here.
410 if *any_unifications {
411 unification_table.reset_unifications(|vid| unify_key::RegionVidKey { min_vid: vid });
412 *any_unifications = false;
415 mem::replace(data, RegionConstraintData::default())
418 pub fn data(&self) -> &RegionConstraintData<'tcx> {
422 fn in_snapshot(&self) -> bool {
423 self.num_open_snapshots > 0
426 pub fn start_snapshot(&mut self) -> RegionSnapshot {
427 let length = self.undo_log.len();
428 debug!("RegionConstraintCollector: start_snapshot({})", length);
429 self.num_open_snapshots += 1;
432 region_snapshot: self.unification_table.snapshot(),
433 any_unifications: self.any_unifications,
437 fn assert_open_snapshot(&self, snapshot: &RegionSnapshot) {
438 assert!(self.undo_log.len() >= snapshot.length);
439 assert!(self.num_open_snapshots > 0);
442 pub fn commit(&mut self, snapshot: RegionSnapshot) {
443 debug!("RegionConstraintCollector: commit({})", snapshot.length);
444 self.assert_open_snapshot(&snapshot);
446 if self.num_open_snapshots == 1 {
447 // The root snapshot. It's safe to clear the undo log because
448 // there's no snapshot further out that we might need to roll back
450 assert!(snapshot.length == 0);
451 self.undo_log.clear();
454 self.num_open_snapshots -= 1;
456 self.unification_table.commit(snapshot.region_snapshot);
459 pub fn rollback_to(&mut self, snapshot: RegionSnapshot) {
460 debug!("RegionConstraintCollector: rollback_to({:?})", snapshot);
461 self.assert_open_snapshot(&snapshot);
463 while self.undo_log.len() > snapshot.length {
464 let undo_entry = self.undo_log.pop().unwrap();
465 self.rollback_undo_entry(undo_entry);
468 self.num_open_snapshots -= 1;
470 self.unification_table.rollback_to(snapshot.region_snapshot);
471 self.any_unifications = snapshot.any_unifications;
474 fn rollback_undo_entry(&mut self, undo_entry: UndoLog<'tcx>) {
477 // nothing to do here
480 self.var_infos.pop().unwrap();
481 assert_eq!(self.var_infos.len(), vid.index() as usize);
483 AddConstraint(ref constraint) => {
484 self.data.constraints.remove(constraint);
486 AddVerify(index) => {
487 self.data.verifys.pop();
488 assert_eq!(self.data.verifys.len(), index);
490 AddGiven(sub, sup) => {
491 self.data.givens.remove(&(sub, sup));
493 AddCombination(Glb, ref regions) => {
494 self.glbs.remove(regions);
496 AddCombination(Lub, ref regions) => {
497 self.lubs.remove(regions);
502 pub fn new_region_var(
504 universe: ty::UniverseIndex,
505 origin: RegionVariableOrigin,
507 let vid = self.var_infos.push(RegionVariableInfo { origin, universe });
511 .new_key(unify_key::RegionVidKey { min_vid: vid });
512 assert_eq!(vid, u_vid);
513 if self.in_snapshot() {
514 self.undo_log.push(AddVar(vid));
517 "created new region variable {:?} with origin {:?}",
523 /// Returns the universe for the given variable.
524 pub fn var_universe(&self, vid: RegionVid) -> ty::UniverseIndex {
525 self.var_infos[vid].universe
528 /// Returns the origin for the given variable.
529 pub fn var_origin(&self, vid: RegionVid) -> RegionVariableOrigin {
530 self.var_infos[vid].origin
533 /// Removes all the edges to/from the placeholder regions that are
534 /// in `skols`. This is used after a higher-ranked operation
535 /// completes to remove all trace of the placeholder regions
536 /// created in that time.
537 pub fn pop_placeholders(&mut self, placeholders: &FxHashSet<ty::Region<'tcx>>) {
538 debug!("pop_placeholders(placeholders={:?})", placeholders);
540 assert!(self.in_snapshot());
542 let constraints_to_kill: Vec<usize> = self
547 .filter(|&(_, undo_entry)| kill_constraint(placeholders, undo_entry))
548 .map(|(index, _)| index)
551 for index in constraints_to_kill {
552 let undo_entry = mem::replace(&mut self.undo_log[index], Purged);
553 self.rollback_undo_entry(undo_entry);
558 fn kill_constraint<'tcx>(
559 placeholders: &FxHashSet<ty::Region<'tcx>>,
560 undo_entry: &UndoLog<'tcx>,
563 &AddConstraint(Constraint::VarSubVar(..)) => false,
564 &AddConstraint(Constraint::RegSubVar(a, _)) => placeholders.contains(&a),
565 &AddConstraint(Constraint::VarSubReg(_, b)) => placeholders.contains(&b),
566 &AddConstraint(Constraint::RegSubReg(a, b)) => {
567 placeholders.contains(&a) || placeholders.contains(&b)
569 &AddGiven(..) => false,
570 &AddVerify(_) => false,
571 &AddCombination(_, ref two_regions) => {
572 placeholders.contains(&two_regions.a) || placeholders.contains(&two_regions.b)
574 &AddVar(..) | &Purged => false,
581 tcx: TyCtxt<'_, '_, 'tcx>,
582 debruijn: ty::DebruijnIndex,
584 // Creates a fresh bound variable for use in GLB computations.
585 // See discussion of GLB computation in the large comment at
586 // the top of this file for more details.
588 // This computation is potentially wrong in the face of
589 // rollover. It's conceivable, if unlikely, that one might
590 // wind up with accidental capture for nested functions in
591 // that case, if the outer function had bound regions created
592 // a very long time before and the inner function somehow
593 // wound up rolling over such that supposedly fresh
594 // identifiers were in fact shadowed. For now, we just assert
595 // that there is no rollover -- eventually we should try to be
596 // robust against this possibility, either by checking the set
597 // of bound identifiers that appear in a given expression and
598 // ensure that we generate one that is distinct, or by
599 // changing the representation of bound regions in a fn
602 let sc = self.bound_count;
603 self.bound_count = sc + 1;
605 if sc >= self.bound_count {
606 bug!("rollover in RegionInference new_bound()");
609 tcx.mk_region(ReLateBound(debruijn, BrFresh(sc)))
612 fn add_constraint(&mut self, constraint: Constraint<'tcx>, origin: SubregionOrigin<'tcx>) {
613 // cannot add constraints once regions are resolved
615 "RegionConstraintCollector: add_constraint({:?})",
619 // never overwrite an existing (constraint, origin) - only insert one if it isn't
620 // present in the map yet. This prevents origins from outside the snapshot being
621 // replaced with "less informative" origins e.g., during calls to `can_eq`
622 let in_snapshot = self.in_snapshot();
623 let undo_log = &mut self.undo_log;
624 self.data.constraints.entry(constraint).or_insert_with(|| {
626 undo_log.push(AddConstraint(constraint));
632 fn add_verify(&mut self, verify: Verify<'tcx>) {
633 // cannot add verifys once regions are resolved
634 debug!("RegionConstraintCollector: add_verify({:?})", verify);
636 // skip no-op cases known to be satisfied
637 if let VerifyBound::AllBounds(ref bs) = verify.bound {
643 let index = self.data.verifys.len();
644 self.data.verifys.push(verify);
645 if self.in_snapshot() {
646 self.undo_log.push(AddVerify(index));
650 pub fn add_given(&mut self, sub: Region<'tcx>, sup: ty::RegionVid) {
651 // cannot add givens once regions are resolved
652 if self.data.givens.insert((sub, sup)) {
653 debug!("add_given({:?} <= {:?})", sub, sup);
655 if self.in_snapshot() {
656 self.undo_log.push(AddGiven(sub, sup));
661 pub fn make_eqregion(
663 origin: SubregionOrigin<'tcx>,
668 // Eventually, it would be nice to add direct support for
670 self.make_subregion(origin.clone(), sub, sup);
671 self.make_subregion(origin, sup, sub);
673 if let (ty::ReVar(sub), ty::ReVar(sup)) = (*sub, *sup) {
674 self.unification_table.union(sub, sup);
675 self.any_unifications = true;
680 pub fn make_subregion(
682 origin: SubregionOrigin<'tcx>,
686 // cannot add constraints once regions are resolved
688 "RegionConstraintCollector: make_subregion({:?}, {:?}) due to {:?}",
693 (&ReLateBound(..), _) | (_, &ReLateBound(..)) => {
696 "cannot relate bound region: {:?} <= {:?}",
702 // all regions are subregions of static, so we can ignore this
704 (&ReVar(sub_id), &ReVar(sup_id)) => {
705 self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin);
707 (_, &ReVar(sup_id)) => {
708 self.add_constraint(Constraint::RegSubVar(sub, sup_id), origin);
710 (&ReVar(sub_id), _) => {
711 self.add_constraint(Constraint::VarSubReg(sub_id, sup), origin);
714 self.add_constraint(Constraint::RegSubReg(sub, sup), origin);
719 /// See [`Verify::VerifyGenericBound`].
720 pub fn verify_generic_bound(
722 origin: SubregionOrigin<'tcx>,
723 kind: GenericKind<'tcx>,
725 bound: VerifyBound<'tcx>,
727 self.add_verify(Verify {
737 tcx: TyCtxt<'_, '_, 'tcx>,
738 origin: SubregionOrigin<'tcx>,
742 // cannot add constraints once regions are resolved
743 debug!("RegionConstraintCollector: lub_regions({:?}, {:?})", a, b);
745 (r @ &ReStatic, _) | (_, r @ &ReStatic) => {
746 r // nothing lives longer than static
753 _ => self.combine_vars(tcx, Lub, a, b, origin),
759 tcx: TyCtxt<'_, '_, 'tcx>,
760 origin: SubregionOrigin<'tcx>,
764 // cannot add constraints once regions are resolved
765 debug!("RegionConstraintCollector: glb_regions({:?}, {:?})", a, b);
767 (&ReStatic, r) | (r, &ReStatic) => {
768 r // static lives longer than everything else
775 _ => self.combine_vars(tcx, Glb, a, b, origin),
779 pub fn opportunistic_resolve_var(
781 tcx: TyCtxt<'_, '_, 'tcx>,
783 ) -> ty::Region<'tcx> {
784 let vid = self.unification_table.probe_value(rid).min_vid;
785 tcx.mk_region(ty::ReVar(vid))
788 fn combine_map(&mut self, t: CombineMapType) -> &mut CombineMap<'tcx> {
790 Glb => &mut self.glbs,
791 Lub => &mut self.lubs,
797 tcx: TyCtxt<'_, '_, 'tcx>,
801 origin: SubregionOrigin<'tcx>,
803 let vars = TwoRegions { a: a, b: b };
804 if let Some(&c) = self.combine_map(t).get(&vars) {
805 return tcx.mk_region(ReVar(c));
807 let a_universe = self.universe(a);
808 let b_universe = self.universe(b);
809 let c_universe = cmp::max(a_universe, b_universe);
810 let c = self.new_region_var(c_universe, MiscVariable(origin.span()));
811 self.combine_map(t).insert(vars, c);
812 if self.in_snapshot() {
813 self.undo_log.push(AddCombination(t, vars));
815 let new_r = tcx.mk_region(ReVar(c));
816 for &old_r in &[a, b] {
818 Glb => self.make_subregion(origin.clone(), new_r, old_r),
819 Lub => self.make_subregion(origin.clone(), old_r, new_r),
822 debug!("combine_vars() c={:?}", c);
826 fn universe(&self, region: Region<'tcx>) -> ty::UniverseIndex {
833 | ty::ReEarlyBound(..) => ty::UniverseIndex::ROOT,
834 ty::RePlaceholder(placeholder) => placeholder.universe,
835 ty::ReClosureBound(vid) | ty::ReVar(vid) => self.var_universe(vid),
836 ty::ReLateBound(..) => bug!("universe(): encountered bound region {:?}", region),
840 pub fn vars_created_since_snapshot(&self, mark: &RegionSnapshot) -> Vec<RegionVid> {
841 self.undo_log[mark.length..]
843 .filter_map(|&elt| match elt {
844 AddVar(vid) => Some(vid),
849 /// See [`RegionInference::region_constraints_added_in_snapshot`].
850 pub fn region_constraints_added_in_snapshot(&self, mark: &RegionSnapshot) -> Option<bool> {
851 self.undo_log[mark.length..]
853 .map(|&elt| match elt {
854 AddConstraint(constraint) => Some(constraint.involves_placeholders()),
861 impl fmt::Debug for RegionSnapshot {
862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863 write!(f, "RegionSnapshot(length={})", self.length)
867 impl<'tcx> fmt::Debug for GenericKind<'tcx> {
868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870 GenericKind::Param(ref p) => write!(f, "{:?}", p),
871 GenericKind::Projection(ref p) => write!(f, "{:?}", p),
876 impl<'tcx> fmt::Display for GenericKind<'tcx> {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879 GenericKind::Param(ref p) => write!(f, "{}", p),
880 GenericKind::Projection(ref p) => write!(f, "{}", p),
885 impl<'a, 'gcx, 'tcx> GenericKind<'tcx> {
886 pub fn to_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
888 GenericKind::Param(ref p) => p.to_ty(tcx),
889 GenericKind::Projection(ref p) => tcx.mk_projection(p.item_def_id, p.substs),
894 impl<'a, 'gcx, 'tcx> VerifyBound<'tcx> {
895 pub fn must_hold(&self) -> bool {
897 VerifyBound::IfEq(..) => false,
898 VerifyBound::OutlivedBy(ty::ReStatic) => true,
899 VerifyBound::OutlivedBy(_) => false,
900 VerifyBound::AnyBound(bs) => bs.iter().any(|b| b.must_hold()),
901 VerifyBound::AllBounds(bs) => bs.iter().all(|b| b.must_hold()),
905 pub fn cannot_hold(&self) -> bool {
907 VerifyBound::IfEq(_, b) => b.cannot_hold(),
908 VerifyBound::OutlivedBy(ty::ReEmpty) => true,
909 VerifyBound::OutlivedBy(_) => false,
910 VerifyBound::AnyBound(bs) => bs.iter().all(|b| b.cannot_hold()),
911 VerifyBound::AllBounds(bs) => bs.iter().any(|b| b.cannot_hold()),
915 pub fn or(self, vb: VerifyBound<'tcx>) -> VerifyBound<'tcx> {
916 if self.must_hold() || vb.cannot_hold() {
918 } else if self.cannot_hold() || vb.must_hold() {
921 VerifyBound::AnyBound(vec![self, vb])
925 pub fn and(self, vb: VerifyBound<'tcx>) -> VerifyBound<'tcx> {
926 if self.must_hold() && vb.must_hold() {
928 } else if self.cannot_hold() && vb.cannot_hold() {
931 VerifyBound::AllBounds(vec![self, vb])
936 impl<'tcx> RegionConstraintData<'tcx> {
937 /// Returns `true` if this region constraint data contains no constraints, and `false`
939 pub fn is_empty(&self) -> bool {
940 let RegionConstraintData {
945 constraints.is_empty() && verifys.is_empty() && givens.is_empty()